### Install and Setup Bullet-Trade for Backtesting Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/backtest.md Installs the necessary environment and copies the example configuration file. Ensure you activate the virtual environment before proceeding. ```bash python -m venv .venv # macos/linux source .venv/bin/activate # windows (cmd) .venv\Scripts\activate.bat pip install -e ".[dev]" # macos/linux cp env.backtest.example .env # windows (cmd) copy env.backtest.example .env ``` -------------------------------- ### Copy example .env file (Windows cmd) Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/python-setup.md On Windows command prompt, copy an example environment file named 'env.example' to '.env' to start configuring your settings. ```bash copy env.example .env ``` -------------------------------- ### Copy example .env file (macOS/Linux) Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/python-setup.md On macOS or Linux, copy an example environment file named 'env.example' to '.env' to start configuring your settings. ```bash cp env.example .env ``` -------------------------------- ### Install BulletTrade Source: https://context7.com/bullettrade/bullet-trade/llms.txt Instructions for installing BulletTrade, including setting up a virtual environment and installing the package in regular or development mode. ```bash python -m venv .venv source .venv/bin/activate pip install bullet-trade pip install -e ".[dev]" cp env.example .env bullet-trade --version ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/bullettrade/bullet-trade/blob/main/tests/unit/test_dividend_data_consistency.md Install the project's development dependencies and specific libraries required for each data provider. ```bash pip install -e ".[dev]" pip install jqdatasdk # 如果测试 jqdata pip install xtquant # 如果测试 miniqmt pip install tushare # 如果测试 tushare ``` -------------------------------- ### Remote QMT Server Setup Source: https://context7.com/bullettrade/bullet-trade/llms.txt Instructions for setting up a remote Bullet Trade server on a Windows machine with QMT installed. Supports single or multiple accounts. ```bash # ── 远程 server 端启动(Windows + QMT 机器)── # .env 配置: # QMT_DATA_PATH=C:\国金QMT交易端\userdata_mini # QMT_ACCOUNT_ID=123456 # QMT_SERVER_TOKEN=secret bullet-trade --env-file .env server \ --listen 0.0.0.0 --port 58620 \ --enable-data --enable-broker # 多账户(股票+期货) bullet-trade server --listen 0.0.0.0 --port 58620 \ --accounts main=123456 hedge=654321:future \ --enable-data --enable-broker ``` -------------------------------- ### Install BulletTrade Package Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/quickstart.md Install the BulletTrade library using pip after activating your virtual environment. ```bash pip install bullet-trade ``` -------------------------------- ### Parameter Optimization Output Example Source: https://context7.com/bullettrade/bullet-trade/llms.txt Example of the console output during parameter optimization, showing top-performing parameter sets sorted by risk-return ratio. ```text # 优化输出示例(按收益回撤比降序,控制台显示 Top 10): 参数优化Top建议(按收益回撤比降序): lookback hold_days top_n threshold 收益回撤比 策略年化收益 最大回撤 夏普比率 25 5 2 0.02 2.35 28.5% -12.1% 1.82 20 5 3 0.01 2.18 25.2% -11.6% 1.65 30 7 2 0.03 2.05 22.8% -11.1% 1.58 ``` -------------------------------- ### Install xtquant Separately Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/python-setup.md If needed, the 'xtquant' library can be installed independently. However, using the 'bullet-trade[qmt]' installation is generally recommended for simplicity. ```bash pip install xtquant ``` -------------------------------- ### Parameter Configuration Example Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/optimize.md Configure the parameter grid for optimization in a JSON file. Parameter names must match the global variable names in the strategy file. ```json { "param_grid": { "lookback": [10, 15, 20, 25, 30], "hold_days": [3, 5, 7, 10], "top_n": [1, 2, 3, 5] } } ``` -------------------------------- ### Check Python and Pip Installation Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/python-setup.md Verify that Python and pip are installed and accessible from the command line. This is a prerequisite before creating a virtual environment. ```bash python --version ``` ```bash pip --version ``` -------------------------------- ### Install BulletTrade with QMT Extension Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/python-setup.md Install BulletTrade with the 'qmt' extension, which includes dependencies for direct QMT connection or running the BulletTrade server. ```bash pip install "bullet-trade[qmt]" ``` -------------------------------- ### Strategy File Example Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/optimize.md Define your trading strategy logic in a Python file. Ensure global variables used for optimization are initialized with default values. ```python from jqdata import * def initialize(context): set_benchmark('000300.XSHG') set_option('use_real_price', True) # 这些参数将被优化器覆盖 g.lookback = 20 # 回看天数 g.hold_days = 5 # 持有天数 g.top_n = 3 # 选股数量 run_daily(trade, '10:00') def trade(context): # 策略逻辑... pass ``` -------------------------------- ### Local QMT Live Trading Setup Source: https://context7.com/bullettrade/bullet-trade/llms.txt Configuration and command to run live trading using the local QMT broker. Requires setting environment variables for data path and account ID. ```bash # ── 本地 QMT 实盘 ── # .env 配置(同一台 Windows 机器): # DEFAULT_DATA_PROVIDER=qmt # DEFAULT_BROKER=qmt # QMT_DATA_PATH=C:\国金QMT交易端\userdata_mini # QMT_ACCOUNT_ID=123456 bullet-trade live strategies/demo_strategy.py --broker qmt ``` -------------------------------- ### Run Local QMT Strategy Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/config.md Command to run a live strategy with the QMT broker in a local setup. ```bash bullet-trade live strategies/demo_strategy.py --broker qmt ``` -------------------------------- ### Run a Minimal Backtest Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/quickstart.md Execute a backtest for a demo strategy with specified start and end dates. Ensure your strategy file is correctly located. ```bash bullet-trade backtest strategies/demo_strategy.py --start 2024-01-01 --end 2024-06-01 ``` -------------------------------- ### Example Strategy Test Output Source: https://github.com/bullettrade/bullet-trade/blob/main/tests/strategies/README.md This is an example of the detailed output generated after testing a strategy, including performance metrics and a pass/fail status. ```text ============================================================ 测试策略: strategy.joinquant.EPO 文件路径: /path/to/tests/strategies/strategy.joinquant.EPO.py ============================================================ 策略配置: 回测期间: 2024-01-01 ~ 2024-12-31 初始资金: 1,000,000 运行频率: daily 基准指数: 000300.XSHG 回测结果: 总收益率: 15.30% 年化收益率: 15.30% 基准收益率: 8.50% 阿尔法: 0.0680 贝塔: 0.7500 夏普比率: 1.45 最大回撤: -18.20% 胜率: 62.00% ============================================================ 策略 strategy.joinquant.EPO 测试通过 ✓ ============================================================ ``` -------------------------------- ### Successful Test Run Output Example Source: https://github.com/bullettrade/bullet-trade/blob/main/tests/unit/README_dividend_test.md Example output demonstrating a successful execution of all dividend data consistency tests. ```text bullet-trade/tests/unit/test_dividend_data_consistency.py::test_golden_dividends_format PASSED [ 16%] bullet-trade/tests/unit/test_dividend_data_consistency.py::test_provider_dividends_match_golden[jqdata] PASSED [ 33%] bullet-trade/tests/unit/test_dividend_data_consistency.py::test_provider_dividends_match_golden[miniqmt] PASSED [ 50%] bullet-trade/tests/unit/test_dividend_data_consistency.py::test_provider_dividends_match_golden[tushare] PASSED [ 66%] bullet-trade/tests/unit/test_dividend_data_consistency.py::test_cross_provider_consistency PASSED [ 83%] bullet-trade/tests/unit/test_dividend_data_consistency.py::test_dividend_cash_calculation PASSED [100%] ============================== 6 passed in 12.34s ============================== ``` -------------------------------- ### Verify BulletTrade Installation Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/python-setup.md Check if BulletTrade is installed correctly by running its help and version commands. Successful output indicates the environment is ready. ```bash bullet-trade --help ``` ```bash bullet-trade --version ``` -------------------------------- ### Start BulletTrade Research Environment Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/research.md Launches the BulletTrade research environment, which typically opens in a web browser. Use the --diagnose flag for troubleshooting. ```bash bullet-trade lab ``` ```bash bullet-trade lab --diagnose ``` -------------------------------- ### Remote qmt-remote Client Setup Source: https://context7.com/bullettrade/bullet-trade/llms.txt Configuration and command to connect a client (macOS/Linux compatible) to a remote QMT server using qmt-remote. Requires server details and token. ```bash # ── 远程 qmt-remote 客户端(macOS/Linux 可用)── # .env 配置: # DEFAULT_DATA_PROVIDER=qmt-remote # DEFAULT_BROKER=qmt-remote # QMT_SERVER_HOST=10.0.0.8 # QMT_SERVER_PORT=58620 # QMT_SERVER_TOKEN=secret # QMT_SERVER_ACCOUNT_KEY=main # 多账户时才需要 bullet-trade live strategies/demo_strategy.py --broker qmt-remote ``` -------------------------------- ### Client-Side Multi-Account Configuration Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/config.md For multi-account setups, clients need to specify the active account key in their environment. ```env QMT_SERVER_ACCOUNT_KEY=main ``` -------------------------------- ### Switch Data Provider Example Source: https://context7.com/bullettrade/bullet-trade/llms.txt Python code demonstrating how to query the current data provider and switch between JQData and MiniQMT using the Bullet Trade API. ```python from bullet_trade.data.api import get_price, set_data_provider, get_data_provider # 查询当前数据源 provider = get_data_provider() print(f"当前数据源: {provider.name}") # 切换到 JQData(需配置 JQDATA_USERNAME / JQDATA_PASSWORD) set_data_provider('jqdata') df_jq = get_price('601318.XSHG', '2025-01-01', '2025-06-30', fq=None) # 切换到 MiniQMT(本地,需配置 QMT_DATA_PATH) set_data_provider('qmt') ``` -------------------------------- ### Create .env file Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/python-setup.md Example configuration for a .env file, used to store environment variables like account IDs and tokens. This file should be placed in the directory where BulletTrade commands are executed. ```env QMT_ACCOUNT_ID=123456 QMT_SERVER_TOKEN=secret ``` -------------------------------- ### Demo Strategy Implementation Source: https://context7.com/bullettrade/bullet-trade/llms.txt A sample strategy demonstrating basic initialization, setting benchmarks, options, and daily execution of trading logic. ```python from jqdata import * def initialize(context): set_benchmark('000300.XSHG') set_option('use_real_price', True) g.target = ['000001.XSHE', '600000.XSHG'] run_daily(market_open, time='10:00') def market_open(context): for stock in g.target: df = get_price(stock, count=5, fields=['close']) if df['close'].iloc[-1] > df['close'].mean(): order_target_value(stock, 50000) else: order_target_value(stock, 0) ``` -------------------------------- ### Get Split and Dividend Events Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/api.md Retrieve a list of stock split and dividend events for a given security. For non-backtesting scenarios, explicit start and end dates must be provided. The output structure is standardized. ```python get_split_dividend(security='000001.XSHE', start_date='2023-01-01', end_date='2023-12-31') ``` -------------------------------- ### 创建最简单的策略文件 Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/beginner-route-a.md 创建一个名为 `my_first_strategy.py` 的 Python 文件,包含 `initialize` 和 `market_open` 函数,用于执行买入操作。 ```python from bullet_trade.core.api import * def initialize(context): set_benchmark('000300.XSHG') g.stock = '510300.XSHG' g.has_bought = False run_daily(market_open, time='open') def market_open(context): if not g.has_bought: order_value(g.stock, context.portfolio.available_cash) g.has_bought = True log.info(f"买入 {g.stock},金额={context.portfolio.available_cash:.2f}") ``` -------------------------------- ### Initialize and Run Daily Strategy - Python Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/beginner-guide.md This Python code snippet demonstrates initializing a strategy with a benchmark and scheduling a daily market open event. It's typical for strategies that primarily use price data, scheduling, and basic order functions, suitable for independent execution. ```python from bullet_trade.core.api import * def initialize(context): set_benchmark('000300.XSHG') run_daily(market_open, time='open') def market_open(context): stocks = get_index_stocks('000300.XSHG') df = get_price(stocks[:10], end_date=context.previous_date, count=20, fields=['close'], panel=False) current = get_current_data()['000001.XSHG'] if current.paused: return order_target_value('510300.XSHG', 100000) ``` -------------------------------- ### Upgrade Pip Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/python-setup.md Upgrade the pip package installer within the activated virtual environment. It's recommended to do this before installing other packages. ```bash python -m pip install --upgrade pip ``` -------------------------------- ### Run Backtest and Live Trading Commands Source: https://github.com/bullettrade/bullet-trade/blob/main/bullet_trade/notebook/01.welcome.ipynb Use these commands to initiate backtesting or live trading simulations for your strategies. Specify the strategy file path and date range for backtests, or the broker for live trading. ```bash bullet-trade backtest strategies/demo_strategy.py --start 2025-01-01 --end 2025-06-01 ``` ```bash bullet-trade live strategies/demo_strategy.py --broker qmt ``` -------------------------------- ### Strategy Entry and Global Objects Source: https://context7.com/bullettrade/bullet-trade/llms.txt Demonstrates how to import JoinQuant compatible APIs, use the global state container 'g', the logging object 'log', and the message sending function 'send_msg'. Includes setting benchmarks and options for real-time pricing. ```python from jqdata import * def initialize(context): # g:全局状态容器,可挂载任意可序列化属性 g.target_ratio = 0.2 g.stocks = ['000001.XSHE', '600000.XSHG'] g.live_trade = True # 标记实盘模式 # log:支持 debug/info/warn/error/critical log.set_level('strategy', 'info') set_benchmark('000300.XSHG') set_option('use_real_price', True) run_daily(trade, time='10:00') def trade(context): # send_msg:输出策略日志,配置 MESSAGE_KEY 后可推送企业微信 send_msg(f"[交易] 当前净值: {context.portfolio.total_value:.2f}") for stock in g.stocks: df = get_price(stock, count=5, fields=['close']) last = df['close'].iloc[-1] mean = df['close'].mean() if last > mean: order_target_value(stock, context.portfolio.total_value * g.target_ratio) log.info(f"买入 {stock}, 最新价={last:.2f}, 5日均价={mean:.2f}") else: order_target_value(stock, 0) # set_message_handler:注册自定义消息处理函数 def my_handler(msg): print(f"[自定义推送] {msg}") set_message_handler(my_handler) # 清除 handler:set_message_handler(None) ``` -------------------------------- ### Add New Strategy Steps (Bash & YAML) Source: https://github.com/bullettrade/bullet-trade/blob/main/tests/strategies/README.md Steps to integrate a new strategy: copy the file, configure parameters in `config.yaml`, and run the test. ```bash # 1. 复制策略文件 cp ~/my_strategy.py tests/strategies/strategy.my_awesome.py # 2. 编辑 config.yaml 添加配置 ```yaml strategy.my_awesome: start_date: '2023-01-01' end_date: '2023-12-31' capital_base: 100000 ``` # 3. 运行测试 pytest tests/test_strategies.py -v -s -k "my_awesome" ``` -------------------------------- ### Check Python installation paths (Windows) Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/python-setup.md If multiple Python installations exist, use 'where' to identify which 'python' and 'pip' executables are being used. This helps in resolving path issues. ```bash where python ``` ```bash where pip ``` -------------------------------- ### Failed Test Run Output Example (Data Inconsistency) Source: https://github.com/bullettrade/bullet-trade/blob/main/tests/unit/README_dividend_test.md Example output for a failed test case, indicating data inconsistency between a provider and the golden standard. The error message specifies the provider, security, dividend event, and the discrepancy in values. ```text FAILED bullet-trade/tests/unit/test_dividend_data_consistency.py::test_provider_dividends_match_golden[miniqmt] AssertionError: miniqmt 601318.XSHG 第1个分红事件 (2024-07-26) bonus_pre_tax 不匹配: 期望 15.0, 实际 1.5 ``` -------------------------------- ### Required Strategy Initialization Function (Python) Source: https://github.com/bullettrade/bullet-trade/blob/main/tests/strategies/README.md Defines the mandatory `initialize` function for strategy setup, which is called once before backtesting begins. ```python def initialize(context): """策略初始化函数,回测开始前调用一次""" pass ``` -------------------------------- ### Run Remote Server Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/config.md Command to start the Bullet Trade server, listening on all interfaces and enabling data and broker services. ```bash bullet-trade --env-file .env server --listen 0.0.0.0 --port 58620 --enable-data --enable-broker ``` -------------------------------- ### Workflow: Migrate Strategy from JoinQuant (Bash & YAML) Source: https://github.com/bullettrade/bullet-trade/blob/main/tests/strategies/README.md Steps to migrate a strategy from JoinQuant: copy the strategy file, configure parameters in `config.yaml`, and run the test. ```bash # 1. 复制策略文件(不修改代码) cp ~/Downloads/my_joinquant_strategy.py tests/strategies/ # 2. 编辑 config.yaml 添加回测参数 vim tests/strategies/config.yaml # 3. 运行测试 pytest tests/test_strategies.py -v -s -k "my_joinquant" ``` -------------------------------- ### Sample Backtesting Strategy Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/backtest.md A basic Python strategy demonstrating initialization, setting a benchmark, enabling real price trading, and scheduling a daily market open function to execute trades based on price trends. ```python from jqdata import * def initialize(context): set_benchmark('000300.XSHG') set_option('use_real_price', True) g.target = ['000001.XSHE', '600000.XSHG'] run_daily(market_open, time='10:00') def market_open(context): for stock in g.target: df = get_price(stock, count=5, fields=['close']) if df['close'][-1] > df['close'].mean(): order_target_value(stock, 10000) ``` -------------------------------- ### 运行最小实盘部署 Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/beginner-route-a.md 使用 `bullet-trade live` 命令运行 `my_first_strategy.py` 策略,并指定券商为 `qmt`。 ```bash bullet-trade live my_first_strategy.py --broker qmt ``` -------------------------------- ### Get All Securities Information Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/api.md Fetch information about all available securities of a specified type (e.g., 'stock'). In a backtesting context, this defaults to the current backtest date. ```python get_all_securities(types='stock', date='2023-01-01') ``` -------------------------------- ### Get Last Price of a Symbol Source: https://github.com/bullettrade/bullet-trade/blob/main/bullet_trade/notebook/04.joinquant_remote_live_trade.ipynb Fetches the last traded price for a specified security symbol. Ensure the data client is initialized before calling this function. ```python bt.get_data_client().get_last_price('600635.XSHG') ``` -------------------------------- ### 配置最小 .env 文件 Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/beginner-route-a.md 在运行回测前,需要配置 `.env` 文件,指定默认数据提供商、QMT 数据路径和账户 ID。 ```env DEFAULT_DATA_PROVIDER=qmt QMT_DATA_PATH=C:\QMT\userdata_mini QMT_ACCOUNT_ID=123456 ``` -------------------------------- ### Get Current Data Provider Name Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/data/DATA_PROVIDER_GUIDE.md Retrieve the name of the currently active data provider using `get_data_provider()`. Useful for debugging or conditional logic. ```python from bullet_trade.data.api import get_data_provider provider = get_data_provider() print(f"Current data provider: {provider.name}") ``` -------------------------------- ### Configure Data Provider for Backtesting Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/backtest.md Set the default data provider and provide credentials if required. The `DEFAULT_DATA_PROVIDER` is mandatory. ```bash # 数据源类型 (jqdata, tushare, qmt) DEFAULT_DATA_PROVIDER=jqdata # 必填,行情源 JQDATA_USERNAME=your_username # 选填,按数据源需要 JQDATA_PASSWORD=your_password ``` -------------------------------- ### Minute-Line Backtesting Configuration Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/backtest.md Command to run a backtest using minute-frequency data. Ensure your data source supports minute data and that `use_real_price=True` is set in your strategy. ```bash bullet-trade backtest strategy.py --start 2024-01-01 --end 2024-01-31 --frequency minute ``` -------------------------------- ### Optional Strategy Functions (Python) Source: https://github.com/bullettrade/bullet-trade/blob/main/tests/strategies/README.md Includes optional functions for handling trading logic, pre-trading setup, and post-trading cleanup at different stages of the trading day. ```python def handle_data(context, data): """每个交易bar调用(按frequency配置)""" pass def before_trading_start(context): """每日交易开始前调用""" pass def after_trading_end(context): """每日交易结束后调用""" pass def process_initialize(context): """实盘/模拟盘初始化""" pass ``` -------------------------------- ### 配置最小 .env 文件用于实盘 Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/beginner-route-a.md 在运行实盘前,配置 `.env` 文件,指定默认数据提供商、默认券商、QMT 数据路径和账户 ID。 ```env DEFAULT_DATA_PROVIDER=qmt DEFAULT_BROKER=qmt QMT_DATA_PATH=C:\QMT\userdata_mini QMT_ACCOUNT_ID=123456 ``` -------------------------------- ### Python: Get Current Tick Snapshot Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/tick.md Fetches a single tick snapshot for a given security code. This method does not depend on the subscription status and can be used for debugging. ```python get_current_tick('000001.XSHE') ``` -------------------------------- ### Get Index Constituent Stocks Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/api.md Retrieve a list of stock codes that constitute a given index on a specific date. Defaults to the current backtest date if running in a backtesting environment. ```python get_index_stocks(index_symbol='000300.XSHG', date='2023-01-01') ``` -------------------------------- ### 多账户配置 Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/trade-support.md 当使用多个账户时,需要在 bt.configure 函数中指定 account_key。这允许策略区分和管理不同的交易账户。 ```python bt.configure( host="your.server.ip", port=58620, token="secret", account_key="main", ) ``` -------------------------------- ### Get Trading Days Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/api.md Retrieve a list of valid trading days within a specified date range. In backtesting environments, the `end_date` is automatically truncated to the current backtest time. ```python get_trade_days(start_date='2023-01-01', end_date='2023-12-31') ``` -------------------------------- ### Run Remote QMT-Remote Client Strategy Source: https://github.com/bullettrade/bullet-trade/blob/main/docs/config.md Command to run a live strategy using the qmt-remote broker, connecting to a remote server. ```bash bullet-trade live strategies/demo_strategy.py --broker qmt-remote ```