RQAlpha is Ricequant Technology developed open-source event-driven backtesting framework. Provides a complete solution for strategy development, backtesting, and simulated trading in the A-share and futures markets. Highly modular, supports extension through the plugin (Mod) system.
Documentation:https://rqalpha.readthedocs.io
Installation
pip install rqalpha
# 下载内置数据包(A股日线数据)
rqalpha download-bundle
# 验证安装
python -c "import rqalpha; print(rqalpha.__version__)"
Strategy Structure
from rqalpha.api import * # 导入所有 API 函数(含 logger)
def init(context):
"""策略启动时调用一次 — 设置订阅和参数"""
context.stock = '000001.XSHE'
context.fired = False
def handle_bar(context, bar_dict):
"""每根K线调用 — 主要交易逻辑"""
if not context.fired:
order_shares(context.stock, 1000)
context.fired = True
logger.info('买入完成') # logger 通过 from rqalpha.api import * 自动可用
def before_trading(context):
"""每个交易日开盘前调用"""
pass
def after_trading(context):
"""每个交易日收盘后调用"""
pass
Note:
from rqalpha.api import *will automatically importlogger, you can directly uselogger.info()、logger.warn()、logger.error()to output logs.
Run Backtest
Command Line
rqalpha run \
-f strategy.py \
-s 2024-01-01 \
-e 2024-06-30 \
--account stock 100000 \
--benchmark 000300.XSHG \
--plot
Python API
from rqalpha.api import *
from rqalpha import run_func
config = {
"base": {
"start_date": "2024-01-01",
"end_date": "2024-06-30",
"accounts": {"stock": 100000},
"benchmark": "000300.XSHG",
"frequency": "1d",
},
"extra": {
"log_level": "warning",
},
"mod": {
"sys_analyser": {"enabled": True, "plot": True},
},
}
result = run_func(init=init, handle_bar=handle_bar, config=config)
print(result)
Code Format
| Market | Suffix | Example |
|---|---|---|
| Shanghai A-shares | .XSHG |
600000.XSHG(Shanghai Pudong Development Bank) |
| Shenzhen A-shares | .XSHE |
000001.XSHE(Ping An Bank) |
| Index | .XSHG/.XSHE |
000300.XSHG(CSI 300) |
| Futures | .XSGE/.XDCE/.XZCE/.CCFX |
IF2401.CCFX(CSI 300 Futures) |
Order Functions
Stock Orders
# 按股数买卖
order_shares('000001.XSHE', 1000) # 买入1000股
order_shares('000001.XSHE', -500) # 卖出500股
# 按手买入(1手=100股)
order_lots('000001.XSHE', 10) # 买入10手(1000股)
# 按金额买入
order_value('000001.XSHE', 50000) # 买入5万元
# 按组合比例买入
order_percent('000001.XSHE', 0.5) # 买入组合值50%的仓位
# 目标仓位
order_target_value('000001.XSHE', 100000) # 调整到10万元
order_target_percent('000001.XSHE', 0.3) # 调整到组合的30%
# 撤单
cancel_order(order_id)
Futures Orders
# 开仓
buy_open('IF2401.CCFX', 1) # 买入开多1手
sell_open('IF2401.CCFX', 1) # 卖出开空1手
# 平仓
sell_close('IF2401.CCFX', 1) # 卖出平多1手
buy_close('IF2401.CCFX', 1) # 买入平空1手
Data Query Functions
def handle_bar(context, bar_dict):
# 当前K线数据
bar = bar_dict['000001.XSHE']
price = bar.close
volume = bar.volume
dt = bar.datetime
# 历史数据(返回DataFrame)
prices = history_bars('000001.XSHE', bar_count=20, frequency='1d',
fields=['close', 'volume', 'open', 'high', 'low'])
# 检查股票是否可交易
tradable = is_valid_price(bar.close)
# 检查是否停牌
suspended = is_suspended('000001.XSHE')
Portfolio and Positions
def handle_bar(context, bar_dict):
# 组合信息
cash = context.portfolio.cash # 可用资金
total = context.portfolio.total_value # 总资产
market_value = context.portfolio.market_value # 持仓市值
pnl = context.portfolio.pnl # 总盈亏
returns = context.portfolio.daily_returns # 日收益率
# 持仓信息
positions = context.portfolio.positions
for stock, pos in positions.items():
print(f'{stock}: quantity={pos.quantity}, '
f'sellable={pos.sellable}, '
f'avg_price={pos.avg_price:.2f}, '
f'market_value={pos.market_value:.2f}, '
f'pnl={pos.pnl:.2f}')
Scheduled Scheduling
from rqalpha.api import *
def init(context):
# 每个交易日指定时间运行函数
scheduler.run_daily(rebalance, time_rule=market_open(minute=5))
# 每周运行(每周一)
scheduler.run_weekly(weekly_task, tradingday=1, time_rule=market_open(minute=5))
# 每月运行(首个交易日)
scheduler.run_monthly(monthly_task, tradingday=1, time_rule=market_open(minute=5))
def rebalance(context, bar_dict):
pass
Mod System (Plugins)
RQAlpha's modular architecture allows functionality to be extended through Mods:
config = {
"mod": {
"sys_analyser": {
"enabled": True,
"plot": True,
"benchmark": "000300.XSHG",
},
"sys_simulation": {
"enabled": True,
"matching_type": "current_bar", # 撮合方式:current_bar(当前Bar)或 next_bar(下一Bar)
"slippage": 0.01, # 滑点(元)
},
"sys_transaction_cost": {
"enabled": True,
"commission_rate": 0.0003, # 手续费率
"tax_rate": 0.001, # 印花税(仅卖出)
"min_commission": 5, # 最低手续费
},
},
}
Available Built-in Mods
| Mod | Description |
|---|---|
sys_analyser |
Performance analysis and chart plotting |
sys_simulation |
Matching simulation |
sys_transaction_cost |
Commission and tax calculation |
sys_accounts |
Account management |
sys_benchmark |
Benchmark tracking |
sys_progress |
Progress bar display |
sys_risk |
Risk management checks |
Advanced Examples
For more complete strategy examples (dual moving average, multi-stock equal weight, RSI mean reversion, stop loss and take profit, futures CTA), see references/advanced-strategies.md。
Performance Analysis Output
After running the backtest, thesys_analyser Mod will output the following metrics:
| Metric | Description |
|---|---|
total_returns |
Total Return |
annualized_returns |
Annualized Return |
benchmark_total_returns |
Benchmark Total Return |
alpha |
Alpha |
beta |
Beta |
sharpe |
Sharpe Ratio |
sortino |
Sortino Ratio |
max_drawdown |
Maximum Drawdown |
tracking_error |
Tracking Error |
information_ratio |
Information Ratio |
volatility |
Volatility |
Common Error Handling
| Error | Cause | Solution |
|---|---|---|
Bundle not found |
Data bundle not downloaded | Run rqalpha download-bundle |
Insufficient cash |
Insufficient available funds | Check context.portfolio.cash |
Order Creation Failed: suspended |
Stock suspended | Use is_suspended() to check in advance |
No data for instrument |
Incorrect stock code | Check the code format (e.g. .XSHG / .XSHE) |
logger is not defined |
API not imported | Ensure from rqalpha.api import * is at the top of the file |
Usage Tips
- RQAlpha is a purely local framework with no cloud dependency, suitable for offline research.
- Use
rqalpha download-bundleto get free built-in A-share daily data. - The Mod system allows inserting custom data sources, broker interfaces, and risk control modules.
- Live trading can connect to vn.py's broker gateway via
rqalpha-mod-vnpy. - Supports daily and minute-level backtesting.
- Documentation:https://rqalpha.readthedocs.io/
Resource Index
- references/advanced-strategies.md — Complete strategy examples (dual moving average, multi-stock equal weight, RSI mean reversion, stop loss and take profit, futures CTA). Read when you need to reference advanced strategy implementations.
Rules
- Before using this Skill, confirm that the user explicitly needs the rqalpha framework for strategy backtesting. If the user only needs data acquisition, guide them to use data Skills such as baostock/pywencai.
- The top of the strategy file must include
from rqalpha.api import *, to ensure that all order functions andloggerare available. - Futures strategies must use
buy_open/sell_open/buy_close/sell_close, and cannot use stock functions such asorder_shares. - Before placing an order, use
is_suspended()to check the suspension status, to avoid order failure. - Stock codes must have a suffix (
.XSHG/.XSHE/.CCFX, etc.), and pure numeric codes cannot be used.