Skip to main content

Quantitative Toolkit - a helper in quant developing

Project description

Quool

Quantitative Toolkit — an extensible event-driven backtesting and live trading framework for quantitative strategies.

Quool provides a modular architecture built around three pillars: Source (market data), Broker (execution & accounting), and Strategy (logic). It supports both backtesting with historical data and paper/live trading with broker integrations.

Installation

pip install quool

Requires Python >= 3.10.

Quick Start

import pandas as pd
from quool import DataFrameSource, Broker, Strategy
from quool import FixedRateCommission, FixedRateSlippage

# 1. Market data source (MultiIndex DataFrame: time x code)
source = DataFrameSource(market_data)

# 2. Broker with commission and slippage models
broker = Broker(
    commission=FixedRateCommission(),
    slippage=FixedRateSlippage(),
)
broker.transfer(pd.Timestamp("2024-01-01"), 1_000_000)  # initial cash

# 3. Implement strategy
class MyStrategy(Strategy):
    def init(self):       # called once before backtest
        pass

    def update(self):     # called every timestamp
        # self.buy("000001", 100)   # buy 100 shares at market
        # self.order_target_percent("000001", 0.1)  # target 10% portfolio
        pass

# 4. Run backtest
strategy = MyStrategy(source, broker)
results = strategy.backtest()

Architecture

┌─────────────────────────────────────────────────────────┐
│                      Strategy                            │
│  init() → preupdate() → update() → stop()               │
└──────────────┬─────────────────────────┬────────────────┘
               │                         │
        ┌──────▼──────┐            ┌──────▼──────┐
        │   Source    │            │   Broker    │
        │ (market    │            │ (execution  │
        │   data)    │            │  & accounting)
        └────────────┘            └──────┬──────┘
                                          │
                                   ┌──────▼──────┐
                                   │   Order /   │
                                   │  Delivery   │
                                   └─────────────┘

Core Concepts

Source

Source is the abstract market data provider. Subclasses implement update() to advance time and return OHLCV snapshots.

Class Description
DataFrameSource Historical data from a pandas DataFrame (MultiIndex: time × code)
DuckPQSource DuckDB/Parquet queries
RealtimeSource Real-time EastMoney API with a rolling buffer
XtDataPreloadSource XtQuant historical data preloaded into a DataFrame

Broker

Broker manages order execution, portfolio accounting (cash & positions), and order matching for backtesting. For live trading, broker subclasses integrate with external systems.

Class Description
Broker Core simulated broker with pluggable commission/slippage models
AShareBroker Enforces A-share 100-share lot-size rules
XueQiuBroker XueQiu paper trading integration
XtBroker XtQuant live trading gateway

Order & Delivery

  • Order tracks the full lifecycle: CREATED → SUBMITTED → PARTIAL → FILLED/CANCELED/EXPIRED/REJECTED
  • Delivery records individual fills (execution details: price, quantity, commission)
  • Execution types: MARKET, LIMIT, STOP, STOPLIMIT, TARGET, TARGETLIMIT

Strategy

Base class for trading strategies. Provides:

  • Lifecycle hooks: init(), preupdate(), update(), stop()
  • Execution helpers: buy(), sell(), close(), order_target_value(), order_target_percent()
  • Backtesting: backtest() — blocking loop; run() / arun() — real-time scheduling
  • Persistence: dump(), load(), store(), restore()

Evaluator

Computes comprehensive performance metrics from broker deliveries:

  • Return: total_return, annual_return, annual_volatility
  • Risk-adjusted: sharpe_ratio, calmar_ratio, sortino_ratio
  • Drawdown: max_drawdown, max_drawdown_period
  • Risk: VaR_5%, CVaR_5%
  • Benchmark: beta, alpha, excess_return, information_ratio
  • Trading: position_duration, trade_win_rate, trade_return
  • Distribution: skewness, kurtosis, day_return_win_rate, monthly_win_rate

Friction Models

Class Description
FixedRateCommission Flat-rate commission with minimum fee and stamp duty
FixedRateSlippage Slippage model adjusting execution price based on volume

Storage

DuckDB-backed Parquet storage for efficient historical data management:

Class Description
DuckTable Single Parquet dataset with SQL querying
DuckPQ Multiple Parquet tables with shared DuckDB connection

Utilities

Function Description
setup_logger Configurable logging with file handlers
notify_task Email notification decorator
proxy_request HTTP requests with proxy failover
google_search Web search via SerpAPI
read_url Fetch web page content

API Reference

For detailed API documentation, see:

License

MIT

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

quool-7.0.16.tar.gz (67.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

quool-7.0.16-py3-none-any.whl (72.8 kB view details)

Uploaded Python 3

File details

Details for the file quool-7.0.16.tar.gz.

File metadata

  • Download URL: quool-7.0.16.tar.gz
  • Upload date:
  • Size: 67.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.2 {"installer":{"name":"uv","version":"0.11.2","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for quool-7.0.16.tar.gz
Algorithm Hash digest
SHA256 b4c945d8733cee7093ebcee55e208f5e591c8bf8d4095d39f20a3cec0e168ee2
MD5 2626124519b9077dc4eff5de0b77ec77
BLAKE2b-256 ec0937b8788f0d81ef9c5365364addb8da543c32d8b85c3d0045cdcd53d5b793

See more details on using hashes here.

File details

Details for the file quool-7.0.16-py3-none-any.whl.

File metadata

  • Download URL: quool-7.0.16-py3-none-any.whl
  • Upload date:
  • Size: 72.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.2 {"installer":{"name":"uv","version":"0.11.2","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for quool-7.0.16-py3-none-any.whl
Algorithm Hash digest
SHA256 aff33e6e7ea009b452d89152da36173bed3120125a40a66699af611a5bffdc3d
MD5 03e56c1ea68c5ca5dbc5b123e56f9c7b
BLAKE2b-256 2e7a8c2ed3c6bb9f636403a2c2e4b11ad954244155c0af849ed3e5e1887431ce

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page