quanttrader Documentation

repository·master·Indexed 20 days ago

https://github.com/letianzj/quanttrader

A pure Python-based, event-driven library for quantitative traders to perform backtesting and live trading. Version 0.6.0 supports various instrument types (Stocks, FX, Futures, Options, Comdty) and standard Interactive Brokers order types. It features a BacktestEngine for orchestrating event-driven tests and provides OpenAI Gym-compatible environments, such as PortfolioEnv and TradingEnv, for reinforcement learning backtesting with constrained portfolio actions.

Tokens
5.5K
Snippets
17
Records
27
Agent score
73%

What's inside quanttrader

  1. Overview of quanttrader capabilities

    master

    quanttrader is an event-driven framework designed for quantitative traders. Its core features include:

    • Backtesting and Live Trading: Strategies developed in the backtesting environment can typically be transitioned to live trading by switching the brokerage component.
    • Monitoring: A control window is provided to monitor individual strategy live trading sessions and the overall portfolio performance.
    • Target Use Case: It is designed for traders who do not require ultra-low latency (nano-second) execution. Typical response times (e.g., receiving data and sending orders) are in the millisecond range, making it suitable for strategies like pairs-trading rather than high-frequency market-making.
  2. How the backtest order filling mechanism works

    master

    The quanttrader backtest framework uses a distinctive design for market orders: it fills market orders immediately rather than waiting for the next day's opening price. In a daily bar setting, this simulates sending an order at 15:59:59 to avoid overnight slippage.

    If you require market orders to be filled at the next available price (similar to limit or stop orders), you must modify the BacktestBrokerage class to save the market order and execute it on the next tick.

  3. Set up Live Trading with Interactive Brokers

    master

    To perform live trading with quanttrader, you must use Interactive Brokers (IB), as it is currently the only supported broker. The setup involves a main entry point script, a live session configuration file, instrument metadata, and a preparation step to ensure data and strategy parameters are ready for the session.

    Key components required for a live trading session:

    • live_engine.py: The main entry point for executing the live trading engine.
    • config_live.yaml: The configuration file defining the parameters for your live session.
    • instrument_meta.yaml: A file containing metadata for the specific instruments you intend to trade.
    • prepare_trading_session.yaml: A script/process used to prepare necessary data and strategy parameters before starting the live session.
  4. Supported data feeds for backtesting

    master

    The backtest framework currently accepts three types of data feeds:

    1. Yahoo Finance: Daily or intraday bars. You can follow external guides for downloading this historical data.
    2. Interactive Brokers: Historical intraday bars. You can use the provided script examples/download_historical_data_from_ib.py to download this data.
    3. Live Tick Data: Recorded from actual live trading sessions.

    You can implement your own custom data source by following the patterns established by these existing examples.

    # To download historical intraday data from Interactive Brokers, use the following script:
    # (Referenced from the repository)
    # examples/download_historical_data_from_ib.py
  5. Run a Live Trading demo

    master

    To run a live trading demo, follow these steps:

    1. Prerequisite: Download and install IB TWS or IB Gateway and enable the API connection.
    2. Download Example Files: Download the following files from the repository (using the 'Raw' button and saving with correct extensions):
      • live_engine.py
      • config_live.yaml
      • order_per_interval_strategy.py
    3. Execute: Navigate to the directory containing the files and run the engine.

    Note: Ensure you have configured your Interactive Brokers API settings correctly before running.

    cd where_the_files_are_saved
    python live_engine.py
  6. How the TradingEnv step function works

    master

    The step(action) method executes a single time step in the backtest. It follows this logic:

    1. Rebalance: Calculates the new position size based on the current NAV and the weight corresponding to the chosen action index.
      • The weight is calculated as pct / (n - 1) where n is the number of discrete actions.
    2. Execution: Calculates the delta_size (change in shares) and applies the _commission_rate to the transaction cost.
    3. Transition: Advances the internal _current_step to the next timestamp.
    4. Reward Calculation: The reward is the change in value resulting from the price movement of the new position, minus the commission: (new_price - current_price) * new_size - current_commission.
    5. State Update: Updates the internal _df_positions tracking cash, position size, and NAV.

    Returns:

    • new_state: The next observation (lookback window + NAV).
    • reward: The PnL for the step.
    • done: Boolean indicating if the episode ended (reached maxsteps or end of data).
    • info: A dictionary containing detailed transaction metadata (e.g., old_price, new_nav, transaction_size, commission).
  7. Initialize and run an event-driven backtest with BacktestEngine

    master

    The BacktestEngine is the central orchestrator for running event-driven backtests. To use it, you must initialize it with a start and end date, configure your capital, provide instrument metadata, load your market data via add_data, and set your trading strategy using a class that inherits from StrategyBase.

    Once configured, calling .run() executes the event loop. The engine returns three components: the equity curve, a DataFrame of positions, and a DataFrame of trades.

    from datetime import datetime
    import pandas as pd
    from quanttrader.backtest_engine import BacktestEngine
    from your_module import MyStrategy
    
    # 1. Initialize engine
    engine = BacktestEngine(start_date=datetime(2023, 1, 1), end_date=datetime(2023, 12, 31))
    
    # 2. Configure environment
    engine.set_capital(100000.0)
    engine.set_instrument_meta({"AAPL": {"tick_size": 0.01}})
    
    # 3. Load data
    data = pd.read_csv("aapl_data.csv", index_col='datetime', parse_dates=True)
    engine.add_data("AAPL", data)
    
    # 4. Set strategy
    engine.set_strategy(MyStrategy())
    
    # 5. Run and retrieve results
    equity, positions, trades = engine.run()
  8. Use InteractiveBrokers for live trading

    master

    The InteractiveBrokers class provides the interface for executing trades through the Interactive Brokers platform. It is part of the quanttrader.brokerage.ib_brokerage module.

    from quanttrader.brokerage.ib_brokerage import InteractiveBrokers
    
    # Initialize the IB brokerage
    brokerage = InteractiveBrokers(...)
  9. Use BacktestBrokerage for simulated trading

    master

    The BacktestBrokerage class allows you to simulate trading environments for backtesting strategies without connecting to a real broker. It is part of the quanttrader.brokerage.backtest_brokerage module.

    from quanttrader.brokerage.backtest_brokerage import BacktestBrokerage
    
    # Initialize the backtest brokerage
    brokerage = BacktestBrokerage(...)
  10. Supported Instruments and Order Types

    master

    The package supports various instrument types and standard Interactive Brokers order types.

    Supported Instruments Examples

    • Stock: AMZN STK SMART
    • Foreign Exchange: EURGBP CASH IDEALPRO
    • Futures: ESM9 FUT GLOBEX
    • Options on Stock: AAPL OPT 20201016 128.75 C SMART
    • Options on Futures: ES FOP 20200911 3450 C 50 GLOBEX
    • Comdty: XAUUSD CMDTY SMART

    Supported Order Types

    • Auction
    • Auction Limit
    • Market
    • Market If Touched
    • Market On Close
    • Market On Open
    • Market to Limit
    • Limit Order
    • Limit if Touched
    • Limit on Close
    • Limit on Open
    • Stop
    • Stop Limit
    • Trailing Stop
    • Trailing Stop Limit