Now liveThe Skillselion MCP - thousands of ranked skills, loaded into your agent mid-task. No install.Get it →
lzwme avatar

Rqalpha

  • 116 installs
  • 169 repo stars
  • Updated June 29, 2026
  • lzwme/finance-quant-skills

rqalpha is an agent skill that provides RQAlpha Python templates for scheduled backtest strategies including dual moving-average entries and multi-stock rebalancing.

About

rqalpha is a Finance & Trading agent skill that packages advanced RQAlpha strategy examples for solo and indie quant builders working in Python. The bundled templates show how to wire init context, daily and monthly schedulers, and order_target_percent so agents generate backtest-ready code instead of guessing RQAlpha APIs. One pattern implements a fast/slow moving-average crossover on a single ticker such as 600000.XSHG, entering at ninety percent weight when the fast average crosses above the slow line and flattening on the reverse. The second pattern maintains an equal-weight basket across several A-share symbols, exiting names that leave the universe and rebalancing on the first trading day each month. Use it during Validate when you are prototyping systematic rules, tuning lookback windows, or standardizing how your coding agent writes handle_bar-safe logic. It does not replace data licensing, risk limits, or live execution plumbing, but it shortens the loop from idea to a runnable RQAlpha module you can iterate in backtests.

  • Dual moving-average crossover with scheduler.run_daily at market_open plus order_target_percent sizing
  • Monthly equal-weight rebalance across a fixed multi-stock universe with suspension checks
  • Position-aware entries and exits using history_bars closes and portfolio quantity checks
  • Two strategy patterns: single-stock MA cross and multi-name monthly rebalance templates

Rqalpha by the numbers

  • 116 all-time installs (skills.sh)
  • +5 installs in the week ending Aug 2, 2026 (Skillselion tracking)
  • Ranked #511 of 1,106 Finance & Trading skills by installs in the Skillselion catalog
  • Security screen: MEDIUM risk (skills.sh audit)
  • Data as of Aug 2, 2026 (Skillselion catalog sync)
npx skills add https://github.com/lzwme/finance-quant-skills --skill rqalpha

Add your badge

Show developers this skill is listed on Skillselion. Paste this into your README.

Listed on Skillselion
Installs116
repo stars169
Security audit2 / 3 scanners passed
Last updatedJune 29, 2026
Repositorylzwme/finance-quant-skills

What it does

Install this when you need copy-paste RQAlpha Python patterns to backtest A-share strategies before risking real capital.

Who is it for?

Best when you're prototyping China A-share rules in RQAlpha and want scheduler-driven MA or rebalance starters your agent can extend.

Skip if: Skip if you do not use RQAlpha, need only live brokerage automation with no backtest, or want generic pandas signals without the RQAlpha API.

When should I use this skill?

When implementing or extending RQAlpha backtest strategies that need scheduled trade logic, history_bars signals, or order_target_percent rebalancing.

What you get

You get runnable init and scheduled trade_logic modules with position checks and target weights ready to run inside RQAlpha backtests.

  • RQAlpha strategy module with init context and scheduler hooks
  • Scheduled trade_logic or rebalance functions using order_target_percent
  • Backtest-ready examples for single-name MA cross and multi-stock rebalance

By the numbers

  • 2 documented strategy patterns: dual MA crossover and monthly equal-weight rebalance
  • Examples use scheduler.run_daily and scheduler.run_monthly with market_open timing rules

Files

SKILL.mdMarkdownGitHub ↗

RQAlpha(米筐开源回测框架)

RQAlpha米筐科技 开发的开源事件驱动回测框架。提供A股和期货市场的策略开发、回测和模拟交易完整解决方案。高度模块化,支持插件(Mod)系统扩展。

文档:https://rqalpha.readthedocs.io

安装

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股.XSHG600000.XSHG(浦发银行)
深圳A股.XSHE000001.XSHE(平安银行)
指数.XSHG/.XSHE000300.XSHG(沪深300)
期货.XSGE/.XDCE/.XZCE/.CCFXIF2401.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基准总收益率
alphaAlpha值
betaBeta值
sharpe夏普比率
sortinoSortino比率
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 等),不能使用纯数字代码。

Related skills

How it compares

Use as RQAlpha-specific strategy templates instead of ad-hoc chat snippets that omit scheduler and order_target_percent semantics.

FAQ

Who is rqalpha for?

rqalpha is for developers and small teams who backtest systematic strategies in RQAlpha on Python, especially A-share tickers, and want agent-assisted strategy scaffolding.

When should I use rqalpha?

Use rqalpha during Validate when you are prototyping backtests: wiring dual moving-average daily entries, monthly equal-weight rebalance, or teaching your agent the correct RQAlpha init and scheduler patterns before you commit to live trading or a full build.

Is rqalpha safe to install?

Treat it like any third-party agent skill: review the Security Audits panel on this Prism catalog page and inspect the skill package in your repo before running backtests or granting shell and filesystem access.

This week in AI coding

Five minutes, every Monday - the tools, releases and tactics for developers.

unsubscribe anytime.