{
  "id": "task_libraries:backtesting/python",
  "path": "/exapedia/python-backtesting-libraries",
  "template": {
    "id": "task_libraries",
    "version": 4
  },
  "title": "Python backtesting libraries",
  "answer": [
    {
      "t": "text",
      "text": "Python backtesting libraries replay historical market data through a trading strategy to estimate how it would have performed. A vectorized engine computes signals across the whole price history at once rather than stepping through each bar. These libraries let quant developers test a strategy's returns and risk before it trades real money."
    }
  ],
  "breadcrumb": [
    {
      "label": "Tools"
    },
    {
      "label": "Python backtesting libraries"
    }
  ],
  "sections": [
    {
      "id": "libraries_popularity",
      "anchor": "popularity",
      "heading": "Popularity",
      "blocks": [
        {
          "b": "table",
          "columns": [
            "Library",
            "Monthly downloads",
            "Stars",
            "Last release",
            "License"
          ],
          "rows": [
            [
              [
                {
                  "t": "link",
                  "href": "#nautilus-trader",
                  "label": [
                    {
                      "t": "fact",
                      "fact": "F136"
                    }
                  ]
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F137"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F145"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F140"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F138"
                }
              ]
            ],
            [
              [
                {
                  "t": "link",
                  "href": "#vectorbt",
                  "label": [
                    {
                      "t": "fact",
                      "fact": "F150"
                    }
                  ]
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F151"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F157"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F154"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F152"
                }
              ]
            ],
            [
              [
                {
                  "t": "link",
                  "href": "#backtesting-py",
                  "label": [
                    {
                      "t": "fact",
                      "fact": "F168"
                    }
                  ]
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F169"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F175"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F172"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F170"
                }
              ]
            ],
            [
              [
                {
                  "t": "link",
                  "href": "#backtrader",
                  "label": [
                    {
                      "t": "fact",
                      "fact": "F185"
                    }
                  ]
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F186"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F192"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F189"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F187"
                }
              ]
            ],
            [
              [
                {
                  "t": "link",
                  "href": "#bt",
                  "label": [
                    {
                      "t": "fact",
                      "fact": "F200"
                    }
                  ]
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F201"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F207"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F204"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F202"
                }
              ]
            ],
            [
              [
                {
                  "t": "link",
                  "href": "#pyqlib",
                  "label": [
                    {
                      "t": "fact",
                      "fact": "F216"
                    }
                  ]
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F217"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F225"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F220"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F218"
                }
              ]
            ],
            [
              [
                {
                  "t": "link",
                  "href": "#lumibot",
                  "label": [
                    {
                      "t": "fact",
                      "fact": "F231"
                    }
                  ]
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F232"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F240"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F235"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F233"
                }
              ]
            ],
            [
              [
                {
                  "t": "link",
                  "href": "#lean",
                  "label": [
                    {
                      "t": "fact",
                      "fact": "F245"
                    }
                  ]
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F246"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F254"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F249"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F247"
                }
              ]
            ]
          ],
          "variant": "pop",
          "caption": [
            {
              "t": "text",
              "text": "Downloads: "
            },
            {
              "t": "text",
              "text": "PyPI"
            },
            {
              "t": "text",
              "text": ", last thirty days. Stars and releases: GitHub. Amber: no release in over a year."
            }
          ]
        }
      ],
      "note": [
        {
          "t": "link",
          "href": "#nautilus-trader",
          "label": [
            {
              "t": "text",
              "text": "NautilusTrader"
            }
          ]
        },
        {
          "t": "text",
          "text": " has the most monthly downloads in this comparison, at "
        },
        {
          "t": "fact",
          "fact": "F137"
        },
        {
          "t": "text",
          "text": "."
        }
      ]
    },
    {
      "id": "libraries_capabilities",
      "anchor": "capabilities",
      "heading": "Capabilities",
      "blocks": [
        {
          "b": "table",
          "columns": [
            "Library",
            "Multi-asset portfolios",
            "Live broker adapters"
          ],
          "rows": [
            [
              [
                {
                  "t": "link",
                  "href": "#nautilus-trader",
                  "label": [
                    {
                      "t": "fact",
                      "fact": "F136"
                    }
                  ]
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F146"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F147"
                }
              ]
            ],
            [
              [
                {
                  "t": "link",
                  "href": "#vectorbt",
                  "label": [
                    {
                      "t": "fact",
                      "fact": "F150"
                    }
                  ]
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F158"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F159"
                }
              ]
            ],
            [
              [
                {
                  "t": "link",
                  "href": "#backtesting-py",
                  "label": [
                    {
                      "t": "fact",
                      "fact": "F168"
                    }
                  ]
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F176"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F177"
                }
              ]
            ],
            [
              [
                {
                  "t": "link",
                  "href": "#backtrader",
                  "label": [
                    {
                      "t": "fact",
                      "fact": "F185"
                    }
                  ]
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F193"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F194"
                }
              ]
            ],
            [
              [
                {
                  "t": "link",
                  "href": "#bt",
                  "label": [
                    {
                      "t": "fact",
                      "fact": "F200"
                    }
                  ]
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F208"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F209"
                }
              ]
            ],
            [
              [
                {
                  "t": "link",
                  "href": "#pyqlib",
                  "label": [
                    {
                      "t": "fact",
                      "fact": "F216"
                    }
                  ]
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F226"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F227"
                }
              ]
            ],
            [
              [
                {
                  "t": "link",
                  "href": "#lumibot",
                  "label": [
                    {
                      "t": "fact",
                      "fact": "F231"
                    }
                  ]
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F241"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F242"
                }
              ]
            ],
            [
              [
                {
                  "t": "link",
                  "href": "#lean",
                  "label": [
                    {
                      "t": "fact",
                      "fact": "F245"
                    }
                  ]
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F255"
                }
              ],
              [
                {
                  "t": "fact",
                  "fact": "F256"
                }
              ]
            ]
          ],
          "variant": "cap"
        }
      ]
    },
    {
      "id": "libraries_entries",
      "anchor": "libraries",
      "heading": "Libraries",
      "blocks": [
        {
          "b": "entry",
          "anchor": "nautilus-trader",
          "name": [
            {
              "t": "fact",
              "fact": "F136"
            }
          ],
          "links": [
            {
              "label": "GitHub",
              "href": "https://github.com/nautechsystems/nautilus_trader"
            },
            {
              "label": "PyPI",
              "href": "https://pypi.org/project/nautilus-trader"
            },
            {
              "label": "Docs",
              "href": "https://pypi.org/project/nautilus-trader/"
            }
          ],
          "what": [
            {
              "t": "fact",
              "fact": "F143"
            }
          ],
          "facts": [
            {
              "label": "Downloads / mo",
              "value": [
                {
                  "t": "fact",
                  "fact": "F137"
                }
              ]
            },
            {
              "label": "Stars",
              "value": [
                {
                  "t": "fact",
                  "fact": "F145"
                }
              ]
            },
            {
              "label": "Last release",
              "value": [
                {
                  "t": "fact",
                  "fact": "F139"
                }
              ]
            },
            {
              "label": "License",
              "value": [
                {
                  "t": "fact",
                  "fact": "F138"
                }
              ]
            },
            {
              "label": "Capabilities",
              "value": [
                {
                  "t": "link",
                  "href": "https://pypi.org/project/nautilus-trader/",
                  "label": [
                    {
                      "t": "text",
                      "text": "From the "
                    },
                    {
                      "t": "fact",
                      "fact": "F136"
                    },
                    {
                      "t": "text",
                      "text": " docs"
                    }
                  ]
                }
              ]
            }
          ],
          "pros": [],
          "cons": [],
          "tabs": [
            {
              "label": [
                {
                  "t": "text",
                  "text": "Quickstart"
                }
              ],
              "language": "python",
              "code": "# %% [markdown]\n# # Backtest (Low-Level API)\n#\n# Use `BacktestEngine` for direct component access: load market data, wire up\n# strategies and execution algorithms, and run backtests with full control over\n# every step. This tutorial backtests an EMA cross strategy with a TWAP execution\n# algorithm on a simulated Binance Spot exchange using historical trade tick data.\n#\n# [View source on GitHub](https://github.com/nautechsystems/nautilus_trader/blob/develop/docs/getting_started/backtest_low_level.py).\n\n# %% [markdown]\n# ## Prerequisites\n# - Python 3.12+\n# - [NautilusTrader](https://pypi.org/project/nautilus_trader/) latest release installed (`pip install nautilus_trader`)\n\n# %%\nfrom decimal import Decimal\n\nfrom nautilus_trader.backtest.config import BacktestEngineConfig\nfrom nautilus_trader.backtest.engine import BacktestEngine\nfrom nautilus_trader.examples.algorithms.twap import TWAPExecAlgorithm\nfrom nautilus_trader.examples.strategies.ema_cross_twap import EMACrossTWAP\nfrom nautilus_trader.examples.strategies.ema_cross_twap import EMACrossTWAPConfig\nfrom nautilus_trader.model import BarType\nfrom nautilus_trader.model import Money\nfrom nautilus_trader.model import TraderId\nfrom nautilus_trader.model import Venue\nfrom nautilus_trader.model.currencies import ETH\nfrom nautilus_trader.model.currencies import USDT\nfrom nautilus_trader.model.enums import AccountType\nfrom nautilus_trader.model.enums import OmsType\nfrom nautilus_trader.persistence.wranglers import TradeTickDataWrangler\nfrom nautilus_trader.test_kit.providers import TestDataProvider\nfrom nautilus_trader.test_kit.providers import TestInstrumentProvider\n\n# %% [markdown]\n# ## Load data\n#\n# Load bundled test data (ETHUSDT trades from Binance), initialize the matching\n# instrument, and wrangle the raw CSV into Nautilus `TradeTick` objects.\n\n# %%\n# Load stub test data\nprovider = TestDataProvider()\ntrades_df = provider.read_csv_ticks(\"binance/ethusdt-trades.csv\")\n\n# Initialize the instrument which matches the data\nETHUSDT_BINANCE = TestInstrumentProvider.ethusdt_binance()\n\n# Process into Nautilus objects\nwrangler = TradeTickDataWrangler(instrument=ETHUSDT_BINANCE)\nticks = wrangler.process(trades_df)\n\n# %% [markdown]\n# See the [Data](../concepts/data.md) concept guide for details on the data processing pipeline.\n\n# %% [markdown]\n# ## Initialize the engine\n#\n# Pass a `BacktestEngineConfig` to configure the engine. Here we set a custom\n# `trader_id` to show the pattern.\n\n# %%\n# Configure backtest engine\nconfig = BacktestEngineConfig(trader_id=TraderId(\"BACKTESTER-001\"))\n\n# Build the backtest engine\nengine = BacktestEngine(config=config)\n\n# %% [markdown]\n# ## Add a venue\n#\n# Set up a simulated venue that matches the market data. Here we configure a\n# Binance Spot exchange with a cash account.\n\n# %%\n# Add a trading venue (multiple venues possible)\nBINANCE = Venue(\"BINANCE\")\nengine.add_venue(\n    venue=BINANCE,\n    oms_type=OmsType.NETTING,\n    account_type=AccountType.CASH,  # Spot CASH account (not for perpetuals or futures)\n    base_currency=None,  # Multi-currency account\n    starting_balances=[Money(1_000_000.0, USDT), Money(10.0, ETH)],\n)\n\n# %% [markdown]\n# ## Add data\n#\n# Add the instrument and trade ticks to the engine.\n\n# %%\n# Add instrument(s)\nengine.add_instrument(ETHUSDT_BINANCE)\n\n# Add data\nengine.add_data(ticks)\n\n# %% [markdown]\n# :::note\n# You can add multiple data types (including custom types) and backtest across multiple venues.\n# :::\n#\n\n# %% [markdown]\n# ## Add strategies\n#\n# Configure and add an EMA cross strategy with TWAP execution parameters.\n\n# %%\n# Configure your strategy\nstrategy_config = EMACrossTWAPConfig(\n    instrument_id=ETHUSDT_BINANCE.id,\n    bar_type=BarType.from_str(\"ETHUSDT.BINANCE-250-TICK-LAST-INTERNAL\"),\n    trade_size=Decimal(\"0.10\"),\n    fast_ema_period=10,\n    slow_ema_period=20,\n    twap_horizon_secs=10.0,\n    twap_interval_secs=2.5,\n)\n\n# Instantiate and add your strategy\nstrategy = EMACrossTWAP(config=strategy_config)\nengine.add_strategy(strategy=strategy)\n\n# %% [markdown]\n# The strategy config references TWAP parameters, but the execution algorithm\n# itself is a separate component.\n#\n# ## Add execution algorithms\n#\n# Add a TWAP execution algorithm to the engine.\n\n# %%\n# Instantiate and add your execution algorithm\nexec_algorithm = TWAPExecAlgorithm()  # Using defaults\nengine.add_exec_algorithm(exec_algorithm)\n\n# %% [markdown]\n# ## Run the backtest\n#\n# Call `.run()` to process all available data. The engine replays events in\n# timestamp order with deterministic execution semantics.\n\n# %%\n# Run the engine (from start to end of data)\nengine.run()\n\n# %% [markdown]\n# ## Post-run analysis\n#\n# The engine retains data and execution objects in memory for generating reports.\n# It also logs a tearsheet with default statistics; see the\n# [Portfolio statistics](../concepts/portfolio.md#portfolio-statistics) guide for\n# custom statistics.\n\n# %%\nengine.trader.generate_account_report(BINANCE)\n\n# %%\nengine.trader.generate_order_fills_report()\n\n# %%\nengine.trader.generate_positions_report()\n\n# %% [markdown]\n# ## Repeated runs\n#\n# Reset the engine for repeated runs. Instruments, data, and loaded components\n# persist across resets; loaded components have their internal state reset.\n\n# %%\n# For repeated backtest runs, reset the engine\nengine.reset()\n\n# Clear or remove loaded components before adding replacements.\n\n# %% [markdown]\n# Remove and add individual components (actors, strategies, execution algorithms) as required.\n#\n# See the [Trader](../api_reference/trading.md) API reference for a description of all methods available to achieve this.\n#\n\n# %%\n# Once done, good practice to dispose of the object if the script continues\nengine.dispose()\n",
              "prov": [
                {
                  "t": "text",
                  "text": "From "
                },
                {
                  "t": "link",
                  "href": "https://github.com/nautechsystems/nautilus_trader/blob/27a8e54e7ac3c57d6cbf8891f0283dfbaee97317/docs/getting_started/backtest_low_level.py",
                  "label": [
                    {
                      "t": "text",
                      "text": "backtest_low_level.py"
                    }
                  ]
                }
              ],
              "more": [
                {
                  "t": "link",
                  "href": "https://dashboard.exa.ai/playground/search?q=nautilus-trader%20GitHub%20projects",
                  "label": [
                    {
                      "t": "text",
                      "text": "Find projects using "
                    },
                    {
                      "t": "fact",
                      "fact": "F136"
                    },
                    {
                      "t": "text",
                      "text": " →"
                    }
                  ]
                }
              ]
            }
          ],
          "install": [
            {
              "t": "fact",
              "fact": "F141"
            }
          ]
        },
        {
          "b": "entry",
          "anchor": "vectorbt",
          "name": [
            {
              "t": "fact",
              "fact": "F150"
            }
          ],
          "links": [
            {
              "label": "GitHub",
              "href": "https://github.com/polakowo/vectorbt"
            },
            {
              "label": "PyPI",
              "href": "https://pypi.org/project/vectorbt"
            },
            {
              "label": "Docs",
              "href": "https://pypi.org/project/vectorbt/"
            }
          ],
          "what": [
            {
              "t": "fact",
              "fact": "F12"
            }
          ],
          "facts": [
            {
              "label": "Downloads / mo",
              "value": [
                {
                  "t": "fact",
                  "fact": "F151"
                }
              ]
            },
            {
              "label": "Stars",
              "value": [
                {
                  "t": "fact",
                  "fact": "F157"
                }
              ]
            },
            {
              "label": "Last release",
              "value": [
                {
                  "t": "fact",
                  "fact": "F153"
                }
              ]
            },
            {
              "label": "License",
              "value": [
                {
                  "t": "fact",
                  "fact": "F152"
                }
              ]
            },
            {
              "label": "Capabilities",
              "value": [
                {
                  "t": "link",
                  "href": "https://pypi.org/project/vectorbt/",
                  "label": [
                    {
                      "t": "text",
                      "text": "From the "
                    },
                    {
                      "t": "fact",
                      "fact": "F150"
                    },
                    {
                      "t": "text",
                      "text": " docs"
                    }
                  ]
                }
              ]
            }
          ],
          "pros": [
            {
              "lead": [
                {
                  "t": "fact",
                  "fact": "F13"
                }
              ],
              "body": [
                {
                  "t": "fact",
                  "fact": "F14"
                }
              ]
            },
            {
              "lead": [
                {
                  "t": "fact",
                  "fact": "F15"
                }
              ],
              "body": [
                {
                  "t": "fact",
                  "fact": "F16"
                }
              ]
            }
          ],
          "cons": [
            {
              "lead": [
                {
                  "t": "fact",
                  "fact": "F17"
                }
              ],
              "body": [
                {
                  "t": "fact",
                  "fact": "F18"
                }
              ]
            },
            {
              "lead": [
                {
                  "t": "fact",
                  "fact": "F19"
                }
              ],
              "body": [
                {
                  "t": "fact",
                  "fact": "F20"
                }
              ]
            }
          ],
          "tabs": [
            {
              "label": [
                {
                  "t": "fact",
                  "fact": "F166"
                }
              ],
              "stars": [
                {
                  "t": "fact",
                  "fact": "F167"
                }
              ],
              "usedBy": [
                {
                  "t": "link",
                  "href": "https://github.com/finlab-python/finlab_crypto",
                  "label": [
                    {
                      "t": "fact",
                      "fact": "F166"
                    }
                  ]
                },
                {
                  "t": "text",
                  "text": " "
                }
              ],
              "language": "python",
              "code": "def backtest(self, ohlcv, variables=None, filters=None, lookback=None, plot=False, signals=False,\n             side='long', cscv_nbins=10, cscv_objective=lambda r: r.mean(), html=None, compounded=True,\n             execution_price='close', k_colors='world', **args):\n    \"\"\"Backtest the strategy with vectorbt.\n\n    Args:\n      ohlcv: OHLCV DataFrame.\n      variables: Strategy parameters. Lists or arrays are optimised over;\n        ``sl_stop``, ``tp_stop``, ``ts_stop`` add stop-loss, take-profit\n        and trailing-stop exits.\n      filters: {name: Filter.create(...)} conditions for entries.\n      lookback: Only use the latest ``lookback`` bars.\n      plot: Show the interactive chart (one parameter set) or the\n        optimisation dashboard with overfitting analysis (many sets).\n      signals: Return ``(entries, exits, figures)`` instead of backtesting.\n      side: Only 'long' is supported.\n      cscv_nbins: Number of blocks for the overfitting analysis.\n      cscv_objective: Performance measure for the overfitting analysis.\n      html: Also save the interactive chart to this file.\n      compounded: Reinvest profits; otherwise trade a fixed size.\n      execution_price: 'close' trades at the signal bar's close, 'open'\n        at the next bar's open.\n      k_colors: Candle colors, 'world', 'taiwan' or\n        {'increasing_line': color, 'decreasing_line': color}.\n      **args: Passed to ``vbt.Portfolio.from_signals`` (ex: ``freq='4h'``, ``fees``).\n\n    Returns:\n      vbt.Portfolio\n    \"\"\"\n    if side == 'short':\n        raise NotImplementedError('Shorting is not supported yet')\n    if side != 'long':\n        raise ValueError(\"side should be 'long' or 'short'\")\n    if execution_price not in EXECUTION_PRICES:\n        raise ValueError(f'execution_price should be one of {EXECUTION_PRICES}')\n\n    variables = dict(variables or {})\n    stop_vars = {name: variables.pop(name) for name in STOP_VARIABLES if name in variables}\n    ohlcv = ohlcv.iloc[-lookback:] if lookback else ohlcv\n\n    parameter_sets = enumerate_variables(variables) or [self._default_parameters]\n    entries, exits, fig_data = enumerate_signal(ohlcv, self, parameter_sets)\n    if filters:\n        filter_results = {name: create(ohlcv) for name, create in filters.items()}\n        entries, exits, fig_data = self._add_filters(entries, exits, fig_data, filter_results)\n    entries, exits = stop_early(ohlcv, entries, exits, stop_vars)\n    entries, exits = entries.squeeze(axis=1), exits.squeeze(axis=1)\n\n    if signals:\n        return entries, exits, fig_data\n\n    if not compounded:\n        args['size'] = vbt.settings.portfolio['init_cash'] / ohlcv.close.iloc[0]\n    price = ohlcv.close if execution_price == 'close' else ohlcv.open.shift(-1)\n    portfolio = vbt.Portfolio.from_signals(price, _as_bool(entries), _as_bool(exits), **args)\n\n    if isinstance(entries, pd.Series):\n        if plot or html is not None:\n            plot_strategy(ohlcv, entries, exits, portfolio, fig_data, html=html, k_colors=k_colors)\n    elif plot:\n        cscv = CSCV(n_bins=cscv_nbins, objective=cscv_objective)\n        cscv.add_daily_returns(portfolio.daily_returns())\n        plot_combination(portfolio, cscv.estimate_overfitting())\n        plt.show()\n        variable_visualization(portfolio)\n\n    return portfolio",
              "prov": [
                {
                  "t": "link",
                  "href": "https://github.com/finlab-python/finlab_crypto/blob/2b3305fd6adacdf1732866d3e931e1fa061ebdf8/finlab_crypto/strategy.py#L100-L166",
                  "label": [
                    {
                      "t": "fact",
                      "fact": "F165"
                    }
                  ]
                }
              ],
              "more": [
                {
                  "t": "link",
                  "href": "https://dashboard.exa.ai/playground/search?q=Python%20applications%20using%20vectorbt%20for%20strategy%20simulation%20and%20portfolio%20allocation&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D",
                  "label": [
                    {
                      "t": "text",
                      "text": "More projects using "
                    },
                    {
                      "t": "fact",
                      "fact": "F150"
                    },
                    {
                      "t": "text",
                      "text": " →"
                    }
                  ]
                }
              ]
            },
            {
              "label": [
                {
                  "t": "text",
                  "text": "Quickstart"
                }
              ],
              "language": "python",
              "code": "import pandas as pd\nimport vectorbt as vbt\n\nclose = pd.Series(\n    [100.0, 102.0, 101.0, 104.0, 103.0, 107.0],\n    index=pd.date_range(\"2024-01-01\", periods=6, freq=\"D\"),\n    name=\"Close\",\n)\npf = vbt.Portfolio.from_holding(close, init_cash=1000, fees=0.001, freq=\"1D\")\nprint(round(float(pf.total_return()) * 100, 2))\n\n",
              "prov": [
                {
                  "t": "text",
                  "text": "From "
                },
                {
                  "t": "link",
                  "href": "https://vectorbt.dev/getting-started/usage/",
                  "label": [
                    {
                      "t": "text",
                      "text": "usage.md"
                    }
                  ]
                }
              ]
            }
          ],
          "install": [
            {
              "t": "fact",
              "fact": "F155"
            }
          ]
        },
        {
          "b": "entry",
          "anchor": "backtesting-py",
          "name": [
            {
              "t": "fact",
              "fact": "F168"
            }
          ],
          "links": [
            {
              "label": "GitHub",
              "href": "https://github.com/kernc/backtesting.py"
            },
            {
              "label": "PyPI",
              "href": "https://pypi.org/project/backtesting"
            },
            {
              "label": "Docs",
              "href": "https://kernc.github.io/backtesting.py/doc/backtesting/"
            }
          ],
          "what": [
            {
              "t": "fact",
              "fact": "F42"
            }
          ],
          "facts": [
            {
              "label": "Downloads / mo",
              "value": [
                {
                  "t": "fact",
                  "fact": "F169"
                }
              ]
            },
            {
              "label": "Stars",
              "value": [
                {
                  "t": "fact",
                  "fact": "F175"
                }
              ]
            },
            {
              "label": "Last release",
              "value": [
                {
                  "t": "fact",
                  "fact": "F171"
                }
              ]
            },
            {
              "label": "License",
              "value": [
                {
                  "t": "fact",
                  "fact": "F170"
                }
              ]
            },
            {
              "label": "Capabilities",
              "value": [
                {
                  "t": "link",
                  "href": "https://kernc.github.io/backtesting.py/doc/backtesting/",
                  "label": [
                    {
                      "t": "text",
                      "text": "From the "
                    },
                    {
                      "t": "fact",
                      "fact": "F168"
                    },
                    {
                      "t": "text",
                      "text": " docs"
                    }
                  ]
                }
              ]
            }
          ],
          "pros": [
            {
              "lead": [
                {
                  "t": "fact",
                  "fact": "F43"
                }
              ],
              "body": [
                {
                  "t": "fact",
                  "fact": "F44"
                }
              ]
            },
            {
              "lead": [
                {
                  "t": "fact",
                  "fact": "F45"
                }
              ],
              "body": [
                {
                  "t": "fact",
                  "fact": "F46"
                }
              ]
            }
          ],
          "cons": [
            {
              "lead": [
                {
                  "t": "fact",
                  "fact": "F47"
                }
              ],
              "body": [
                {
                  "t": "fact",
                  "fact": "F48"
                }
              ]
            },
            {
              "lead": [
                {
                  "t": "fact",
                  "fact": "F49"
                }
              ],
              "body": [
                {
                  "t": "fact",
                  "fact": "F50"
                }
              ]
            }
          ],
          "tabs": [
            {
              "label": [
                {
                  "t": "fact",
                  "fact": "F183"
                }
              ],
              "stars": [
                {
                  "t": "fact",
                  "fact": "F184"
                }
              ],
              "usedBy": [
                {
                  "t": "link",
                  "href": "https://github.com/Fincept-Corporation/FinceptTerminal",
                  "label": [
                    {
                      "t": "fact",
                      "fact": "F183"
                    }
                  ]
                },
                {
                  "t": "text",
                  "text": " "
                }
              ],
              "language": "python",
              "code": "def optimize(self, request: Dict[str, Any]) -> Dict[str, Any]:\n    \"\"\"Run parameter optimization via backtesting.py's `bt.optimize`.\n\n    The frontend sweeps strategy params under their *frontend* names (e.g.\n    `fastPeriod`); backtesting.py optimizes class-level attribute names\n    (e.g. `n1`). `btp_strategies.STRATEGY_OPTIMIZE_PARAM_MAP` translates.\n\n    Returns the same shape as run_backtest (`data.performance`, `data.trades`,\n    `data.equity`) so the existing screen renderer works unchanged, plus\n    optimization-specific fields under `data.optimization`.\n    \"\"\"\n    try:\n        self._log('Starting parameter optimization')\n\n        strategy_def = request.get('strategy', {})\n        strategy_type = strategy_def.get('type', 'sma_crossover')\n        # Frontend canonical name is `paramRanges`; legacy callers used `parameters`.\n        param_ranges = request.get('paramRanges', {}) or request.get('parameters', {})\n        objective = request.get('optimizeObjective') or request.get('metric', 'sharpe')\n        start_date = request.get('startDate')\n        end_date = request.get('endDate')\n        initial_capital = request.get('initialCapital', 10000)\n        max_iterations = int(request.get('maxIterations', 500) or 500)\n\n        # Canonical: `symbols: [str]`. Fallback: `assets: [{symbol, ...}]`.\n        symbols = request.get('symbols', [])\n        if not symbols:\n            assets = request.get('assets', [])\n            symbols = [a.get('symbol') for a in assets if isinstance(a, dict) and a.get('symbol')]\n\n        if not param_ranges:\n            return self._create_error_result('No parameter ranges supplied (expected paramRanges)')\n\n        symbol = symbols[0] if symbols else 'SPY'\n        data = self._load_data(symbol, start_date, end_date, request.get('interval', '1d'))\n        if data is None or len(data) == 0:\n            return self._create_error_result(f'No data available for {symbol}')\n\n        # Build the strategy class with default params; bt.optimize will\n        # sweep class-level attributes from there.\n        strategy_class = self._create_strategy_class(strategy_def)\n\n        # Translate frontend param names -> class attribute names per strategy.\n        import btp_strategies as _strat\n        mapped_ranges = _strat.map_optimize_params(strategy_type, param_ranges)\n\n        # Build python ranges. Drop any range that targets an attribute the\n        # strategy class doesn't declare — backtesting.py would reject it\n        # otherwise and we'd get the cryptic \"missing parameter X\" error.\n        opt_kwargs = {}\n        skipped: List[str] = []\n        for cattr, cfg in mapped_ranges.items():\n            if not hasattr(strategy_class, cattr):\n                skipped.append(cattr)\n                continue\n            try:\n                lo = int(cfg.get('min', 1))\n                hi = int(cfg.get('max', 100))\n                step = max(1, int(cfg.get('step', 1)))\n            except Exception:\n                continue\n            if hi < lo:\n                lo, hi = hi, lo\n            opt_kwargs[cattr] = range(lo, hi + 1, step)\n\n        if not opt_kwargs:\n            return self._create_error_result(\n                f\"No optimizable parameters for strategy '{strategy_type}'. \"\n                f\"Mapped attrs not present on class: {skipped}\"\n            )\n\n        if skipped:\n            self._log(f'Skipped non-class attrs during optimize: {skipped}')\n\n        from backtesting import Backtest\n        bt = Backtest(\n            data, strategy_class,\n            cash=initial_capital,\n            commission=float(request.get('commission', 0.0) or 0.0) + float(request.get('slippage', 0.0) or 0.0),\n        )\n\n        # Map frontend objective to backtesting.py stat key.\n        metric_map = {\n            'sharpe':  'Sharpe Ratio',\n            'sortino': 'Sortino Ratio',\n            'calmar':  'Calmar Ratio',\n            'return':  'Return [%]',\n            # Tolerate human-readable variants for callers outside the screen.\n            'Sharpe Ratio': 'Sharpe Ratio',\n            'Sortino Ratio': 'Sortino Ratio',\n            'Calmar Ratio': 'Calmar Ratio',\n            'Total Return': 'Return [%]',\n        }\n        maximize_metric = metric_map.get(objective, 'Sharpe Ratio')\n\n        self._log(f'Optimizing {len(opt_kwargs)} attrs (max_tries={max_iterations}) maximize={maximize_metric}')\n        stats = bt.optimize(**opt_kwargs, maximize=maximize_metric, max_tries=max_iterations)\n\n        # Extract chosen optimal params back under frontend names.\n        inverse_map = {cattr: fname for fname, cattr in\n                       _strat.STRATEGY_OPTIMIZE_PARAM_MAP.get(strategy_type, {}).items()}\n        optimal_params: Dict[str, Any] = {}\n        for cattr in opt_kwargs.keys():\n            if not hasattr(stats._strategy, cattr):\n                continue\n            fname = inverse_map.get(cattr, cattr)\n            val = getattr(stats._strategy, cattr)\n            optimal_params[fname] = int(val) if hasattr(val, '__int__') else val\n\n        # Wire shape: same as run_backtest so display_result() renders performance/trades.\n        result_dict = self._convert_results(\n            stats, symbol, start_date, end_date, initial_capital\n        ).to_dict()\n\n        using_synthetic = not self._has_real_data(symbol)\n        result_dict['using_synthetic_data'] = using_synthetic\n        result_dict['optimization'] = {\n            'objective': objective,\n            'objective_value': float(stats.get(maximize_metric, 0)),\n            'best_params': optimal_params,\n            'iterations': int(max_iterations),\n            'attrs_optimized': list(opt_kwargs.keys()),\n            'attrs_skipped': skipped,\n        }\n\n        self._log(\n            f\"Optimization done: best {maximize_metric} = \"\n            f\"{result_dict['optimization']['objective_value']:.4f} with {optimal_params}\"\n        )\n        return {'success': True, 'message': 'Optimization completed', 'data': result_dict}\n\n    except Exception as e:\n        self._error('Optimization failed', e)\n        import traceback\n        return self._create_error_result(f'Optimization failed: {str(e)}\\n{traceback.format_exc()}')",
              "prov": [
                {
                  "t": "link",
                  "href": "https://github.com/Fincept-Corporation/FinceptTerminal/blob/68691b7577ce642009cdf2c1b4b0766ca9e37999/fincept-qt/scripts/Analytics/backtesting/backtestingpy/backtestingpy_provider.py#L349-L483",
                  "label": [
                    {
                      "t": "fact",
                      "fact": "F182"
                    }
                  ]
                }
              ],
              "more": [
                {
                  "t": "link",
                  "href": "https://dashboard.exa.ai/playground/search?q=Python%20applications%20using%20backtesting%20for%20strategy%20simulation%20and%20portfolio%20allocation&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D",
                  "label": [
                    {
                      "t": "text",
                      "text": "More projects using "
                    },
                    {
                      "t": "fact",
                      "fact": "F168"
                    },
                    {
                      "t": "text",
                      "text": " →"
                    }
                  ]
                }
              ]
            },
            {
              "label": [
                {
                  "t": "text",
                  "text": "Quickstart"
                }
              ],
              "language": "python",
              "code": "from backtesting import Backtest, Strategy\nfrom backtesting.lib import crossover\n\nfrom backtesting.test import SMA, GOOG\n\n\nclass SmaCross(Strategy):\n    def init(self):\n        price = self.data.Close\n        self.ma1 = self.I(SMA, price, 10)\n        self.ma2 = self.I(SMA, price, 20)\n\n    def next(self):\n        if crossover(self.ma1, self.ma2):\n            self.buy()\n        elif crossover(self.ma2, self.ma1):\n            self.sell()\n\n\nbt = Backtest(GOOG, SmaCross, commission=.002,\n              exclusive_orders=True)\nstats = bt.run()\nbt.plot()\n",
              "prov": [
                {
                  "t": "text",
                  "text": "From "
                },
                {
                  "t": "link",
                  "href": "https://github.com/kernc/backtesting.py/blob/master/README.md",
                  "label": [
                    {
                      "t": "text",
                      "text": "README.md"
                    }
                  ]
                }
              ]
            }
          ],
          "install": [
            {
              "t": "fact",
              "fact": "F173"
            }
          ]
        },
        {
          "b": "entry",
          "anchor": "backtrader",
          "name": [
            {
              "t": "fact",
              "fact": "F185"
            }
          ],
          "links": [
            {
              "label": "GitHub",
              "href": "https://github.com/mementum/backtrader"
            },
            {
              "label": "PyPI",
              "href": "https://pypi.org/project/backtrader"
            },
            {
              "label": "Docs",
              "href": "https://pypi.org/project/backtrader/"
            }
          ],
          "what": [
            {
              "t": "fact",
              "fact": "F68"
            }
          ],
          "facts": [
            {
              "label": "Downloads / mo",
              "value": [
                {
                  "t": "fact",
                  "fact": "F186"
                }
              ]
            },
            {
              "label": "Stars",
              "value": [
                {
                  "t": "fact",
                  "fact": "F192"
                }
              ]
            },
            {
              "label": "Last release",
              "value": [
                {
                  "t": "fact",
                  "fact": "F188"
                }
              ]
            },
            {
              "label": "License",
              "value": [
                {
                  "t": "fact",
                  "fact": "F187"
                }
              ]
            },
            {
              "label": "Capabilities",
              "value": [
                {
                  "t": "link",
                  "href": "https://pypi.org/project/backtrader/",
                  "label": [
                    {
                      "t": "text",
                      "text": "From the "
                    },
                    {
                      "t": "fact",
                      "fact": "F185"
                    },
                    {
                      "t": "text",
                      "text": " docs"
                    }
                  ]
                }
              ]
            }
          ],
          "pros": [
            {
              "lead": [
                {
                  "t": "fact",
                  "fact": "F69"
                }
              ],
              "body": [
                {
                  "t": "fact",
                  "fact": "F70"
                }
              ]
            },
            {
              "lead": [
                {
                  "t": "fact",
                  "fact": "F71"
                }
              ],
              "body": [
                {
                  "t": "fact",
                  "fact": "F72"
                }
              ]
            }
          ],
          "cons": [
            {
              "lead": [
                {
                  "t": "fact",
                  "fact": "F73"
                }
              ],
              "body": [
                {
                  "t": "fact",
                  "fact": "F74"
                }
              ]
            },
            {
              "lead": [
                {
                  "t": "fact",
                  "fact": "F75"
                }
              ],
              "body": [
                {
                  "t": "fact",
                  "fact": "F76"
                }
              ]
            }
          ],
          "tabs": [
            {
              "label": [
                {
                  "t": "fact",
                  "fact": "F198"
                }
              ],
              "stars": [
                {
                  "t": "fact",
                  "fact": "F199"
                }
              ],
              "usedBy": [
                {
                  "t": "link",
                  "href": "https://github.com/UFund-Me/Qbot",
                  "label": [
                    {
                      "t": "fact",
                      "fact": "F198"
                    }
                  ]
                },
                {
                  "t": "text",
                  "text": " "
                }
              ],
              "language": "python",
              "code": "def next(self):\n    self.log('Close, %.2f' % self.dataclose[0])\n    if self.order:\n        return\n    if not self.position:\n        if (self.rsi[0] < 50 and\n                self.rsi[-1] >= 50 and\n                self.dataclose[0] > self.sma[0]):\n            self.log('BUY CREATE, %.2f' % self.dataclose[0])\n            self.order = self.buy()\n    else:\n        if (self.rsi[0] > 50 and\n                self.rsi[-1] <= 50 and\n                self.dataclose[0] < self.sma[0]):\n            self.log('SELL CREATE, %.2f' % self.dataclose[0])\n            self.order = self.sell()",
              "prov": [
                {
                  "t": "link",
                  "href": "https://github.com/UFund-Me/Qbot/blob/f0425ae4ae8bd02b79656b8f7039f4cd6874095e/qbot/strategies/multi_strategy_bt.py#L76-L91",
                  "label": [
                    {
                      "t": "fact",
                      "fact": "F197"
                    }
                  ]
                }
              ],
              "more": [
                {
                  "t": "link",
                  "href": "https://dashboard.exa.ai/playground/search?q=Python%20applications%20using%20backtrader%20for%20strategy%20simulation%20and%20portfolio%20allocation&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D",
                  "label": [
                    {
                      "t": "text",
                      "text": "More projects using "
                    },
                    {
                      "t": "fact",
                      "fact": "F185"
                    },
                    {
                      "t": "text",
                      "text": " →"
                    }
                  ]
                }
              ]
            },
            {
              "label": [
                {
                  "t": "text",
                  "text": "Quickstart"
                }
              ],
              "language": "python",
              "code": "import backtrader as bt\ncerebro = bt.Cerebro()\nprint(cerebro.broker.getvalue())\n",
              "prov": [
                {
                  "t": "text",
                  "text": "From "
                },
                {
                  "t": "link",
                  "href": "https://www.backtrader.com/docu/quickstart/quickstart/",
                  "label": [
                    {
                      "t": "text",
                      "text": "quickstart.md"
                    }
                  ]
                }
              ]
            }
          ],
          "install": [
            {
              "t": "fact",
              "fact": "F190"
            }
          ]
        },
        {
          "b": "entry",
          "anchor": "bt",
          "name": [
            {
              "t": "fact",
              "fact": "F200"
            }
          ],
          "links": [
            {
              "label": "GitHub",
              "href": "https://github.com/pmorissette/bt"
            },
            {
              "label": "PyPI",
              "href": "https://pypi.org/project/bt"
            },
            {
              "label": "Docs",
              "href": "https://pmorissette.github.io/bt/"
            }
          ],
          "what": [
            {
              "t": "fact",
              "fact": "F93"
            }
          ],
          "facts": [
            {
              "label": "Downloads / mo",
              "value": [
                {
                  "t": "fact",
                  "fact": "F201"
                }
              ]
            },
            {
              "label": "Stars",
              "value": [
                {
                  "t": "fact",
                  "fact": "F207"
                }
              ]
            },
            {
              "label": "Last release",
              "value": [
                {
                  "t": "fact",
                  "fact": "F203"
                }
              ]
            },
            {
              "label": "License",
              "value": [
                {
                  "t": "fact",
                  "fact": "F202"
                }
              ]
            },
            {
              "label": "Capabilities",
              "value": [
                {
                  "t": "link",
                  "href": "https://pmorissette.github.io/bt/",
                  "label": [
                    {
                      "t": "text",
                      "text": "From the "
                    },
                    {
                      "t": "fact",
                      "fact": "F200"
                    },
                    {
                      "t": "text",
                      "text": " docs"
                    }
                  ]
                }
              ]
            }
          ],
          "pros": [
            {
              "lead": [
                {
                  "t": "fact",
                  "fact": "F94"
                }
              ],
              "body": [
                {
                  "t": "fact",
                  "fact": "F95"
                }
              ]
            },
            {
              "lead": [
                {
                  "t": "fact",
                  "fact": "F96"
                }
              ],
              "body": [
                {
                  "t": "fact",
                  "fact": "F97"
                }
              ]
            }
          ],
          "cons": [
            {
              "lead": [
                {
                  "t": "fact",
                  "fact": "F98"
                }
              ],
              "body": [
                {
                  "t": "fact",
                  "fact": "F99"
                }
              ]
            },
            {
              "lead": [
                {
                  "t": "fact",
                  "fact": "F100"
                }
              ],
              "body": [
                {
                  "t": "fact",
                  "fact": "F101"
                }
              ]
            }
          ],
          "tabs": [
            {
              "label": [
                {
                  "t": "fact",
                  "fact": "F214"
                }
              ],
              "stars": [
                {
                  "t": "fact",
                  "fact": "F215"
                }
              ],
              "usedBy": [
                {
                  "t": "link",
                  "href": "https://github.com/Fincept-Corporation/FinceptTerminal",
                  "label": [
                    {
                      "t": "fact",
                      "fact": "F214"
                    }
                  ]
                },
                {
                  "t": "text",
                  "text": " "
                }
              ],
              "language": "python",
              "code": "@_register('momentum_topn', 'momentum', 'Momentum Top-N',\n           'Select top N assets by momentum, equal weight',\n           [{'name': 'topN', 'label': 'Top N', 'default': 5, 'min': 1, 'max': 50},\n            {'name': 'lookback', 'label': 'Momentum Lookback', 'default': 60}])\ndef _build_momentum_topn(params):\n    \"\"\"Momentum top-N selection strategy.\"\"\"\n    top_n = int(params.get('topN', 5))\n    lookback = int(params.get('lookback', 60))\n\n    def build(data, name='momentum_topn'):\n        if _BT_AVAILABLE:\n            algos = [\n                # Wait until the lookback window has data (the first rebalance otherwise\n                # fails on an empty/NaN estimate). Must precede RunMonthly: placed after\n                # it, the counter only advanced on month starts (lookback MONTHS).\n                _bt.algos.RunAfterDays(int(lookback) + 2),\n                _bt.algos.RunMonthly(),\n                _bt.algos.SelectAll(),  # SelectMomentum ranks the current selection\n                _bt.algos.SelectMomentum(n=top_n, lookback=pd.DateOffset(days=lookback), lag=_LAG),\n                _bt.algos.WeighEqually(),\n                _bt.algos.Rebalance(),\n            ]\n            return _bt.Strategy(name, algos)\n        return None\n    return build",
              "prov": [
                {
                  "t": "link",
                  "href": "https://github.com/Fincept-Corporation/FinceptTerminal/blob/68691b7577ce642009cdf2c1b4b0766ca9e37999/fincept-qt/scripts/Analytics/backtesting/bt/bt_strategies.py#L510-L534",
                  "label": [
                    {
                      "t": "fact",
                      "fact": "F213"
                    }
                  ]
                }
              ],
              "more": [
                {
                  "t": "link",
                  "href": "https://dashboard.exa.ai/playground/search?q=Python%20applications%20using%20bt%20for%20strategy%20simulation%20and%20portfolio%20allocation&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D",
                  "label": [
                    {
                      "t": "text",
                      "text": "More projects using "
                    },
                    {
                      "t": "fact",
                      "fact": "F200"
                    },
                    {
                      "t": "text",
                      "text": " →"
                    }
                  ]
                }
              ]
            },
            {
              "label": [
                {
                  "t": "text",
                  "text": "Quickstart"
                }
              ],
              "language": "python",
              "code": "import numpy as np\nimport pandas as pd\n\nimport bt\n\nprices = pd.DataFrame(\n    {\n        \"asset_a\": np.linspace(100, 120, 252),\n        \"asset_b\": np.linspace(100, 110, 252),\n    },\n    index=pd.bdate_range(\"2020-01-01\", periods=252),\n)\n\nstrategy = bt.Strategy(\n    \"equal_weight\",\n    [\n        bt.algos.RunMonthly(),\n        bt.algos.SelectAll(),\n        bt.algos.WeighEqually(),\n        bt.algos.Rebalance(),\n    ],\n)\nresult = bt.run(bt.Backtest(strategy, prices))\nresult.display()\n",
              "prov": [
                {
                  "t": "text",
                  "text": "From "
                },
                {
                  "t": "link",
                  "href": "https://github.com/pmorissette/bt/blob/master/README.md",
                  "label": [
                    {
                      "t": "text",
                      "text": "README.md"
                    }
                  ]
                }
              ]
            }
          ],
          "install": [
            {
              "t": "fact",
              "fact": "F205"
            }
          ]
        },
        {
          "b": "entry",
          "anchor": "pyqlib",
          "name": [
            {
              "t": "fact",
              "fact": "F216"
            }
          ],
          "links": [
            {
              "label": "GitHub",
              "href": "https://github.com/microsoft/qlib"
            },
            {
              "label": "PyPI",
              "href": "https://pypi.org/project/pyqlib"
            },
            {
              "label": "Docs",
              "href": "https://pypi.org/project/pyqlib/"
            }
          ],
          "what": [
            {
              "t": "fact",
              "fact": "F223"
            }
          ],
          "facts": [
            {
              "label": "Downloads / mo",
              "value": [
                {
                  "t": "fact",
                  "fact": "F217"
                }
              ]
            },
            {
              "label": "Stars",
              "value": [
                {
                  "t": "fact",
                  "fact": "F225"
                }
              ]
            },
            {
              "label": "Last release",
              "value": [
                {
                  "t": "fact",
                  "fact": "F219"
                }
              ]
            },
            {
              "label": "License",
              "value": [
                {
                  "t": "fact",
                  "fact": "F218"
                }
              ]
            },
            {
              "label": "Capabilities",
              "value": [
                {
                  "t": "link",
                  "href": "https://pypi.org/project/pyqlib/",
                  "label": [
                    {
                      "t": "text",
                      "text": "From the "
                    },
                    {
                      "t": "fact",
                      "fact": "F216"
                    },
                    {
                      "t": "text",
                      "text": " docs"
                    }
                  ]
                }
              ]
            }
          ],
          "pros": [],
          "cons": [],
          "tabs": [
            {
              "label": [
                {
                  "t": "text",
                  "text": "Quickstart"
                }
              ],
              "language": "python",
              "code": "import qlib\nfrom qlib.data import D\nfrom qlib.constant import REG_CN\n\n# Initialization\nmount_path = \"~/.qlib/qlib_data/cn_data\"  # target_dir\nqlib.init(mount_path=mount_path, region=REG_CN)\n\n# Get stock data by Qlib\n# Load trading calendar with the given time range and frequency\nprint(D.calendar(start_time='2010-01-01', end_time='2017-12-31', freq='day')[:2])\n",
              "prov": [
                {
                  "t": "text",
                  "text": "From "
                },
                {
                  "t": "link",
                  "href": "https://raw.githubusercontent.com/microsoft/qlib/v0.9.7/README.md",
                  "label": [
                    {
                      "t": "text",
                      "text": "README.md"
                    }
                  ]
                }
              ],
              "more": [
                {
                  "t": "link",
                  "href": "https://dashboard.exa.ai/playground/search?q=pyqlib%20GitHub%20projects",
                  "label": [
                    {
                      "t": "text",
                      "text": "Find projects using "
                    },
                    {
                      "t": "fact",
                      "fact": "F216"
                    },
                    {
                      "t": "text",
                      "text": " →"
                    }
                  ]
                }
              ]
            }
          ],
          "install": [
            {
              "t": "fact",
              "fact": "F221"
            }
          ]
        },
        {
          "b": "entry",
          "anchor": "lumibot",
          "name": [
            {
              "t": "fact",
              "fact": "F231"
            }
          ],
          "links": [
            {
              "label": "GitHub",
              "href": "https://github.com/Lumiwealth/lumibot"
            },
            {
              "label": "PyPI",
              "href": "https://pypi.org/project/lumibot"
            },
            {
              "label": "Docs",
              "href": "https://lumibot.lumiwealth.com/"
            }
          ],
          "what": [
            {
              "t": "fact",
              "fact": "F238"
            }
          ],
          "facts": [
            {
              "label": "Downloads / mo",
              "value": [
                {
                  "t": "fact",
                  "fact": "F232"
                }
              ]
            },
            {
              "label": "Stars",
              "value": [
                {
                  "t": "fact",
                  "fact": "F240"
                }
              ]
            },
            {
              "label": "Last release",
              "value": [
                {
                  "t": "fact",
                  "fact": "F234"
                }
              ]
            },
            {
              "label": "License",
              "value": [
                {
                  "t": "fact",
                  "fact": "F233"
                }
              ]
            },
            {
              "label": "Capabilities",
              "value": [
                {
                  "t": "link",
                  "href": "https://lumibot.lumiwealth.com/",
                  "label": [
                    {
                      "t": "text",
                      "text": "From the "
                    },
                    {
                      "t": "fact",
                      "fact": "F231"
                    },
                    {
                      "t": "text",
                      "text": " docs"
                    }
                  ]
                }
              ]
            }
          ],
          "pros": [],
          "cons": [],
          "tabs": [
            {
              "label": [
                {
                  "t": "text",
                  "text": "Quickstart"
                }
              ],
              "language": "python",
              "code": "from datetime import datetime\n\nfrom lumibot.backtesting import YahooDataBacktesting\nfrom lumibot.strategies import Strategy\n\nclass BuyAndHold(Strategy):\n    def initialize(self):\n        self.sleeptime = \"1D\"\n\n    def on_trading_iteration(self):\n        if self.first_iteration:\n            price = self.get_last_price(\"SPY\")\n            quantity = int(self.get_cash() // price)\n            order = self.create_order(\"SPY\", quantity, \"buy\")\n            self.submit_order(order)\n\nif __name__ == \"__main__\":\n    BuyAndHold.run_backtest(\n        YahooDataBacktesting,\n        datetime(2025, 1, 1),\n        datetime(2025, 2, 1),\n    )\n\n",
              "prov": [
                {
                  "t": "text",
                  "text": "From "
                },
                {
                  "t": "link",
                  "href": "https://lumibot.lumiwealth.com/strategy_api_overview.html",
                  "label": [
                    {
                      "t": "text",
                      "text": "strategy_api_overview.html"
                    }
                  ]
                }
              ],
              "more": [
                {
                  "t": "link",
                  "href": "https://dashboard.exa.ai/playground/search?q=lumibot%20GitHub%20projects",
                  "label": [
                    {
                      "t": "text",
                      "text": "Find projects using "
                    },
                    {
                      "t": "fact",
                      "fact": "F231"
                    },
                    {
                      "t": "text",
                      "text": " →"
                    }
                  ]
                }
              ]
            }
          ],
          "install": [
            {
              "t": "fact",
              "fact": "F236"
            }
          ]
        },
        {
          "b": "entry",
          "anchor": "lean",
          "name": [
            {
              "t": "fact",
              "fact": "F245"
            }
          ],
          "links": [
            {
              "label": "GitHub",
              "href": "https://github.com/QuantConnect/lean-cli"
            },
            {
              "label": "PyPI",
              "href": "https://pypi.org/project/lean"
            },
            {
              "label": "Docs",
              "href": "https://www.lean.io/docs/v2/lean-cli/key-concepts/getting-started"
            }
          ],
          "what": [
            {
              "t": "fact",
              "fact": "F252"
            }
          ],
          "facts": [
            {
              "label": "Downloads / mo",
              "value": [
                {
                  "t": "fact",
                  "fact": "F246"
                }
              ]
            },
            {
              "label": "Stars",
              "value": [
                {
                  "t": "fact",
                  "fact": "F254"
                }
              ]
            },
            {
              "label": "Last release",
              "value": [
                {
                  "t": "fact",
                  "fact": "F248"
                }
              ]
            },
            {
              "label": "License",
              "value": [
                {
                  "t": "fact",
                  "fact": "F247"
                }
              ]
            },
            {
              "label": "Capabilities",
              "value": [
                {
                  "t": "link",
                  "href": "https://www.lean.io/docs/v2/lean-cli/key-concepts/getting-started",
                  "label": [
                    {
                      "t": "text",
                      "text": "From the "
                    },
                    {
                      "t": "fact",
                      "fact": "F245"
                    },
                    {
                      "t": "text",
                      "text": " docs"
                    }
                  ]
                }
              ]
            }
          ],
          "pros": [],
          "cons": [],
          "tabs": [
            {
              "label": [
                {
                  "t": "text",
                  "text": "Quickstart"
                }
              ],
              "language": "python",
              "code": "lean init\nlean create-project \"Project Name\"\nlean backtest \"Project Name\"\n",
              "prov": [
                {
                  "t": "text",
                  "text": "From "
                },
                {
                  "t": "link",
                  "href": "https://pypi.org/pypi/lean/1.0.233/json#info.description",
                  "label": [
                    {
                      "t": "text",
                      "text": "README.md"
                    }
                  ]
                }
              ],
              "more": [
                {
                  "t": "link",
                  "href": "https://dashboard.exa.ai/playground/search?q=lean%20GitHub%20projects",
                  "label": [
                    {
                      "t": "text",
                      "text": "Find projects using "
                    },
                    {
                      "t": "fact",
                      "fact": "F245"
                    },
                    {
                      "t": "text",
                      "text": " →"
                    }
                  ]
                }
              ]
            }
          ],
          "install": [
            {
              "t": "fact",
              "fact": "F250"
            }
          ]
        }
      ]
    }
  ],
  "questions": [
    {
      "q": "Which Python backtesting library should I use?",
      "a": [
        {
          "t": "link",
          "href": "#backtesting-py",
          "label": [
            {
              "t": "text",
              "text": "Backtesting.py"
            }
          ]
        },
        {
          "t": "text",
          "text": " suits single-asset strategies with interactive plots. "
        },
        {
          "t": "link",
          "href": "#vectorbt",
          "label": [
            {
              "t": "text",
              "text": "vectorbt"
            }
          ]
        },
        {
          "t": "text",
          "text": " suits fast parameter sweeps across many combinations. "
        },
        {
          "t": "link",
          "href": "#nautilus-trader",
          "label": [
            {
              "t": "text",
              "text": "NautilusTrader"
            }
          ]
        },
        {
          "t": "text",
          "text": " suits strategies that must run the same code in backtests and live trading."
        }
      ]
    },
    {
      "q": "What is backtesting?",
      "a": [
        {
          "t": "text",
          "text": "Backtesting runs a trading strategy against historical prices to measure its returns, drawdowns, and trade statistics. Results depend on realistic costs, slippage, and data free of look-ahead bias."
        }
      ]
    },
    {
      "q": "What is backtrader?",
      "a": [
        {
          "t": "link",
          "href": "#backtrader",
          "label": [
            {
              "t": "text",
              "text": "backtrader"
            }
          ]
        },
        {
          "t": "text",
          "text": " is an event-driven backtesting framework that simulates strategies with multiple data feeds, order types, and broker behavior."
        }
      ]
    },
    {
      "q": "What is Qlib?",
      "a": [
        {
          "t": "link",
          "href": "#pyqlib",
          "label": [
            {
              "t": "text",
              "text": "Qlib"
            }
          ]
        },
        {
          "t": "text",
          "text": " is a quantitative research platform from Microsoft for building and testing machine learning trading models."
        }
      ]
    },
    {
      "q": "What is vectorbt?",
      "a": [
        {
          "t": "link",
          "href": "#vectorbt",
          "label": [
            {
              "t": "text",
              "text": "vectorbt"
            }
          ]
        },
        {
          "t": "text",
          "text": " simulates portfolios from arrays of orders or signals with NumPy and Numba. It tests many parameter combinations in one run."
        }
      ]
    },
    {
      "q": "What is NautilusTrader?",
      "a": [
        {
          "t": "link",
          "href": "#nautilus-trader",
          "label": [
            {
              "t": "text",
              "text": "NautilusTrader"
            }
          ]
        },
        {
          "t": "text",
          "text": " is a trading engine with a Rust core and a Python API. Its event-driven design runs the same strategy code in backtests and live trading."
        }
      ]
    }
  ],
  "facts": {
    "F1": {
      "label": "Library name, vectorbt",
      "display": "VectorBT",
      "asOf": "2026-11-17"
    },
    "F2": {
      "label": "Monthly downloads, vectorbt",
      "display": "386.8K",
      "asOf": "2026-11-16"
    },
    "F3": {
      "label": "License, vectorbt",
      "display": "Apache 2.0 with Commons Clause",
      "asOf": "2026-11-17"
    },
    "F4": {
      "label": "Package release, vectorbt",
      "display": "1.2.1, Nov 2026",
      "asOf": "2026-11-11"
    },
    "F5": {
      "label": "Package release date, vectorbt",
      "display": "Nov 2026",
      "asOf": "2026-11-11"
    },
    "F6": {
      "label": "Repository stars, vectorbt",
      "display": "9.9K",
      "asOf": "2026-11-17"
    },
    "F7": {
      "label": "Simulates multiple assets, vectorbt",
      "display": "Built-in",
      "asOf": "2026-11-17"
    },
    "F8": {
      "label": "Evaluates parameter grids, vectorbt",
      "display": "Built-in",
      "asOf": "2026-11-17"
    },
    "F9": {
      "label": "Models transaction costs, vectorbt",
      "display": "Built-in",
      "asOf": "2026-11-17"
    },
    "F10": {
      "label": "Supports short positions, vectorbt",
      "display": "Built-in",
      "asOf": "2026-11-17"
    },
    "F11": {
      "label": "Install, vectorbt",
      "display": "pip install vectorbt",
      "asOf": "2026-11-17"
    },
    "F12": {
      "label": "What it does, vectorbt",
      "display": "Simulates portfolios from arrays of orders or signals and compares parameter combinations.",
      "asOf": "2026-11-17"
    },
    "F13": {
      "label": "strengths lead, vectorbt",
      "display": "Broadcasts strategy inputs across assets",
      "asOf": "2026-11-17"
    },
    "F14": {
      "label": "strengths, vectorbt",
      "display": "Pass array inputs across assets and parameter combinations.",
      "asOf": "2026-11-17"
    },
    "F15": {
      "label": "strengths lead, vectorbt",
      "display": "Models fees and slippage",
      "asOf": "2026-11-17"
    },
    "F16": {
      "label": "strengths, vectorbt",
      "display": "Set fees and slippage when creating the simulated portfolio.",
      "asOf": "2026-11-17"
    },
    "F17": {
      "label": "limitations lead, vectorbt",
      "display": "Repeated entries require accumulation",
      "asOf": "2026-11-17"
    },
    "F18": {
      "label": "limitations, vectorbt",
      "display": "Enable accumulate when new entry signals should increase an existing position.",
      "asOf": "2026-11-17"
    },
    "F19": {
      "label": "limitations lead, vectorbt",
      "display": "Complex orders need custom callbacks",
      "asOf": "2026-11-17"
    },
    "F20": {
      "label": "limitations, vectorbt",
      "display": "Use from_order_func for complex conditions and multiple orders.",
      "asOf": "2026-11-17"
    },
    "F21": {
      "label": "Quickstart, vectorbt",
      "display": "import pandas as pd\nimport vectorbt as vbt\n\nclose = pd.Series(\n    [100.0, 102.0, 101.0, 104.0, 103.0, 107.0],\n    index=pd.date_range(\"2024-01-01\", periods=6, freq=\"D\"),\n    name=\"Close\",\n)\npf = vbt.Portfolio.from_holding(close, init_cash=1000, fees=0.001, freq=\"1D\")\nprint(round(float(pf.total_return()) * 100, 2))\n\n",
      "asOf": "2026-11-17"
    },
    "F22": {
      "label": "Project function, vectorbt",
      "display": "def run_backtest(\n    frame: pd.DataFrame,\n    entries: pd.Series,\n    exits: pd.Series,\n    *,\n    symbol: str = \"\",\n    strategy: str = \"\",\n    parameters: dict[str, Any] | None = None,\n    settings: BacktestingSettings | None = None,\n) -> BacktestResult:\n    \"\"\"Run a single vectorized backtest over `frame` given `entries`/`exits`\n    signals, and return the full-fidelity `BacktestResult`.\n\n    Port of `VectorBTEngine.run_backtest` minus data fetching, caching,\n    structured logging/memory-profiling instrumentation, and chart code.\n    `symbol`/`strategy`/`parameters` are pure metadata carried onto the\n    result; `start_date`/`end_date` are derived from `frame`'s index rather\n    than accepted as separate arguments, since the frame is the only source\n    of truth about what period was actually backtested.\n    \"\"\"\n    settings = settings or get_backtesting_settings()\n    close = _validate_frame(frame)\n    if len(entries) != len(frame) or len(exits) != len(frame):\n        raise ValueError(\"entries/exits length must match frame length\")\n\n    portfolio: Any = vbt.Portfolio.from_signals(\n        close=close.astype(np.float32),\n        entries=entries.astype(bool),\n        exits=exits.astype(bool),\n        init_cash=settings.initial_capital,\n        fees=settings.fees,\n        slippage=settings.slippage,\n        freq=\"D\",\n        cash_sharing=False,\n        call_seq=\"auto\",\n        group_by=False,\n        broadcast_kwargs={\"wrapper_kwargs\": {\"freq\": \"D\"}},\n    )\n\n    equity_curve = {str(k): float(v) for k, v in portfolio.value().to_dict().items()}\n    drawdown_series = {\n        str(k): float(v) for k, v in portfolio.drawdown().to_dict().items()\n    }\n\n    return BacktestResult(\n        symbol=symbol,\n        strategy=strategy,\n        parameters=parameters or {},\n        metrics=_extract_metrics(portfolio),\n        trades=_extract_trades(portfolio),\n        equity_curve=equity_curve,\n        drawdown_series=drawdown_series,\n        start_date=_format_date(frame.index[0]),\n        end_date=_format_date(frame.index[-1]),\n        initial_capital=settings.initial_capital,\n        memory_stats=None,\n    )\n",
      "asOf": "2026-11-17"
    },
    "F23": {
      "label": "Project function reference, vectorbt",
      "display": "engine.py · run_backtest()",
      "asOf": "2026-11-17"
    },
    "F24": {
      "label": "Project repository, vectorbt",
      "display": "wshobson/maverick-mcp",
      "asOf": "2026-11-17"
    },
    "F25": {
      "label": "Project stars, wshobson/maverick-mcp",
      "display": "728",
      "asOf": "2026-11-17"
    },
    "F26": {
      "label": "Project push date, wshobson/maverick-mcp",
      "display": "Nov 2026",
      "asOf": "2026-11-13"
    },
    "F27": {
      "label": "Project function, vectorbt",
      "display": "def backtest(self, ohlcv, variables=None, filters=None, lookback=None, plot=False, signals=False,\n             side='long', cscv_nbins=10, cscv_objective=lambda r: r.mean(), html=None, compounded=True,\n             execution_price='close', k_colors='world', **args):\n    \"\"\"Backtest the strategy with vectorbt.\n\n    Args:\n      ohlcv: OHLCV DataFrame.\n      variables: Strategy parameters. Lists or arrays are optimised over;\n        ``sl_stop``, ``tp_stop``, ``ts_stop`` add stop-loss, take-profit\n        and trailing-stop exits.\n      filters: {name: Filter.create(...)} conditions for entries.\n      lookback: Only use the latest ``lookback`` bars.\n      plot: Show the interactive chart (one parameter set) or the\n        optimisation dashboard with overfitting analysis (many sets).\n      signals: Return ``(entries, exits, figures)`` instead of backtesting.\n      side: Only 'long' is supported.\n      cscv_nbins: Number of blocks for the overfitting analysis.\n      cscv_objective: Performance measure for the overfitting analysis.\n      html: Also save the interactive chart to this file.\n      compounded: Reinvest profits; otherwise trade a fixed size.\n      execution_price: 'close' trades at the signal bar's close, 'open'\n        at the next bar's open.\n      k_colors: Candle colors, 'world', 'taiwan' or\n        {'increasing_line': color, 'decreasing_line': color}.\n      **args: Passed to ``vbt.Portfolio.from_signals`` (ex: ``freq='4h'``, ``fees``).\n\n    Returns:\n      vbt.Portfolio\n    \"\"\"\n    if side == 'short':\n        raise NotImplementedError('Shorting is not supported yet')\n    if side != 'long':\n        raise ValueError(\"side should be 'long' or 'short'\")\n    if execution_price not in EXECUTION_PRICES:\n        raise ValueError(f'execution_price should be one of {EXECUTION_PRICES}')\n\n    variables = dict(variables or {})\n    stop_vars = {name: variables.pop(name) for name in STOP_VARIABLES if name in variables}\n    ohlcv = ohlcv.iloc[-lookback:] if lookback else ohlcv\n\n    parameter_sets = enumerate_variables(variables) or [self._default_parameters]\n    entries, exits, fig_data = enumerate_signal(ohlcv, self, parameter_sets)\n    if filters:\n        filter_results = {name: create(ohlcv) for name, create in filters.items()}\n        entries, exits, fig_data = self._add_filters(entries, exits, fig_data, filter_results)\n    entries, exits = stop_early(ohlcv, entries, exits, stop_vars)\n    entries, exits = entries.squeeze(axis=1), exits.squeeze(axis=1)\n\n    if signals:\n        return entries, exits, fig_data\n\n    if not compounded:\n        args['size'] = vbt.settings.portfolio['init_cash'] / ohlcv.close.iloc[0]\n    price = ohlcv.close if execution_price == 'close' else ohlcv.open.shift(-1)\n    portfolio = vbt.Portfolio.from_signals(price, _as_bool(entries), _as_bool(exits), **args)\n\n    if isinstance(entries, pd.Series):\n        if plot or html is not None:\n            plot_strategy(ohlcv, entries, exits, portfolio, fig_data, html=html, k_colors=k_colors)\n    elif plot:\n        cscv = CSCV(n_bins=cscv_nbins, objective=cscv_objective)\n        cscv.add_daily_returns(portfolio.daily_returns())\n        plot_combination(portfolio, cscv.estimate_overfitting())\n        plt.show()\n        variable_visualization(portfolio)\n\n    return portfolio\n",
      "asOf": "2026-11-17"
    },
    "F28": {
      "label": "Project function reference, vectorbt",
      "display": "strategy.py · backtest()",
      "asOf": "2026-11-17"
    },
    "F29": {
      "label": "Project repository, vectorbt",
      "display": "finlab-python/finlab_crypto",
      "asOf": "2026-11-17"
    },
    "F30": {
      "label": "Project stars, finlab-python/finlab_crypto",
      "display": "293",
      "asOf": "2026-11-17"
    },
    "F31": {
      "label": "Project push date, finlab-python/finlab_crypto",
      "display": "Sep 2026",
      "asOf": "2026-09-24"
    },
    "F32": {
      "label": "Library name, backtesting",
      "display": "Backtesting.py",
      "asOf": "2026-11-17"
    },
    "F33": {
      "label": "Monthly downloads, backtesting",
      "display": "239.5K",
      "asOf": "2026-11-16"
    },
    "F34": {
      "label": "License, backtesting",
      "display": "AGPL-3.0",
      "asOf": "2026-11-17"
    },
    "F35": {
      "label": "Package release, backtesting",
      "display": "0.6.6, Jul 2026",
      "asOf": "2026-07-22"
    },
    "F36": {
      "label": "Package release date, backtesting",
      "display": "Jul 2026",
      "asOf": "2026-07-22"
    },
    "F37": {
      "label": "Repository stars, backtesting",
      "display": "9.3K",
      "asOf": "2026-11-17"
    },
    "F38": {
      "label": "Evaluates parameter grids, backtesting",
      "display": "Built-in",
      "asOf": "2026-11-17"
    },
    "F39": {
      "label": "Models transaction costs, backtesting",
      "display": "Built-in",
      "asOf": "2026-11-17"
    },
    "F40": {
      "label": "Supports short positions, backtesting",
      "display": "Built-in",
      "asOf": "2026-11-17"
    },
    "F41": {
      "label": "Install, backtesting",
      "display": "pip install backtesting",
      "asOf": "2026-11-17"
    },
    "F42": {
      "label": "What it does, backtesting",
      "display": "Runs historical trading strategies with indicators, order simulation, parameter optimization, and interactive plots.",
      "asOf": "2026-11-17"
    },
    "F43": {
      "label": "strengths lead, backtesting",
      "display": "Searches parameter combinations",
      "asOf": "2026-11-17"
    },
    "F44": {
      "label": "strengths, backtesting",
      "display": "Use optimize to search parameter combinations, with optional constraints.",
      "asOf": "2026-11-17"
    },
    "F45": {
      "label": "strengths lead, backtesting",
      "display": "Charges commissions at both ends",
      "asOf": "2026-11-17"
    },
    "F46": {
      "label": "strengths, backtesting",
      "display": "Commission applies when trades open and when they close.",
      "asOf": "2026-11-17"
    },
    "F47": {
      "label": "limitations lead, backtesting",
      "display": "Fractional trading needs another class",
      "asOf": "2026-11-17"
    },
    "F48": {
      "label": "limitations, backtesting",
      "display": "Use FractionalBacktest when strategies trade fractional units.",
      "asOf": "2026-11-17"
    },
    "F49": {
      "label": "limitations lead, backtesting",
      "display": "Margin types share one setting",
      "asOf": "2026-11-17"
    },
    "F50": {
      "label": "limitations, backtesting",
      "display": "The engine does not distinguish initial margin from maintenance margin.",
      "asOf": "2026-11-17"
    },
    "F51": {
      "label": "Quickstart, backtesting",
      "display": "from backtesting import Backtest, Strategy\nfrom backtesting.lib import crossover\n\nfrom backtesting.test import SMA, GOOG\n\n\nclass SmaCross(Strategy):\n    def init(self):\n        price = self.data.Close\n        self.ma1 = self.I(SMA, price, 10)\n        self.ma2 = self.I(SMA, price, 20)\n\n    def next(self):\n        if crossover(self.ma1, self.ma2):\n            self.buy()\n        elif crossover(self.ma2, self.ma1):\n            self.sell()\n\n\nbt = Backtest(GOOG, SmaCross, commission=.002,\n              exclusive_orders=True)\nstats = bt.run()\nbt.plot()\n",
      "asOf": "2026-11-17"
    },
    "F52": {
      "label": "Project function, backtesting",
      "display": "def optimize(self, request: Dict[str, Any]) -> Dict[str, Any]:\n    \"\"\"Run parameter optimization via backtesting.py's `bt.optimize`.\n\n    The frontend sweeps strategy params under their *frontend* names (e.g.\n    `fastPeriod`); backtesting.py optimizes class-level attribute names\n    (e.g. `n1`). `btp_strategies.STRATEGY_OPTIMIZE_PARAM_MAP` translates.\n\n    Returns the same shape as run_backtest (`data.performance`, `data.trades`,\n    `data.equity`) so the existing screen renderer works unchanged, plus\n    optimization-specific fields under `data.optimization`.\n    \"\"\"\n    try:\n        self._log('Starting parameter optimization')\n\n        strategy_def = request.get('strategy', {})\n        strategy_type = strategy_def.get('type', 'sma_crossover')\n        # Frontend canonical name is `paramRanges`; legacy callers used `parameters`.\n        param_ranges = request.get('paramRanges', {}) or request.get('parameters', {})\n        objective = request.get('optimizeObjective') or request.get('metric', 'sharpe')\n        start_date = request.get('startDate')\n        end_date = request.get('endDate')\n        initial_capital = request.get('initialCapital', 10000)\n        max_iterations = int(request.get('maxIterations', 500) or 500)\n\n        # Canonical: `symbols: [str]`. Fallback: `assets: [{symbol, ...}]`.\n        symbols = request.get('symbols', [])\n        if not symbols:\n            assets = request.get('assets', [])\n            symbols = [a.get('symbol') for a in assets if isinstance(a, dict) and a.get('symbol')]\n\n        if not param_ranges:\n            return self._create_error_result('No parameter ranges supplied (expected paramRanges)')\n\n        symbol = symbols[0] if symbols else 'SPY'\n        data = self._load_data(symbol, start_date, end_date, request.get('interval', '1d'))\n        if data is None or len(data) == 0:\n            return self._create_error_result(f'No data available for {symbol}')\n\n        # Build the strategy class with default params; bt.optimize will\n        # sweep class-level attributes from there.\n        strategy_class = self._create_strategy_class(strategy_def)\n\n        # Translate frontend param names -> class attribute names per strategy.\n        import btp_strategies as _strat\n        mapped_ranges = _strat.map_optimize_params(strategy_type, param_ranges)\n\n        # Build python ranges. Drop any range that targets an attribute the\n        # strategy class doesn't declare — backtesting.py would reject it\n        # otherwise and we'd get the cryptic \"missing parameter X\" error.\n        opt_kwargs = {}\n        skipped: List[str] = []\n        for cattr, cfg in mapped_ranges.items():\n            if not hasattr(strategy_class, cattr):\n                skipped.append(cattr)\n                continue\n            try:\n                lo = int(cfg.get('min', 1))\n                hi = int(cfg.get('max', 100))\n                step = max(1, int(cfg.get('step', 1)))\n            except Exception:\n                continue\n            if hi < lo:\n                lo, hi = hi, lo\n            opt_kwargs[cattr] = range(lo, hi + 1, step)\n\n        if not opt_kwargs:\n            return self._create_error_result(\n                f\"No optimizable parameters for strategy '{strategy_type}'. \"\n                f\"Mapped attrs not present on class: {skipped}\"\n            )\n\n        if skipped:\n            self._log(f'Skipped non-class attrs during optimize: {skipped}')\n\n        from backtesting import Backtest\n        bt = Backtest(\n            data, strategy_class,\n            cash=initial_capital,\n            commission=float(request.get('commission', 0.0) or 0.0) + float(request.get('slippage', 0.0) or 0.0),\n        )\n\n        # Map frontend objective to backtesting.py stat key.\n        metric_map = {\n            'sharpe':  'Sharpe Ratio',\n            'sortino': 'Sortino Ratio',\n            'calmar':  'Calmar Ratio',\n            'return':  'Return [%]',\n            # Tolerate human-readable variants for callers outside the screen.\n            'Sharpe Ratio': 'Sharpe Ratio',\n            'Sortino Ratio': 'Sortino Ratio',\n            'Calmar Ratio': 'Calmar Ratio',\n            'Total Return': 'Return [%]',\n        }\n        maximize_metric = metric_map.get(objective, 'Sharpe Ratio')\n\n        self._log(f'Optimizing {len(opt_kwargs)} attrs (max_tries={max_iterations}) maximize={maximize_metric}')\n        stats = bt.optimize(**opt_kwargs, maximize=maximize_metric, max_tries=max_iterations)\n\n        # Extract chosen optimal params back under frontend names.\n        inverse_map = {cattr: fname for fname, cattr in\n                       _strat.STRATEGY_OPTIMIZE_PARAM_MAP.get(strategy_type, {}).items()}\n        optimal_params: Dict[str, Any] = {}\n        for cattr in opt_kwargs.keys():\n            if not hasattr(stats._strategy, cattr):\n                continue\n            fname = inverse_map.get(cattr, cattr)\n            val = getattr(stats._strategy, cattr)\n            optimal_params[fname] = int(val) if hasattr(val, '__int__') else val\n\n        # Wire shape: same as run_backtest so display_result() renders performance/trades.\n        result_dict = self._convert_results(\n            stats, symbol, start_date, end_date, initial_capital\n        ).to_dict()\n\n        using_synthetic = not self._has_real_data(symbol)\n        result_dict['using_synthetic_data'] = using_synthetic\n        result_dict['optimization'] = {\n            'objective': objective,\n            'objective_value': float(stats.get(maximize_metric, 0)),\n            'best_params': optimal_params,\n            'iterations': int(max_iterations),\n            'attrs_optimized': list(opt_kwargs.keys()),\n            'attrs_skipped': skipped,\n        }\n\n        self._log(\n            f\"Optimization done: best {maximize_metric} = \"\n            f\"{result_dict['optimization']['objective_value']:.4f} with {optimal_params}\"\n        )\n        return {'success': True, 'message': 'Optimization completed', 'data': result_dict}\n\n    except Exception as e:\n        self._error('Optimization failed', e)\n        import traceback\n        return self._create_error_result(f'Optimization failed: {str(e)}\\n{traceback.format_exc()}')\n",
      "asOf": "2026-11-17"
    },
    "F53": {
      "label": "Project function reference, backtesting",
      "display": "backtestingpy_provider.py · optimize()",
      "asOf": "2026-11-17"
    },
    "F54": {
      "label": "Project repository, backtesting",
      "display": "Fincept-Corporation/FinceptTerminal",
      "asOf": "2026-11-17"
    },
    "F55": {
      "label": "Project stars, Fincept-Corporation/FinceptTerminal",
      "display": "33.9K",
      "asOf": "2026-11-17"
    },
    "F56": {
      "label": "Project push date, Fincept-Corporation/FinceptTerminal",
      "display": "Nov 2026",
      "asOf": "2026-11-13"
    },
    "F57": {
      "label": "Library name, backtrader",
      "display": "backtrader",
      "asOf": "2026-11-17"
    },
    "F58": {
      "label": "Monthly downloads, backtrader",
      "display": "232.8K",
      "asOf": "2026-11-16"
    },
    "F59": {
      "label": "License, backtrader",
      "display": "GPLv3+",
      "asOf": "2026-11-17"
    },
    "F60": {
      "label": "Package release, backtrader",
      "display": "1.9.78.123, Apr 2023",
      "asOf": "2023-04-19"
    },
    "F61": {
      "label": "Package release date, backtrader",
      "display": "Apr 2023",
      "asOf": "2023-04-19"
    },
    "F62": {
      "label": "Repository stars, backtrader",
      "display": "23.8K",
      "asOf": "2026-11-17"
    },
    "F63": {
      "label": "Simulates multiple assets, backtrader",
      "display": "Built-in",
      "asOf": "2026-11-17"
    },
    "F64": {
      "label": "Evaluates parameter grids, backtrader",
      "display": "Built-in",
      "asOf": "2026-11-17"
    },
    "F65": {
      "label": "Models transaction costs, backtrader",
      "display": "Built-in",
      "asOf": "2026-11-17"
    },
    "F66": {
      "label": "Supports short positions, backtrader",
      "display": "Built-in",
      "asOf": "2026-11-17"
    },
    "F67": {
      "label": "Install, backtrader",
      "display": "pip install backtrader",
      "asOf": "2026-11-17"
    },
    "F68": {
      "label": "What it does, backtrader",
      "display": "Simulates trading strategies with multiple data feeds, order types, and broker behavior.",
      "asOf": "2026-11-17"
    },
    "F69": {
      "label": "strengths lead, backtrader",
      "display": "Combines feeds and timeframes",
      "asOf": "2026-11-17"
    },
    "F70": {
      "label": "strengths, backtrader",
      "display": "Run multiple data feeds and timeframes within the same strategy.",
      "asOf": "2026-11-17"
    },
    "F71": {
      "label": "strengths lead, backtrader",
      "display": "Searches strategy parameter ranges",
      "asOf": "2026-11-17"
    },
    "F72": {
      "label": "strengths, backtrader",
      "display": "Use optstrategy to run a strategy with different parameter values.",
      "asOf": "2026-11-17"
    },
    "F73": {
      "label": "limitations lead, backtrader",
      "display": "Market orders fill next bar",
      "asOf": "2026-11-17"
    },
    "F74": {
      "label": "limitations, backtrader",
      "display": "By default, market orders execute at the following bar’s open.",
      "asOf": "2026-11-17"
    },
    "F75": {
      "label": "limitations lead, backtrader",
      "display": "Default fills ignore available volume",
      "asOf": "2026-11-17"
    },
    "F76": {
      "label": "limitations, backtrader",
      "display": "Configure a filler when simulated fills must respect available volume.",
      "asOf": "2026-11-17"
    },
    "F77": {
      "label": "Quickstart, backtrader",
      "display": "from __future__ import (absolute_import, division, print_function,\n                        unicode_literals)\n\nimport datetime  # For datetime objects\nimport os.path  # To manage paths\nimport sys  # To find out the script name (in argv[0])\n\n# Import the backtrader platform\nimport backtrader as bt\n\n# Create a Stratey\nclass TestStrategy(bt.Strategy):\n\n    def log(self, txt, dt=None):\n        ''' Logging function fot this strategy'''\n        dt = dt or self.datas[0].datetime.date(0)\n        print('%s, %s' % (dt.isoformat(), txt))\n\n    def __init__(self):\n        # Keep a reference to the \"close\" line in the data[0] dataseries\n        self.dataclose = self.datas[0].close\n\n    def next(self):\n        # Simply log the closing price of the series from the reference\n        self.log('Close, %.2f' % self.dataclose[0])\n\n        if self.dataclose[0] < self.dataclose[-1]:\n            # current close less than previous close\n\n            if self.dataclose[-1] < self.dataclose[-2]:\n                # previous close less than the previous close\n\n                # BUY, BUY, BUY!!! (with all possible default parameters)\n                self.log('BUY CREATE, %.2f' % self.dataclose[0])\n                self.buy()\n\nif __name__ == '__main__':\n    # Create a cerebro entity\n    cerebro = bt.Cerebro()\n\n    # Add a strategy\n    cerebro.addstrategy(TestStrategy)\n\n    # Datas are in a subfolder of the samples. Need to find where the script is\n    # because it could have been called from anywhere\n    modpath = os.path.dirname(os.path.abspath(sys.argv[0]))\n    datapath = os.path.join(modpath, '../../datas/orcl-1995-2014.txt')\n\n    # Create a Data Feed\n    data = bt.feeds.YahooFinanceCSVData(\n        dataname=datapath,\n        # Do not pass values before this date\n        fromdate=datetime.datetime(2000, 1, 1),\n        # Do not pass values before this date\n        todate=datetime.datetime(2000, 12, 31),\n        # Do not pass values after this date\n        reverse=False)\n\n    # Add the Data Feed to Cerebro\n    cerebro.adddata(data)\n\n    # Set our desired cash start\n    cerebro.broker.setcash(100000.0)\n\n    # Print out the starting conditions\n    print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())\n\n    # Run over everything\n    cerebro.run()\n\n    # Print out the final result\n    print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())\n\n",
      "asOf": "2026-11-17"
    },
    "F78": {
      "label": "Project function, backtrader",
      "display": "def __init__(self):\n    self.dataclose = self.datas[0].close\n    self.order = None\n    self.buyprice = None\n    self.buycomm = None\n    self.sma = btind.SimpleMovingAverage(\n        self.datas[0], period=self.params.maperiod\n    )\n    self.rsi = btind.RelativeStrengthIndex()\n",
      "asOf": "2026-11-17"
    },
    "F79": {
      "label": "Project function reference, backtrader",
      "display": "multi_strategy_bt.py · __init__()",
      "asOf": "2026-11-17"
    },
    "F80": {
      "label": "Project repository, backtrader",
      "display": "UFund-Me/Qbot",
      "asOf": "2026-11-17"
    },
    "F81": {
      "label": "Project stars, UFund-Me/Qbot",
      "display": "18.8K",
      "asOf": "2026-11-17"
    },
    "F82": {
      "label": "Project push date, UFund-Me/Qbot",
      "display": "Mar 2026",
      "asOf": "2026-03-11"
    },
    "F83": {
      "label": "Library name, bt",
      "display": "bt",
      "asOf": "2026-11-17"
    },
    "F84": {
      "label": "Monthly downloads, bt",
      "display": "62.2K",
      "asOf": "2026-11-16"
    },
    "F85": {
      "label": "License, bt",
      "display": "MIT",
      "asOf": "2026-11-17"
    },
    "F86": {
      "label": "Package release, bt",
      "display": "1.4.1, Oct 2026",
      "asOf": "2026-10-10"
    },
    "F87": {
      "label": "Package release date, bt",
      "display": "Oct 2026",
      "asOf": "2026-10-10"
    },
    "F88": {
      "label": "Repository stars, bt",
      "display": "3.0K",
      "asOf": "2026-11-17"
    },
    "F89": {
      "label": "Simulates multiple assets, bt",
      "display": "Built-in",
      "asOf": "2026-11-17"
    },
    "F90": {
      "label": "Models transaction costs, bt",
      "display": "Built-in",
      "asOf": "2026-11-17"
    },
    "F91": {
      "label": "Supports short positions, bt",
      "display": "Built-in",
      "asOf": "2026-11-17"
    },
    "F92": {
      "label": "Install, bt",
      "display": "pip install bt",
      "asOf": "2026-11-17"
    },
    "F93": {
      "label": "What it does, bt",
      "display": "Builds allocation strategies from reusable algorithms and combines them into portfolio trees.",
      "asOf": "2026-11-17"
    },
    "F94": {
      "label": "strengths lead, bt",
      "display": "Combines strategies into portfolios",
      "asOf": "2026-11-17"
    },
    "F95": {
      "label": "strengths, bt",
      "display": "Nest strategies and securities in a common portfolio tree.",
      "asOf": "2026-11-17"
    },
    "F96": {
      "label": "strengths lead, bt",
      "display": "Models nonlinear transaction costs",
      "asOf": "2026-11-17"
    },
    "F97": {
      "label": "strengths, bt",
      "display": "Use cost models that account for order size, volume, and volatility.",
      "asOf": "2026-11-17"
    },
    "F98": {
      "label": "limitations lead, bt",
      "display": "Positions default to whole shares",
      "asOf": "2026-11-17"
    },
    "F99": {
      "label": "limitations, bt",
      "display": "Set integer_positions=False when fractional allocations are required.",
      "asOf": "2026-11-17"
    },
    "F100": {
      "label": "limitations lead, bt",
      "display": "Impact models need additional data",
      "asOf": "2026-11-17"
    },
    "F101": {
      "label": "limitations, bt",
      "display": "Supply volume and volatility data when commissions uses a CostModel.",
      "asOf": "2026-11-17"
    },
    "F102": {
      "label": "Quickstart, bt",
      "display": "import numpy as np\nimport pandas as pd\n\nimport bt\n\nprices = pd.DataFrame(\n    {\n        \"asset_a\": np.linspace(100, 120, 252),\n        \"asset_b\": np.linspace(100, 110, 252),\n    },\n    index=pd.bdate_range(\"2020-01-01\", periods=252),\n)\n\nstrategy = bt.Strategy(\n    \"equal_weight\",\n    [\n        bt.algos.RunMonthly(),\n        bt.algos.SelectAll(),\n        bt.algos.WeighEqually(),\n        bt.algos.Rebalance(),\n    ],\n)\nresult = bt.run(bt.Backtest(strategy, prices))\nresult.display()\n",
      "asOf": "2026-11-17"
    },
    "F103": {
      "label": "Developer need",
      "display": "Bar-by-bar order simulation",
      "asOf": "2026-11-17"
    },
    "F104": {
      "label": "Why choose backtrader",
      "display": "multiple feeds and timeframes in a strategy",
      "asOf": "2026-11-17"
    },
    "F105": {
      "label": "Developer need in introduction",
      "display": "bar-by-bar order simulation",
      "asOf": "2026-11-17"
    },
    "F106": {
      "label": "When to consider backtesting",
      "display": "built-in parameter search is the main requirement",
      "asOf": "2026-11-17"
    },
    "F107": {
      "label": "Developer need",
      "display": "Strategy parameter searches",
      "asOf": "2026-11-17"
    },
    "F108": {
      "label": "Why choose backtesting",
      "display": "parameter combinations and optional constraints",
      "asOf": "2026-11-17"
    },
    "F109": {
      "label": "Developer need in introduction",
      "display": "strategy parameter searches",
      "asOf": "2026-11-17"
    },
    "F110": {
      "label": "Developer need",
      "display": "Array-based strategy experiments",
      "asOf": "2026-11-17"
    },
    "F111": {
      "label": "Why choose vectorbt",
      "display": "array inputs across assets and parameters",
      "asOf": "2026-11-17"
    },
    "F112": {
      "label": "Developer need in introduction",
      "display": "array-based strategy experiments",
      "asOf": "2026-11-17"
    },
    "F113": {
      "label": "When to consider bt",
      "display": "nested allocation strategies better match the problem",
      "asOf": "2026-11-17"
    },
    "F114": {
      "label": "Developer need",
      "display": "Portfolio allocation trees",
      "asOf": "2026-11-17"
    },
    "F115": {
      "label": "Why choose bt",
      "display": "nested strategies and securities",
      "asOf": "2026-11-17"
    },
    "F116": {
      "label": "Developer need in introduction",
      "display": "portfolio allocation trees",
      "asOf": "2026-11-17"
    },
    "F117": {
      "label": "When to consider vectorbt",
      "display": "array-shaped assets and parameter experiments fit the workload",
      "asOf": "2026-11-17"
    },
    "F118": {
      "label": "Page introduction",
      "display": "Python backtesting libraries let developers evaluate trading strategies using historical data.",
      "asOf": "2026-11-17"
    },
    "F119": {
      "label": "FAQ: Which Python backtesting library should I choose?",
      "display": "backtrader supports multiple feeds and timeframes.",
      "asOf": "2026-11-17"
    },
    "F120": {
      "label": "FAQ: Which Python backtesting library should I choose?",
      "display": "Backtesting.py searches parameter combinations.",
      "asOf": "2026-11-17"
    },
    "F121": {
      "label": "FAQ: Which Python backtesting library should I choose?",
      "display": "VectorBT broadcasts array inputs.",
      "asOf": "2026-11-17"
    },
    "F122": {
      "label": "FAQ: Which Python backtesting library should I choose?",
      "display": "bt nests strategies and securities in a shared portfolio tree.",
      "asOf": "2026-11-17"
    },
    "F123": {
      "label": "FAQ: When does a backtrader market order execute?",
      "display": "By default, a market order executes at the next bar’s opening price.",
      "asOf": "2026-11-17"
    },
    "F124": {
      "label": "FAQ: Does backtrader limit simulated fills to bar volume by default?",
      "display": "Its default filler setting executes the order in a single shot.",
      "asOf": "2026-11-17"
    },
    "F125": {
      "label": "FAQ: Does backtrader limit simulated fills to bar volume by default?",
      "display": "A custom filler receives the order, price and bar index and returns the executed size.",
      "asOf": "2026-11-17"
    },
    "F126": {
      "label": "FAQ: How does Backtesting.py charge commission?",
      "display": "Commission is applied at trade entry and exit.",
      "asOf": "2026-11-17"
    },
    "F127": {
      "label": "FAQ: How does Backtesting.py charge commission?",
      "display": "Commission can be a fixed-plus-relative tuple or a callable.",
      "asOf": "2026-11-17"
    },
    "F128": {
      "label": "FAQ: Can Backtesting.py trade fractional units?",
      "display": "Use the FractionalBacktest class for fractional-unit strategies.",
      "asOf": "2026-11-17"
    },
    "F129": {
      "label": "FAQ: Does Backtesting.py distinguish margin types?",
      "display": "Initial and maintenance margins use the same setting.",
      "asOf": "2026-11-17"
    },
    "F130": {
      "label": "FAQ: Why does VectorBT ignore a repeated entry signal?",
      "display": "The default signals mode does not add another entry while already in a position.",
      "asOf": "2026-11-17"
    },
    "F131": {
      "label": "FAQ: Why does VectorBT ignore a repeated entry signal?",
      "display": "Enable accumulate for behavior closer to from_orders.",
      "asOf": "2026-11-17"
    },
    "F132": {
      "label": "FAQ: When should VectorBT use a custom order function?",
      "display": "Use from_order_func when signals depend on complex conditions or generate multiple orders at once.",
      "asOf": "2026-11-17"
    },
    "F133": {
      "label": "FAQ: How can bt simulate fractional positions?",
      "display": "The integer_positions setting defaults to True; set it to False for fractional positions.",
      "asOf": "2026-11-17"
    },
    "F134": {
      "label": "FAQ: What data do bt impact cost models need?",
      "display": "Provide volume and volatility with a CostModel; a simple commissions callable is a separate option.",
      "asOf": "2026-11-17"
    },
    "F135": {
      "label": "FAQ: Which compared library saves an interactive HTML plot?",
      "display": "Backtesting.py plot accepts a filename for its interactive HTML output.",
      "asOf": "2026-11-17"
    },
    "F136": {
      "label": "Library name, nautilus-trader",
      "display": "NautilusTrader",
      "asOf": "2026-11-20"
    },
    "F137": {
      "label": "Monthly downloads, nautilus-trader",
      "display": "667.0K",
      "asOf": "2026-11-20"
    },
    "F138": {
      "label": "License, nautilus-trader",
      "display": "LGPL-3.0-or-later",
      "asOf": "2026-11-20"
    },
    "F139": {
      "label": "Package release, nautilus-trader",
      "display": "1.231.0",
      "asOf": "2026-11-20"
    },
    "F140": {
      "label": "Package release date, nautilus-trader",
      "display": "Aug 2026",
      "asOf": "2026-11-20"
    },
    "F141": {
      "label": "Install, nautilus-trader",
      "display": "pip install nautilus-trader",
      "asOf": "2026-11-20"
    },
    "F142": {
      "label": "Quickstart, nautilus-trader",
      "display": "# %% [markdown]\n# # Backtest (Low-Level API)\n#\n# Use `BacktestEngine` for direct component access: load market data, wire up\n# strategies and execution algorithms, and run backtests with full control over\n# every step. This tutorial backtests an EMA cross strategy with a TWAP execution\n# algorithm on a simulated Binance Spot exchange using historical trade tick data.\n#\n# [View source on GitHub](https://github.com/nautechsystems/nautilus_trader/blob/develop/docs/getting_started/backtest_low_level.py).\n\n# %% [markdown]\n# ## Prerequisites\n# - Python 3.12+\n# - [NautilusTrader](https://pypi.org/project/nautilus_trader/) latest release installed (`pip install nautilus_trader`)\n\n# %%\nfrom decimal import Decimal\n\nfrom nautilus_trader.backtest.config import BacktestEngineConfig\nfrom nautilus_trader.backtest.engine import BacktestEngine\nfrom nautilus_trader.examples.algorithms.twap import TWAPExecAlgorithm\nfrom nautilus_trader.examples.strategies.ema_cross_twap import EMACrossTWAP\nfrom nautilus_trader.examples.strategies.ema_cross_twap import EMACrossTWAPConfig\nfrom nautilus_trader.model import BarType\nfrom nautilus_trader.model import Money\nfrom nautilus_trader.model import TraderId\nfrom nautilus_trader.model import Venue\nfrom nautilus_trader.model.currencies import ETH\nfrom nautilus_trader.model.currencies import USDT\nfrom nautilus_trader.model.enums import AccountType\nfrom nautilus_trader.model.enums import OmsType\nfrom nautilus_trader.persistence.wranglers import TradeTickDataWrangler\nfrom nautilus_trader.test_kit.providers import TestDataProvider\nfrom nautilus_trader.test_kit.providers import TestInstrumentProvider\n\n# %% [markdown]\n# ## Load data\n#\n# Load bundled test data (ETHUSDT trades from Binance), initialize the matching\n# instrument, and wrangle the raw CSV into Nautilus `TradeTick` objects.\n\n# %%\n# Load stub test data\nprovider = TestDataProvider()\ntrades_df = provider.read_csv_ticks(\"binance/ethusdt-trades.csv\")\n\n# Initialize the instrument which matches the data\nETHUSDT_BINANCE = TestInstrumentProvider.ethusdt_binance()\n\n# Process into Nautilus objects\nwrangler = TradeTickDataWrangler(instrument=ETHUSDT_BINANCE)\nticks = wrangler.process(trades_df)\n\n# %% [markdown]\n# See the [Data](../concepts/data.md) concept guide for details on the data processing pipeline.\n\n# %% [markdown]\n# ## Initialize the engine\n#\n# Pass a `BacktestEngineConfig` to configure the engine. Here we set a custom\n# `trader_id` to show the pattern.\n\n# %%\n# Configure backtest engine\nconfig = BacktestEngineConfig(trader_id=TraderId(\"BACKTESTER-001\"))\n\n# Build the backtest engine\nengine = BacktestEngine(config=config)\n\n# %% [markdown]\n# ## Add a venue\n#\n# Set up a simulated venue that matches the market data. Here we configure a\n# Binance Spot exchange with a cash account.\n\n# %%\n# Add a trading venue (multiple venues possible)\nBINANCE = Venue(\"BINANCE\")\nengine.add_venue(\n    venue=BINANCE,\n    oms_type=OmsType.NETTING,\n    account_type=AccountType.CASH,  # Spot CASH account (not for perpetuals or futures)\n    base_currency=None,  # Multi-currency account\n    starting_balances=[Money(1_000_000.0, USDT), Money(10.0, ETH)],\n)\n\n# %% [markdown]\n# ## Add data\n#\n# Add the instrument and trade ticks to the engine.\n\n# %%\n# Add instrument(s)\nengine.add_instrument(ETHUSDT_BINANCE)\n\n# Add data\nengine.add_data(ticks)\n\n# %% [markdown]\n# :::note\n# You can add multiple data types (including custom types) and backtest across multiple venues.\n# :::\n#\n\n# %% [markdown]\n# ## Add strategies\n#\n# Configure and add an EMA cross strategy with TWAP execution parameters.\n\n# %%\n# Configure your strategy\nstrategy_config = EMACrossTWAPConfig(\n    instrument_id=ETHUSDT_BINANCE.id,\n    bar_type=BarType.from_str(\"ETHUSDT.BINANCE-250-TICK-LAST-INTERNAL\"),\n    trade_size=Decimal(\"0.10\"),\n    fast_ema_period=10,\n    slow_ema_period=20,\n    twap_horizon_secs=10.0,\n    twap_interval_secs=2.5,\n)\n\n# Instantiate and add your strategy\nstrategy = EMACrossTWAP(config=strategy_config)\nengine.add_strategy(strategy=strategy)\n\n# %% [markdown]\n# The strategy config references TWAP parameters, but the execution algorithm\n# itself is a separate component.\n#\n# ## Add execution algorithms\n#\n# Add a TWAP execution algorithm to the engine.\n\n# %%\n# Instantiate and add your execution algorithm\nexec_algorithm = TWAPExecAlgorithm()  # Using defaults\nengine.add_exec_algorithm(exec_algorithm)\n\n# %% [markdown]\n# ## Run the backtest\n#\n# Call `.run()` to process all available data. The engine replays events in\n# timestamp order with deterministic execution semantics.\n\n# %%\n# Run the engine (from start to end of data)\nengine.run()\n\n# %% [markdown]\n# ## Post-run analysis\n#\n# The engine retains data and execution objects in memory for generating reports.\n# It also logs a tearsheet with default statistics; see the\n# [Portfolio statistics](../concepts/portfolio.md#portfolio-statistics) guide for\n# custom statistics.\n\n# %%\nengine.trader.generate_account_report(BINANCE)\n\n# %%\nengine.trader.generate_order_fills_report()\n\n# %%\nengine.trader.generate_positions_report()\n\n# %% [markdown]\n# ## Repeated runs\n#\n# Reset the engine for repeated runs. Instruments, data, and loaded components\n# persist across resets; loaded components have their internal state reset.\n\n# %%\n# For repeated backtest runs, reset the engine\nengine.reset()\n\n# Clear or remove loaded components before adding replacements.\n\n# %% [markdown]\n# Remove and add individual components (actors, strategies, execution algorithms) as required.\n#\n# See the [Trader](../api_reference/trading.md) API reference for a description of all methods available to achieve this.\n#\n\n# %%\n# Once done, good practice to dispose of the object if the script continues\nengine.dispose()\n",
      "asOf": "2026-11-20"
    },
    "F143": {
      "label": "Official description, nautilus-trader",
      "display": "Runs an event-driven trading engine with a Rust core.",
      "asOf": "2026-11-20"
    },
    "F144": {
      "label": "Quickstart source file, nautilus-trader",
      "display": "docs/getting_started/backtest_low_level.py",
      "asOf": "2026-11-20"
    },
    "F145": {
      "label": "Repository stars, nautilus-trader",
      "display": "31.7K",
      "asOf": "2026-11-20"
    },
    "F146": {
      "label": "Multi-asset portfolios, nautilus-trader",
      "display": "Yes",
      "asOf": "2026-11-20"
    },
    "F147": {
      "label": "Live broker adapters, nautilus-trader",
      "display": "Yes",
      "asOf": "2026-11-20"
    },
    "F148": {
      "label": "Python requirement, nautilus-trader",
      "display": "<3.15,>=3.12",
      "asOf": "2026-11-20"
    },
    "F149": {
      "label": "Primary package role, nautilus-trader",
      "display": "Production-grade Rust-native trading engine with deterministic event-driven architecture",
      "asOf": "2026-11-20"
    },
    "F150": {
      "label": "Library name, vectorbt",
      "display": "vectorbt",
      "asOf": "2026-11-20"
    },
    "F151": {
      "label": "Monthly downloads, vectorbt",
      "display": "389.4K",
      "asOf": "2026-11-20"
    },
    "F152": {
      "label": "License, vectorbt",
      "display": "Apache-2.0 with Commons Clause",
      "asOf": "2026-11-20"
    },
    "F153": {
      "label": "Package release, vectorbt",
      "display": "1.2.1",
      "asOf": "2026-11-20"
    },
    "F154": {
      "label": "Package release date, vectorbt",
      "display": "Nov 2026",
      "asOf": "2026-11-20"
    },
    "F155": {
      "label": "Install, vectorbt",
      "display": "pip install vectorbt",
      "asOf": "2026-11-20"
    },
    "F156": {
      "label": "Quickstart, vectorbt",
      "display": "import pandas as pd\nimport vectorbt as vbt\n\nclose = pd.Series(\n    [100.0, 102.0, 101.0, 104.0, 103.0, 107.0],\n    index=pd.date_range(\"2024-01-01\", periods=6, freq=\"D\"),\n    name=\"Close\",\n)\npf = vbt.Portfolio.from_holding(close, init_cash=1000, fees=0.001, freq=\"1D\")\nprint(round(float(pf.total_return()) * 100, 2))\n\n",
      "asOf": "2026-11-20"
    },
    "F157": {
      "label": "Repository stars, vectorbt",
      "display": "9.9K",
      "asOf": "2026-11-20"
    },
    "F158": {
      "label": "Multi-asset portfolios, vectorbt",
      "display": "Yes",
      "asOf": "2026-11-20"
    },
    "F159": {
      "label": "Live broker adapters, vectorbt",
      "display": "Undocumented",
      "asOf": "2026-11-20"
    },
    "F160": {
      "label": "Python requirement, vectorbt",
      "display": "<3.15,>=3.11",
      "asOf": "2026-11-20"
    },
    "F161": {
      "label": "Primary package role, vectorbt",
      "display": "Python library for backtesting and analyzing trading strategies at scale",
      "asOf": "2026-11-20"
    },
    "F162": {
      "label": "License condition, vectorbt",
      "display": "Apache 2.0 with Commons Clause",
      "asOf": "2026-11-20"
    },
    "F163": {
      "label": "Portfolio grouping, vectorbt",
      "display": "Independent columns or configured shared cash",
      "asOf": "2026-11-20"
    },
    "F164": {
      "label": "Project function, vectorbt",
      "display": "def backtest(self, ohlcv, variables=None, filters=None, lookback=None, plot=False, signals=False,\n             side='long', cscv_nbins=10, cscv_objective=lambda r: r.mean(), html=None, compounded=True,\n             execution_price='close', k_colors='world', **args):\n    \"\"\"Backtest the strategy with vectorbt.\n\n    Args:\n      ohlcv: OHLCV DataFrame.\n      variables: Strategy parameters. Lists or arrays are optimised over;\n        ``sl_stop``, ``tp_stop``, ``ts_stop`` add stop-loss, take-profit\n        and trailing-stop exits.\n      filters: {name: Filter.create(...)} conditions for entries.\n      lookback: Only use the latest ``lookback`` bars.\n      plot: Show the interactive chart (one parameter set) or the\n        optimisation dashboard with overfitting analysis (many sets).\n      signals: Return ``(entries, exits, figures)`` instead of backtesting.\n      side: Only 'long' is supported.\n      cscv_nbins: Number of blocks for the overfitting analysis.\n      cscv_objective: Performance measure for the overfitting analysis.\n      html: Also save the interactive chart to this file.\n      compounded: Reinvest profits; otherwise trade a fixed size.\n      execution_price: 'close' trades at the signal bar's close, 'open'\n        at the next bar's open.\n      k_colors: Candle colors, 'world', 'taiwan' or\n        {'increasing_line': color, 'decreasing_line': color}.\n      **args: Passed to ``vbt.Portfolio.from_signals`` (ex: ``freq='4h'``, ``fees``).\n\n    Returns:\n      vbt.Portfolio\n    \"\"\"\n    if side == 'short':\n        raise NotImplementedError('Shorting is not supported yet')\n    if side != 'long':\n        raise ValueError(\"side should be 'long' or 'short'\")\n    if execution_price not in EXECUTION_PRICES:\n        raise ValueError(f'execution_price should be one of {EXECUTION_PRICES}')\n\n    variables = dict(variables or {})\n    stop_vars = {name: variables.pop(name) for name in STOP_VARIABLES if name in variables}\n    ohlcv = ohlcv.iloc[-lookback:] if lookback else ohlcv\n\n    parameter_sets = enumerate_variables(variables) or [self._default_parameters]\n    entries, exits, fig_data = enumerate_signal(ohlcv, self, parameter_sets)\n    if filters:\n        filter_results = {name: create(ohlcv) for name, create in filters.items()}\n        entries, exits, fig_data = self._add_filters(entries, exits, fig_data, filter_results)\n    entries, exits = stop_early(ohlcv, entries, exits, stop_vars)\n    entries, exits = entries.squeeze(axis=1), exits.squeeze(axis=1)\n\n    if signals:\n        return entries, exits, fig_data\n\n    if not compounded:\n        args['size'] = vbt.settings.portfolio['init_cash'] / ohlcv.close.iloc[0]\n    price = ohlcv.close if execution_price == 'close' else ohlcv.open.shift(-1)\n    portfolio = vbt.Portfolio.from_signals(price, _as_bool(entries), _as_bool(exits), **args)\n\n    if isinstance(entries, pd.Series):\n        if plot or html is not None:\n            plot_strategy(ohlcv, entries, exits, portfolio, fig_data, html=html, k_colors=k_colors)\n    elif plot:\n        cscv = CSCV(n_bins=cscv_nbins, objective=cscv_objective)\n        cscv.add_daily_returns(portfolio.daily_returns())\n        plot_combination(portfolio, cscv.estimate_overfitting())\n        plt.show()\n        variable_visualization(portfolio)\n\n    return portfolio",
      "asOf": "2026-11-20"
    },
    "F165": {
      "label": "Project source file, vectorbt",
      "display": "finlab_crypto/strategy.py",
      "asOf": "2026-11-20"
    },
    "F166": {
      "label": "Project full_name, vectorbt",
      "display": "finlab-python/finlab_crypto",
      "asOf": "2026-11-20"
    },
    "F167": {
      "label": "Project stargazers_count, vectorbt",
      "display": "293",
      "asOf": "2026-11-20"
    },
    "F168": {
      "label": "Library name, backtesting",
      "display": "Backtesting.py",
      "asOf": "2026-11-20"
    },
    "F169": {
      "label": "Monthly downloads, backtesting",
      "display": "245.8K",
      "asOf": "2026-11-20"
    },
    "F170": {
      "label": "License, backtesting",
      "display": "AGPL-3.0",
      "asOf": "2026-11-20"
    },
    "F171": {
      "label": "Package release, backtesting",
      "display": "0.6.6",
      "asOf": "2026-11-20"
    },
    "F172": {
      "label": "Package release date, backtesting",
      "display": "Jul 2026",
      "asOf": "2026-11-20"
    },
    "F173": {
      "label": "Install, backtesting",
      "display": "pip install backtesting",
      "asOf": "2026-11-20"
    },
    "F174": {
      "label": "Quickstart, backtesting",
      "display": "from backtesting import Backtest, Strategy\nfrom backtesting.lib import crossover\n\nfrom backtesting.test import SMA, GOOG\n\n\nclass SmaCross(Strategy):\n    def init(self):\n        price = self.data.Close\n        self.ma1 = self.I(SMA, price, 10)\n        self.ma2 = self.I(SMA, price, 20)\n\n    def next(self):\n        if crossover(self.ma1, self.ma2):\n            self.buy()\n        elif crossover(self.ma2, self.ma1):\n            self.sell()\n\n\nbt = Backtest(GOOG, SmaCross, commission=.002,\n              exclusive_orders=True)\nstats = bt.run()\nbt.plot()\n",
      "asOf": "2026-11-20"
    },
    "F175": {
      "label": "Repository stars, backtesting",
      "display": "9.3K",
      "asOf": "2026-11-20"
    },
    "F176": {
      "label": "Multi-asset portfolios, backtesting",
      "display": "No",
      "asOf": "2026-11-20"
    },
    "F177": {
      "label": "Live broker adapters, backtesting",
      "display": "No",
      "asOf": "2026-11-20"
    },
    "F178": {
      "label": "Python requirement, backtesting",
      "display": ">=3.9",
      "asOf": "2026-11-20"
    },
    "F179": {
      "label": "Primary package role, backtesting",
      "display": "Backtest trading strategies in Python",
      "asOf": "2026-11-20"
    },
    "F180": {
      "label": "Simulation unit, backtesting",
      "display": "One tradeable asset per backtest",
      "asOf": "2026-11-20"
    },
    "F181": {
      "label": "Project function, backtesting",
      "display": "def optimize(self, request: Dict[str, Any]) -> Dict[str, Any]:\n    \"\"\"Run parameter optimization via backtesting.py's `bt.optimize`.\n\n    The frontend sweeps strategy params under their *frontend* names (e.g.\n    `fastPeriod`); backtesting.py optimizes class-level attribute names\n    (e.g. `n1`). `btp_strategies.STRATEGY_OPTIMIZE_PARAM_MAP` translates.\n\n    Returns the same shape as run_backtest (`data.performance`, `data.trades`,\n    `data.equity`) so the existing screen renderer works unchanged, plus\n    optimization-specific fields under `data.optimization`.\n    \"\"\"\n    try:\n        self._log('Starting parameter optimization')\n\n        strategy_def = request.get('strategy', {})\n        strategy_type = strategy_def.get('type', 'sma_crossover')\n        # Frontend canonical name is `paramRanges`; legacy callers used `parameters`.\n        param_ranges = request.get('paramRanges', {}) or request.get('parameters', {})\n        objective = request.get('optimizeObjective') or request.get('metric', 'sharpe')\n        start_date = request.get('startDate')\n        end_date = request.get('endDate')\n        initial_capital = request.get('initialCapital', 10000)\n        max_iterations = int(request.get('maxIterations', 500) or 500)\n\n        # Canonical: `symbols: [str]`. Fallback: `assets: [{symbol, ...}]`.\n        symbols = request.get('symbols', [])\n        if not symbols:\n            assets = request.get('assets', [])\n            symbols = [a.get('symbol') for a in assets if isinstance(a, dict) and a.get('symbol')]\n\n        if not param_ranges:\n            return self._create_error_result('No parameter ranges supplied (expected paramRanges)')\n\n        symbol = symbols[0] if symbols else 'SPY'\n        data = self._load_data(symbol, start_date, end_date, request.get('interval', '1d'))\n        if data is None or len(data) == 0:\n            return self._create_error_result(f'No data available for {symbol}')\n\n        # Build the strategy class with default params; bt.optimize will\n        # sweep class-level attributes from there.\n        strategy_class = self._create_strategy_class(strategy_def)\n\n        # Translate frontend param names -> class attribute names per strategy.\n        import btp_strategies as _strat\n        mapped_ranges = _strat.map_optimize_params(strategy_type, param_ranges)\n\n        # Build python ranges. Drop any range that targets an attribute the\n        # strategy class doesn't declare — backtesting.py would reject it\n        # otherwise and we'd get the cryptic \"missing parameter X\" error.\n        opt_kwargs = {}\n        skipped: List[str] = []\n        for cattr, cfg in mapped_ranges.items():\n            if not hasattr(strategy_class, cattr):\n                skipped.append(cattr)\n                continue\n            try:\n                lo = int(cfg.get('min', 1))\n                hi = int(cfg.get('max', 100))\n                step = max(1, int(cfg.get('step', 1)))\n            except Exception:\n                continue\n            if hi < lo:\n                lo, hi = hi, lo\n            opt_kwargs[cattr] = range(lo, hi + 1, step)\n\n        if not opt_kwargs:\n            return self._create_error_result(\n                f\"No optimizable parameters for strategy '{strategy_type}'. \"\n                f\"Mapped attrs not present on class: {skipped}\"\n            )\n\n        if skipped:\n            self._log(f'Skipped non-class attrs during optimize: {skipped}')\n\n        from backtesting import Backtest\n        bt = Backtest(\n            data, strategy_class,\n            cash=initial_capital,\n            commission=float(request.get('commission', 0.0) or 0.0) + float(request.get('slippage', 0.0) or 0.0),\n        )\n\n        # Map frontend objective to backtesting.py stat key.\n        metric_map = {\n            'sharpe':  'Sharpe Ratio',\n            'sortino': 'Sortino Ratio',\n            'calmar':  'Calmar Ratio',\n            'return':  'Return [%]',\n            # Tolerate human-readable variants for callers outside the screen.\n            'Sharpe Ratio': 'Sharpe Ratio',\n            'Sortino Ratio': 'Sortino Ratio',\n            'Calmar Ratio': 'Calmar Ratio',\n            'Total Return': 'Return [%]',\n        }\n        maximize_metric = metric_map.get(objective, 'Sharpe Ratio')\n\n        self._log(f'Optimizing {len(opt_kwargs)} attrs (max_tries={max_iterations}) maximize={maximize_metric}')\n        stats = bt.optimize(**opt_kwargs, maximize=maximize_metric, max_tries=max_iterations)\n\n        # Extract chosen optimal params back under frontend names.\n        inverse_map = {cattr: fname for fname, cattr in\n                       _strat.STRATEGY_OPTIMIZE_PARAM_MAP.get(strategy_type, {}).items()}\n        optimal_params: Dict[str, Any] = {}\n        for cattr in opt_kwargs.keys():\n            if not hasattr(stats._strategy, cattr):\n                continue\n            fname = inverse_map.get(cattr, cattr)\n            val = getattr(stats._strategy, cattr)\n            optimal_params[fname] = int(val) if hasattr(val, '__int__') else val\n\n        # Wire shape: same as run_backtest so display_result() renders performance/trades.\n        result_dict = self._convert_results(\n            stats, symbol, start_date, end_date, initial_capital\n        ).to_dict()\n\n        using_synthetic = not self._has_real_data(symbol)\n        result_dict['using_synthetic_data'] = using_synthetic\n        result_dict['optimization'] = {\n            'objective': objective,\n            'objective_value': float(stats.get(maximize_metric, 0)),\n            'best_params': optimal_params,\n            'iterations': int(max_iterations),\n            'attrs_optimized': list(opt_kwargs.keys()),\n            'attrs_skipped': skipped,\n        }\n\n        self._log(\n            f\"Optimization done: best {maximize_metric} = \"\n            f\"{result_dict['optimization']['objective_value']:.4f} with {optimal_params}\"\n        )\n        return {'success': True, 'message': 'Optimization completed', 'data': result_dict}\n\n    except Exception as e:\n        self._error('Optimization failed', e)\n        import traceback\n        return self._create_error_result(f'Optimization failed: {str(e)}\\n{traceback.format_exc()}')",
      "asOf": "2026-11-20"
    },
    "F182": {
      "label": "Project source file, backtesting",
      "display": "fincept-qt/scripts/Analytics/backtesting/backtestingpy/backtestingpy_provider.py",
      "asOf": "2026-11-20"
    },
    "F183": {
      "label": "Project full_name, backtesting",
      "display": "Fincept-Corporation/FinceptTerminal",
      "asOf": "2026-11-20"
    },
    "F184": {
      "label": "Project stargazers_count, backtesting",
      "display": "33.9K",
      "asOf": "2026-11-20"
    },
    "F185": {
      "label": "Library name, backtrader",
      "display": "backtrader",
      "asOf": "2026-11-20"
    },
    "F186": {
      "label": "Monthly downloads, backtrader",
      "display": "229.9K",
      "asOf": "2026-11-20"
    },
    "F187": {
      "label": "License, backtrader",
      "display": "GPL-3.0-or-later",
      "asOf": "2026-11-20"
    },
    "F188": {
      "label": "Package release, backtrader",
      "display": "1.9.78.123",
      "asOf": "2026-11-20"
    },
    "F189": {
      "label": "Package release date, backtrader",
      "display": "Apr 2023",
      "asOf": "2026-11-20"
    },
    "F190": {
      "label": "Install, backtrader",
      "display": "pip install backtrader",
      "asOf": "2026-11-20"
    },
    "F191": {
      "label": "Quickstart, backtrader",
      "display": "import backtrader as bt\ncerebro = bt.Cerebro()\nprint(cerebro.broker.getvalue())\n",
      "asOf": "2026-11-20"
    },
    "F192": {
      "label": "Repository stars, backtrader",
      "display": "23.8K",
      "asOf": "2026-11-20"
    },
    "F193": {
      "label": "Multi-asset portfolios, backtrader",
      "display": "Yes",
      "asOf": "2026-11-20"
    },
    "F194": {
      "label": "Live broker adapters, backtrader",
      "display": "Yes",
      "asOf": "2026-11-20"
    },
    "F195": {
      "label": "Primary package role, backtrader",
      "display": "BackTesting Engine",
      "asOf": "2026-11-20"
    },
    "F196": {
      "label": "Project function, backtrader",
      "display": "def next(self):\n    self.log('Close, %.2f' % self.dataclose[0])\n    if self.order:\n        return\n    if not self.position:\n        if (self.rsi[0] < 50 and\n                self.rsi[-1] >= 50 and\n                self.dataclose[0] > self.sma[0]):\n            self.log('BUY CREATE, %.2f' % self.dataclose[0])\n            self.order = self.buy()\n    else:\n        if (self.rsi[0] > 50 and\n                self.rsi[-1] <= 50 and\n                self.dataclose[0] < self.sma[0]):\n            self.log('SELL CREATE, %.2f' % self.dataclose[0])\n            self.order = self.sell()",
      "asOf": "2026-11-20"
    },
    "F197": {
      "label": "Project source file, backtrader",
      "display": "qbot/strategies/multi_strategy_bt.py",
      "asOf": "2026-11-20"
    },
    "F198": {
      "label": "Project full_name, backtrader",
      "display": "UFund-Me/Qbot",
      "asOf": "2026-11-20"
    },
    "F199": {
      "label": "Project stargazers_count, backtrader",
      "display": "18.8K",
      "asOf": "2026-11-20"
    },
    "F200": {
      "label": "Library name, bt",
      "display": "bt",
      "asOf": "2026-11-20"
    },
    "F201": {
      "label": "Monthly downloads, bt",
      "display": "64.4K",
      "asOf": "2026-11-20"
    },
    "F202": {
      "label": "License, bt",
      "display": "MIT",
      "asOf": "2026-11-20"
    },
    "F203": {
      "label": "Package release, bt",
      "display": "1.4.1",
      "asOf": "2026-11-20"
    },
    "F204": {
      "label": "Package release date, bt",
      "display": "Oct 2026",
      "asOf": "2026-11-20"
    },
    "F205": {
      "label": "Install, bt",
      "display": "pip install bt",
      "asOf": "2026-11-20"
    },
    "F206": {
      "label": "Quickstart, bt",
      "display": "import numpy as np\nimport pandas as pd\n\nimport bt\n\nprices = pd.DataFrame(\n    {\n        \"asset_a\": np.linspace(100, 120, 252),\n        \"asset_b\": np.linspace(100, 110, 252),\n    },\n    index=pd.bdate_range(\"2020-01-01\", periods=252),\n)\n\nstrategy = bt.Strategy(\n    \"equal_weight\",\n    [\n        bt.algos.RunMonthly(),\n        bt.algos.SelectAll(),\n        bt.algos.WeighEqually(),\n        bt.algos.Rebalance(),\n    ],\n)\nresult = bt.run(bt.Backtest(strategy, prices))\nresult.display()\n",
      "asOf": "2026-11-20"
    },
    "F207": {
      "label": "Repository stars, bt",
      "display": "3.0K",
      "asOf": "2026-11-20"
    },
    "F208": {
      "label": "Multi-asset portfolios, bt",
      "display": "Yes",
      "asOf": "2026-11-20"
    },
    "F209": {
      "label": "Live broker adapters, bt",
      "display": "Undocumented",
      "asOf": "2026-11-20"
    },
    "F210": {
      "label": "Python requirement, bt",
      "display": ">=3.9",
      "asOf": "2026-11-20"
    },
    "F211": {
      "label": "Primary package role, bt",
      "display": "A flexible backtesting framework for Python",
      "asOf": "2026-11-20"
    },
    "F212": {
      "label": "Project function, bt",
      "display": "@_register('momentum_topn', 'momentum', 'Momentum Top-N',\n           'Select top N assets by momentum, equal weight',\n           [{'name': 'topN', 'label': 'Top N', 'default': 5, 'min': 1, 'max': 50},\n            {'name': 'lookback', 'label': 'Momentum Lookback', 'default': 60}])\ndef _build_momentum_topn(params):\n    \"\"\"Momentum top-N selection strategy.\"\"\"\n    top_n = int(params.get('topN', 5))\n    lookback = int(params.get('lookback', 60))\n\n    def build(data, name='momentum_topn'):\n        if _BT_AVAILABLE:\n            algos = [\n                # Wait until the lookback window has data (the first rebalance otherwise\n                # fails on an empty/NaN estimate). Must precede RunMonthly: placed after\n                # it, the counter only advanced on month starts (lookback MONTHS).\n                _bt.algos.RunAfterDays(int(lookback) + 2),\n                _bt.algos.RunMonthly(),\n                _bt.algos.SelectAll(),  # SelectMomentum ranks the current selection\n                _bt.algos.SelectMomentum(n=top_n, lookback=pd.DateOffset(days=lookback), lag=_LAG),\n                _bt.algos.WeighEqually(),\n                _bt.algos.Rebalance(),\n            ]\n            return _bt.Strategy(name, algos)\n        return None\n    return build",
      "asOf": "2026-11-20"
    },
    "F213": {
      "label": "Project source file, bt",
      "display": "fincept-qt/scripts/Analytics/backtesting/bt/bt_strategies.py",
      "asOf": "2026-11-20"
    },
    "F214": {
      "label": "Project full_name, bt",
      "display": "Fincept-Corporation/FinceptTerminal",
      "asOf": "2026-11-20"
    },
    "F215": {
      "label": "Project stargazers_count, bt",
      "display": "33.9K",
      "asOf": "2026-11-20"
    },
    "F216": {
      "label": "Library name, pyqlib",
      "display": "Qlib",
      "asOf": "2026-11-20"
    },
    "F217": {
      "label": "Monthly downloads, pyqlib",
      "display": "43.4K",
      "asOf": "2026-11-20"
    },
    "F218": {
      "label": "License, pyqlib",
      "display": "MIT",
      "asOf": "2026-11-20"
    },
    "F219": {
      "label": "Package release, pyqlib",
      "display": "0.9.7",
      "asOf": "2026-11-20"
    },
    "F220": {
      "label": "Package release date, pyqlib",
      "display": "Aug 2025",
      "asOf": "2026-11-20"
    },
    "F221": {
      "label": "Install, pyqlib",
      "display": "pip install pyqlib",
      "asOf": "2026-11-20"
    },
    "F222": {
      "label": "Quickstart, pyqlib",
      "display": "import qlib\nfrom qlib.data import D\nfrom qlib.constant import REG_CN\n\n# Initialization\nmount_path = \"~/.qlib/qlib_data/cn_data\"  # target_dir\nqlib.init(mount_path=mount_path, region=REG_CN)\n\n# Get stock data by Qlib\n# Load trading calendar with the given time range and frequency\nprint(D.calendar(start_time='2010-01-01', end_time='2017-12-31', freq='day')[:2])\n",
      "asOf": "2026-11-20"
    },
    "F223": {
      "label": "Official description, pyqlib",
      "display": "Provides a quantitative research platform.",
      "asOf": "2026-11-20"
    },
    "F224": {
      "label": "Quickstart source file, pyqlib",
      "display": "README.md",
      "asOf": "2026-11-20"
    },
    "F225": {
      "label": "Repository stars, pyqlib",
      "display": "50.4K",
      "asOf": "2026-11-20"
    },
    "F226": {
      "label": "Multi-asset portfolios, pyqlib",
      "display": "Yes",
      "asOf": "2026-11-20"
    },
    "F227": {
      "label": "Live broker adapters, pyqlib",
      "display": "Undocumented",
      "asOf": "2026-11-20"
    },
    "F228": {
      "label": "Python requirement, pyqlib",
      "display": ">=3.8.0",
      "asOf": "2026-11-20"
    },
    "F229": {
      "label": "Primary package role, pyqlib",
      "display": "A Quantitative-research Platform",
      "asOf": "2026-11-20"
    },
    "F230": {
      "label": "Research/model workflow, pyqlib",
      "display": "Data, model training, prediction, and portfolio analysis",
      "asOf": "2026-11-20"
    },
    "F231": {
      "label": "Library name, lumibot",
      "display": "LumiBot",
      "asOf": "2026-11-20"
    },
    "F232": {
      "label": "Monthly downloads, lumibot",
      "display": "22.1K",
      "asOf": "2026-11-20"
    },
    "F233": {
      "label": "License, lumibot",
      "display": "GPL-3.0",
      "asOf": "2026-11-20"
    },
    "F234": {
      "label": "Package release, lumibot",
      "display": "4.6.88",
      "asOf": "2026-11-20"
    },
    "F235": {
      "label": "Package release date, lumibot",
      "display": "Nov 2026",
      "asOf": "2026-11-20"
    },
    "F236": {
      "label": "Install, lumibot",
      "display": "pip install lumibot",
      "asOf": "2026-11-20"
    },
    "F237": {
      "label": "Quickstart, lumibot",
      "display": "from datetime import datetime\n\nfrom lumibot.backtesting import YahooDataBacktesting\nfrom lumibot.strategies import Strategy\n\nclass BuyAndHold(Strategy):\n    def initialize(self):\n        self.sleeptime = \"1D\"\n\n    def on_trading_iteration(self):\n        if self.first_iteration:\n            price = self.get_last_price(\"SPY\")\n            quantity = int(self.get_cash() // price)\n            order = self.create_order(\"SPY\", quantity, \"buy\")\n            self.submit_order(order)\n\nif __name__ == \"__main__\":\n    BuyAndHold.run_backtest(\n        YahooDataBacktesting,\n        datetime(2025, 1, 1),\n        datetime(2025, 2, 1),\n    )\n\n",
      "asOf": "2026-11-20"
    },
    "F238": {
      "label": "Official description, lumibot",
      "display": "Backtests and deploys trading strategies with the same code for stocks, options, crypto, futures, and forex.",
      "asOf": "2026-11-20"
    },
    "F239": {
      "label": "Quickstart source file, lumibot",
      "display": "strategy_api_overview.html",
      "asOf": "2026-11-20"
    },
    "F240": {
      "label": "Repository stars, lumibot",
      "display": "2.2K",
      "asOf": "2026-11-20"
    },
    "F241": {
      "label": "Multi-asset portfolios, lumibot",
      "display": "Yes",
      "asOf": "2026-11-20"
    },
    "F242": {
      "label": "Live broker adapters, lumibot",
      "display": "Yes",
      "asOf": "2026-11-20"
    },
    "F243": {
      "label": "Python requirement, lumibot",
      "display": ">=3.10",
      "asOf": "2026-11-20"
    },
    "F244": {
      "label": "Primary package role, lumibot",
      "display": "Python framework for algorithmic trading: backtesting and live deployment for stocks, options, crypto, futures, and forex. Same code for backtest and live trading.",
      "asOf": "2026-11-20"
    },
    "F245": {
      "label": "Library name, lean",
      "display": "LEAN CLI",
      "asOf": "2026-11-20"
    },
    "F246": {
      "label": "Monthly downloads, lean",
      "display": "21.4K",
      "asOf": "2026-11-20"
    },
    "F247": {
      "label": "License, lean",
      "display": "Apache-2.0",
      "asOf": "2026-11-20"
    },
    "F248": {
      "label": "Package release, lean",
      "display": "1.0.233",
      "asOf": "2026-11-20"
    },
    "F249": {
      "label": "Package release date, lean",
      "display": "Oct 2026",
      "asOf": "2026-11-20"
    },
    "F250": {
      "label": "Install, lean",
      "display": "pip install lean",
      "asOf": "2026-11-20"
    },
    "F251": {
      "label": "Quickstart, lean",
      "display": "lean init\nlean create-project \"Project Name\"\nlean backtest \"Project Name\"\n",
      "asOf": "2026-11-20"
    },
    "F252": {
      "label": "Official description, lean",
      "display": "Runs the QuantConnect LEAN engine locally and in the cloud.",
      "asOf": "2026-11-20"
    },
    "F253": {
      "label": "Quickstart source file, lean",
      "display": "README.md",
      "asOf": "2026-11-20"
    },
    "F254": {
      "label": "Repository stars, lean",
      "display": "336",
      "asOf": "2026-11-20"
    },
    "F255": {
      "label": "Multi-asset portfolios, lean",
      "display": "Via plugin",
      "asOf": "2026-11-20"
    },
    "F256": {
      "label": "Live broker adapters, lean",
      "display": "Via plugin",
      "asOf": "2026-11-20"
    },
    "F257": {
      "label": "Python requirement, lean",
      "display": ">=3.9",
      "asOf": "2026-11-20"
    },
    "F258": {
      "label": "Primary package role, lean",
      "display": "A CLI aimed at making it easier to run QuantConnect's LEAN engine locally and in the cloud",
      "asOf": "2026-11-20"
    },
    "F259": {
      "label": "Execution host, lean",
      "display": "External LEAN engine in Docker",
      "asOf": "2026-11-20"
    }
  },
  "dataCheckedAt": "2026-11-20",
  "agent": {
    "exaCall": {
      "endpoint": "/search",
      "body": {
        "query": "Best Python backtesting libraries backtrader Backtesting.py vectorbt bt code examples",
        "numResults": 5
      },
      "docsUrl": "https://exa.ai/docs/reference/search"
    },
    "calls": []
  }
}
