RQAlpha 米筐开源事件驱动回测框架 - 支持A股和期货,模块化架构,可自由扩展。
RQAlpha 是 米筐科技 开发的开源事件驱动回测框架。提供A股和期货市场的策略开发、回测和模拟交易完整解决方案。高度模块化,支持插件(Mod)系统扩展。
Docs: https://rqalpha.readthedocs.io/
bash
pip install rqalpha
python
def init(context):
策略启动时调用一次 — 设置订阅和参数
context.stock = 000001.XSHE
context.fired = False
def handlebar(context, bardict):
每根K线调用 — 主要交易逻辑
if not context.fired:
order_shares(context.stock, 1000)
context.fired = True
def before_trading(context):
每个交易日开盘前调用
pass
def after_trading(context):
每个交易日收盘后调用
pass
bash
rqalpha run \
-f strategy.py \
-s 2024-01-01 \
-e 2024-06-30 \
--account stock 100000 \
--benchmark 000300.XSHG \
--plot
python
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 = runfunc(init=init, handlebar=handle_bar, config=config)
print(result)
| 市场 | 后缀 | 示例 |
|---|---|---|
| 上海A股 | .XSHG | 600000.XSHG(浦发银行) |
| 深圳A股 |
python
python
def handlebar(context, bardict):
# 当前K线数据
bar = bar_dict[000001.XSHE]
price = bar.close
volume = bar.volume
dt = bar.datetime
# 历史数据(返回DataFrame)
prices = historybars(000001.XSHE, barcount=20, frequency=1d,
fields=[close, volume, open, high, low])
# 检查股票是否可交易
tradable = isvalidprice(bar.close)
# 检查是否停牌
suspended = is_suspended(000001.XSHE)
python
def handlebar(context, bardict):
# 组合信息
cash = context.portfolio.cash # 可用资金
total = context.portfolio.total_value # 总资产
marketvalue = context.portfolio.marketvalue # 持仓市值
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},
fsellable={pos.sellable},
favgprice={pos.avgprice:.2f},
fmarketvalue={pos.marketvalue:.2f},
fpnl={pos.pnl:.2f})
python
from rqalpha.api import *
def init(context):
# 每个交易日指定时间运行函数
scheduler.rundaily(rebalance, timerule=market_open(minute=5))
# 每周运行(每周一)
scheduler.runweekly(weeklytask, tradingday=1, timerule=marketopen(minute=5))
# 每月运行(首个交易日)
scheduler.runmonthly(monthlytask, tradingday=1, timerule=marketopen(minute=5))
def rebalance(context, bar_dict):
pass
RQAlpha的模块化架构允许通过Mod扩展功能:
python
config = {
mod: {
sys_analyser: {
enabled: True,
plot: True,
benchmark: 000300.XSHG,
},
sys_simulation: {
enabled: True,
matchingtype: currentbar, # 撮合方式:currentbar或nextbar
slippage: 0.01, # 滑点(元)
},
systransactioncost: {
enabled: True,
commission_rate: 0.0003, # 手续费率
tax_rate: 0.001, # 印花税(仅卖出)
min_commission: 5, # 最低手续费
},
},
}
| Mod | 说明 |
|---|---|
| sysanalyser | 绩效分析和图表绘制 |
| syssimulation |
python
import numpy as np
from rqalpha.api import *
def init(context):
context.stock = 600000.XSHG
context.fast = 5
context.slow = 20
scheduler.rundaily(tradelogic, timerule=marketopen(minute=5))
def tradelogic(context, bardict):
prices = history_bars(context.stock, context.slow + 1, 1d, fields=[close])
if len(prices) < context.slow:
return
closes = prices[close]
fast_ma = np.mean(closes[-context.fast:])
slow_ma = np.mean(closes[-context.slow:])
pos = context.portfolio.positions.get(context.stock)
has_position = pos is not None and pos.quantity > 0
if fastma > slowma and not has_position:
ordertargetpercent(context.stock, 0.9)
logger.info(fBUY: fastma={fastma:.2f} > slowma={slowma:.2f})
elif fastma < slowma and has_position:
ordertargetpercent(context.stock, 0)
logger.info(fSELL: fastma={fastma:.2f} < slowma={slowma:.2f})
def handlebar(context, bardict):
pass
python
from rqalpha.api import *
def init(context):
context.stocks = [600000.XSHG, 000001.XSHE, 601318.XSHG,
600036.XSHG, 000858.XSHE]
scheduler.runmonthly(rebalance, tradingday=1, timerule=market_open(minute=30))
def rebalance(context
该技能支持在以下平台通过对话安装:
帮我安装 SkillHub 和 rqalpha-1776114134 技能
设置 SkillHub 为我的优先技能安装源,然后帮我安装 rqalpha-1776114134 技能
skillhub install rqalpha-1776114134
文件大小: 10.23 KB | 发布时间: 2026-4-15 14:13