
rqalpha
RQAlpha 米筐开源事件驱动回测框架。支持A股和期货,模块化架构,可自由扩展;当用户需要快速回测A股/期货策略、使用内置数据(download-bundle)、开发Mod插件,或提及 rqalpha、米筐时使用。与 backtrader 相比,rqalpha 内置A股日线数据、安装更简便,适合快速验证;backtrader 更灵活、社区更大。若用户仅需数据获取而无回测需求,引导使用 baostock/akshare/tushare 等数据 Skill。
- Installs
- 209
- Last 24h
- —
- Trending rank
- —
- Security
- Not audited
Install
Works with every agent the skills CLI supports.
npx skills add https://github.com/lzwme/finance-quant-skills --skill rqalpha- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads rqalpha automatically when relevant.
- 03
Review the result
The agent follows the SKILL.md steps, scripts and references bundled with the skill.
SKILL.md
The instructions your agent reads when the skill is triggered.
RQAlpha(米筐开源回测框架)
RQAlpha 是 米筐科技 开发的开源事件驱动回测框架。提供A股和期货市场的策略开发、回测和模拟交易完整解决方案。高度模块化,支持插件(Mod)系统扩展。
安装
pip install rqalpha
# 下载内置数据包(A股日线数据)
rqalpha download-bundle
# 验证安装
python -c "import rqalpha; print(rqalpha.__version__)"
策略结构
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
注意:
from rqalpha.api import *会自动导入logger,可直接使用logger.info()、logger.warn()、logger.error()输出日志。
运行回测
命令行
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)
代码格式
| 市场 | 后缀 | 示例 |
|---|---|---|
| 上海A股 | .XSHG | 600000.XSHG(浦发银行) |
| 深圳A股 | .XSHE | 000001.XSHE(平安银行) |
| 指数 | .XSHG/.XSHE | 000300.XSHG(沪深300) |
| 期货 | .XSGE/.XDCE/.XZCE/.CCFX | IF2401.CCFX(沪深300期货) |
下单函数
股票下单
# 按股数买卖
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)
期货下单
# 开仓
buy_open('IF2401.CCFX', 1) # 买入开多1手
sell_open('IF2401.CCFX', 1) # 卖出开空1手
# 平仓
sell_close('IF2401.CCFX', 1) # 卖出平多1手
buy_close('IF2401.CCFX', 1) # 买入平空1手
数据查询函数
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')
投资组合与持仓
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}')
定时调度
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系统(插件)
RQAlpha的模块化架构允许通过Mod扩展功能:
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, # 最低手续费
},
},
}
可用内置Mod
| Mod | 说明 |
|---|---|
sys_analyser | 绩效分析和图表绘制 |
sys_simulation | 撮合模拟 |
sys_transaction_cost | 手续费和税费计算 |
sys_accounts | 账户管理 |
sys_benchmark | 基准追踪 |
sys_progress | 进度条显示 |
sys_risk | 风险管理检查 |
进阶示例
更多完整策略示例(双均线、多股等权、RSI均值回归、止损止盈、期货CTA)见 references/advanced-strategies.md。
绩效分析输出
运行回测后,sys_analyser Mod会输出以下指标:
| 指标 | 说明 |
|---|---|
total_returns | 总收益率 |
annualized_returns | 年化收益率 |
benchmark_total_returns | 基准总收益率 |
alpha | Alpha值 |
beta | Beta值 |
sharpe | 夏普比率 |
sortino | Sortino比率 |
max_drawdown | 最大回撤 |
tracking_error | 跟踪误差 |
information_ratio | 信息比率 |
volatility | 波动率 |
常见错误处理
| 错误 | 原因 | 解决方法 |
|---|---|---|
Bundle not found | 未下载数据包 | 运行 rqalpha download-bundle |
Insufficient cash | 可用资金不足 | 检查 context.portfolio.cash |
Order Creation Failed: suspended | 股票停牌 | 用 is_suspended() 提前检查 |
No data for instrument | 股票代码错误 | 检查代码格式(如 .XSHG / .XSHE) |
logger 未定义 | 未导入 API | 确保 from rqalpha.api import * 在文件顶部 |
使用技巧
- RQAlpha 是纯本地框架,无云端依赖,适合离线研究。
- 使用
rqalpha download-bundle获取免费内置A股日线数据。 - Mod 系统允许插入自定义数据源、券商接口和风控模块。
- 实盘交易可通过
rqalpha-mod-vnpy连接 vn.py 的券商网关。 - 支持日线和分钟级回测。
- 文档:https://rqalpha.readthedocs.io/
资源索引
- references/advanced-strategies.md — 完整策略示例(双均线、多股等权、RSI均值回归、止损止盈、期货CTA)。需要参考进阶策略实现时读取。
规则
- 使用此 Skill 前,确认用户明确需要 rqalpha 框架进行策略回测。若用户仅需数据获取,引导使用 baostock/pywencai 等数据 Skill。
- 策略文件顶部必须包含
from rqalpha.api import *,以确保所有下单函数和logger可用。 - 期货策略必须使用
buy_open/sell_open/buy_close/sell_close,不能使用股票的order_shares等函数。 - 下单前应使用
is_suspended()检查停牌状态,避免订单失败。 - 股票代码必须带后缀(
.XSHG/.XSHE/.CCFX等),不能使用纯数字代码。
FAQ
What does the rqalpha skill do?
RQAlpha 米筐开源事件驱动回测框架。支持A股和期货,模块化架构,可自由扩展;当用户需要快速回测A股/期货策略、使用内置数据(download-bundle)、开发Mod插件,或提及 rqalpha、米筐时使用。与 backtrader 相比,rqalpha 内置A股日线数据、安装更简便,适合快速验证;backtrader 更灵活、社区更大。若用户仅需数据获取而无回测需求,引导使用 baostock/akshare/tushare 等数据 Skill。
How do I install rqalpha?
Run npx skills add https://github.com/lzwme/finance-quant-skills --skill rqalpha in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/rqalpha/ (personal) or .claude/skills/rqalpha/ (project).
Which AI agents can use rqalpha?
Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.
Is rqalpha safe to install?
No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.
Who maintains rqalpha?
It is published by lzwme in lzwme/finance-quant-skills. It has 209 recorded installs.
More from lzwme/finance-quant-skills
pywencai
lzwme/finance-quant-skills
同花顺问财数据查询:使用中文自然语言查询A股、指数、基金、港美股、可转债等市场数据;当用户需要通过自然语言从问财获取选股、财务、资金流、技术指标等数据时使用。
akshare
lzwme/finance-quant-skills
AKShare 开源金融数据接口库,提供股票、期货、期权、基金、外汇、债券、指数、加密货币等全品类金融数据;当用户需要获取各类金融市场数据时使用
baostock
lzwme/finance-quant-skills
BaoStock 免费开源 A 股数据平台,无需注册、无需 API Key,支持股票行情、K线、财务数据、行业分类、指数成分股查询。当用户提及 baostock、需要获取A股历史行情、财务报表、交易日历,或需要免费、免注册的A股数据时使用。与 tushare(数据更全但需注册)和 jqdatasdk(聚宽数据)不同,baostock 完全免费无限制,适合快速入门和低成本数据需求。
tdxquant
lzwme/finance-quant-skills
通达信量化数据获取技能。当用户提及 tdxquant、通达信、TdxQuant、tqcenter,并且需要获取A股数据(行情快照、K线、财务、板块、可转债、新股、交易数据等)、查询交易日历、执行通达信公式、订阅行情、交易下单时使用
backtrader
lzwme/finance-quant-skills
Backtrader 开源量化回测框架,支持多数据源、多策略、多周期回测与实盘交易,纯Python实现。当用户需要开发量化策略、进行回测分析、编写交易逻辑、回测参数优化,或提及 backtrader、量化回测框架时使用。若用户仅需数据获取而无回测需求,引导使用 baostock/akshare/tushare 等数据 Skill。
miniqmt
lzwme/finance-quant-skills
MiniQMT 迅投量化交易接口,基于 XtQuant Python 库(xtdata 行情 / xttrader 交易),供外部 Python 程序连接 MiniQMT 客户端,支持 A 股/期货/期权的行情获取(K线、分笔、财务数据等)和交易下单(报单、撤单、查询资产/委托/持仓)。当用户提及 miniqmt、xtquant、获取实时行情、量化交易下单、回测数据获取,或需要用外部 Python 程序连接 MiniQMT 客户端进行程序化交易时使用。若需在 QMT 客户端内编写/回测内置策略(ContextInfo/passorder),请用 qmt-strategy 技能。
Popular business & finance skills
website-builder
flowkit-labs/skills
Build and preview a hosted website for a business from a plain-language brief. Use for a new business homepage, landing page, service showcase, portfolio, online store, or customer portal, and for updates to sites hosted by this builder. Add bookings, checkout, or member accounts as needed and automate reminders, customer follow-ups, and reports after launch. Follow the user's choice when they specify another host or ask to edit an existing codebase.
sales-funnel-blueprint
autonnel/autonnel-skills
Turn an offer into a concrete multi-step sales funnel spec - page-by-page structure, price ladder, copy outline and the metrics each step must hit. Use when asked to build a sales funnel, marketing funnel, landing page flow, lead magnet funnel, webinar funnel, tripwire or VSL funnel, when planning a product launch page flow, or when someone asks "what pages do I need" for selling something online.
sales-enablement
coreyhaines31/marketingskills
When the user wants to create sales collateral, pitch decks, one-pagers, objection handling docs, or demo scripts. Also use when the user mentions 'sales deck,' 'pitch deck,' 'one-pager,' 'leave-behind,' 'objection handling,' 'deal-specific ROI analysis,' 'demo script,' 'talk track,' 'sales playbook,' 'proposal template,' 'buyer persona card,' 'battle card,' 'battlecard,' 'competitive one-pager,' 'win-loss analysis,' 'why are we losing deals,' 'loss reasons,' 'how do I respond to this objection,' 'prospect just said,' 'help my sales team,' 'sales materials,' or 'what should I give my sales reps,' 'cold call script,' or 'voicemail script.' Use this for any document or asset that helps a sales team close deals. For public competitor comparison pages, see competitors. For running buyer interviews or churn research, see customer-research. For marketing website copy, see copywriting. For cold outreach emails, see cold-email. For the offer being sold (bonuses, guarantees, pricing structure),
revops
coreyhaines31/marketingskills
When the user wants help with revenue operations, lead lifecycle management, or marketing-to-sales handoff processes. Also use when the user mentions 'RevOps,' 'revenue operations,' 'lead scoring,' 'outbound pipeline stages,' 'lead routing,' 'MQL,' 'SQL,' 'pipeline stages,' 'deal desk,' 'CRM automation,' 'marketing-to-sales handoff,' 'data hygiene,' 'leads aren't getting to sales,' 'pipeline management,' 'lead qualification,' or 'when should marketing hand off to sales.' Use this for anything involving the systems and processes that connect marketing to revenue. For cold outreach emails, see cold-email. For email drip campaigns, see emails. For pricing decisions, see pricing.
pricing
coreyhaines31/marketingskills
When the user wants help with pricing decisions, packaging, or monetization strategy. Also use when the user mentions 'pricing,' 'pricing tiers,' 'freemium,' 'free trial,' 'packaging,' 'price increase,' 'value metric,' 'Van Westendorp,' 'willingness to pay,' 'monetization,' 'how much should I charge,' 'my pricing is wrong,' 'pricing page,' 'annual vs monthly,' 'per seat pricing,' 'should I offer a free plan,' 'pricing page teardown,' 'pricing page audit,' 'is my pricing page AI-readable,' or 'can AI read my pricing.' Use this whenever someone is figuring out what to charge, how to structure their plans, or wants to audit a pricing page (for humans and for the AI agents that shortlist tools). For in-app upgrade screens, see paywalls. For offer construction (bonuses, guarantees, value framing, naming) on services/courses/coaching/high-ticket B2B, see offers.
offers
coreyhaines31/marketingskills
When the user wants to design, construct, or improve an offer — the thing they actually sell — including value framing, bonus stacking, guarantee design, scarcity/urgency, naming, and payment structure. Also use when the user mentions 'offer,' 'offer design,' 'build an offer,' 'grand slam offer,' 'irresistible offer,' 'value stack,' 'bonus stack,' 'guarantee,' 'risk reversal,' 'money-back guarantee,' 'scarcity,' 'urgency,' 'high-ticket offer,' 'productize a service,' 'naming an offer,' 'payment plan,' 'down-sell,' 'upsell offer,' or 'why isn't my offer converting.' Best for services, agencies, courses, coaching, info products, high-ticket B2B, and direct-response. If you run pure self-serve SaaS, read pricing first — tiers and packaging do more work there. For price level itself (tiers, freemium, value metric), see pricing. For the page that presents the offer, see copywriting. For the launch moment, see launch. For sales collateral, see sales-enablement.