Skip to main content

Quant Module

quant 模块提供量化分析工具,包括技术指标计算、因子分析、OHLCV 行情数据和策略回测。 公式语法基于 Mai-language,兼容通达信/同花顺。

快速开始

from reportify_sdk import Reportify

client = Reportify(api_key="your-api-key")

# 计算 RSI 指标
df = client.quant.indicators_compute(["000001"], "RSI(14)")

# 因子选股
stocks = client.quant.factors_screen(formula="RSI(14) < 30")

# 获取 OHLCV 数据
ohlcv = client.quant.ohlcv("000001")

# 策略回测
result = client.quant.backtest(
    symbol="000001",
    entry_formula="CROSS(MA(CLOSE, 5), MA(CLOSE, 20))",
    start_date="2023-01-01",
    end_date="2024-01-01"
)

指标 (Indicators)

indicators()

获取可用技术指标列表。
indicators = client.quant.indicators()

for ind in indicators:
    print(f"{ind['name']}: {ind['description']}")
    print(f"  输出字段: {ind['fields']}")
返回字段:
  • name: 指标名称(如 MACD, RSI, KDJ)
  • description: 指标描述
  • fields: 输出字段(如 MACD 返回 [“dif”, “dea”, “macd”])

indicators_compute()

计算技术指标值。
df = client.quant.indicators_compute(
    symbols=["000001", "600519"],
    formula="RSI(14)",
    market="cn",           # 可选,默认 "cn"
    start_date="2024-01-01",  # 可选
    end_date="2024-06-01"     # 可选
)
参数:
参数类型必填说明
symbolslist[str]股票代码列表
formulastr指标公式
marketstr市场(cn/hk/us),默认 cn
start_datestr开始日期,默认 3 个月前
end_datestr结束日期,默认今天
公式示例:
# RSI 指标
df = client.quant.indicators_compute(["000001"], "RSI(14)")
print(df[["symbol", "date", "rsi"]])

# MACD 指标(默认参数)
df = client.quant.indicators_compute(["000001"], "MACD()")
print(df[["symbol", "date", "dif", "dea", "macd"]])

# MACD 指标(自定义参数)
df = client.quant.indicators_compute(["000001"], "MACD(12, 26, 9)")

# KDJ 指标
df = client.quant.indicators_compute(["000001"], "KDJ(9, 3, 3)")
print(df[["symbol", "date", "k", "d", "j"]])

# 布林带
df = client.quant.indicators_compute(["000001"], "BOLL(20, 2)")
print(df[["symbol", "date", "upper", "mid", "lower"]])

因子 (Factors)

factors()

获取可用因子列表(变量和函数)。
factors = client.quant.factors()

for f in factors:
    print(f"{f['name']} ({f['type']}, level {f['level']}): {f['description']}")
因子分级:
  • Level 0 变量: CLOSE, OPEN, HIGH, LOW, VOLUME 及别名
  • Level 0 函数: MA, EMA, REF, HHV, LLV, STD 等核心函数
  • Level 1 函数: CROSS, COUNT, EVERY 等应用函数
  • Level 2 函数: MACD, KDJ, RSI, BOLL 等技术指标

factors_compute()

计算因子值,使用 Mai-language 语法。
df = client.quant.factors_compute(
    symbols=["000001"],
    formula="RSI(14)",
    market="cn",
    start_date="2024-01-01",
    end_date="2024-06-01"
)
公式示例:
# 简单指标
df = client.quant.factors_compute(["000001"], "RSI(14)")

# 获取 MACD 的 DIF 线
df = client.quant.factors_compute(["000001"], "MACD().dif")

# 收盘价是否高于 20 日均线(布尔值)
df = client.quant.factors_compute(["000001"], "CLOSE > MA(CLOSE, 20)")

# MA20 偏离度(百分比)
df = client.quant.factors_compute(["000001"], "(CLOSE - MA(CLOSE, 20)) / MA(CLOSE, 20) * 100")

# 复合条件
df = client.quant.factors_compute(["000001"], "(CLOSE > MA(CLOSE, 20)) & (MA(CLOSE, 20) > MA(CLOSE, 60))")
支持的运算符:
类型运算符说明
比较>, <, >=, <=, ==, !=比较运算
逻辑与&AND大小写不敏感
逻辑或|OR大小写不敏感
逻辑非~NOT大小写不敏感
算术+, -, *, /四则运算
支持的变量:
变量别名说明
CLOSEC收盘价
OPENO开盘价
HIGHH最高价
LOWL最低价
VOLUMEV, VOL成交量

factors_screen()

因子选股,筛选满足条件的股票。
stocks = client.quant.factors_screen(
    formula="RSI(14) < 30",
    market="cn",            # 可选
    check_date="2024-06-01",  # 可选,默认最新交易日
    symbols=None              # 可选,None 表示全市场
)
参数:
参数类型必填说明
formulastr选股公式
marketstr市场,默认 cn
check_datestr检查日期,默认最新交易日
symbolslist[str]股票池,None 表示全市场
选股示例:
# RSI 超卖
stocks = client.quant.factors_screen(formula="RSI(14) < 30")

# 金叉
stocks = client.quant.factors_screen(formula="CROSS(MA(CLOSE, 5), MA(CLOSE, 10))")

# 上升趋势
stocks = client.quant.factors_screen(formula="(CLOSE > MA(CLOSE, 20)) & (MA(CLOSE, 20) > MA(CLOSE, 60))")

# 突破布林带上轨
stocks = client.quant.factors_screen(formula="CLOSE > BOLL(20, 2).upper")

# 在指定股票池中筛选
stocks = client.quant.factors_screen(
    formula="RSI(14) < 30",
    symbols=["000001", "600519", "000002"]
)

行情 (Quotes)

ohlcv()

获取单个股票的 OHLCV 日线数据。
df = client.quant.ohlcv(
    symbol="000001",
    market="cn",
    start_date="2024-01-01",
    end_date="2024-06-01"
)

print(df[["date", "open", "high", "low", "close", "volume"]])
参数:
参数类型必填说明
symbolstr股票代码
marketstr市场,默认 cn
start_datestr开始日期,默认 1 个月前
end_datestr结束日期,默认今天

ohlcv_batch()

批量获取多个股票的 OHLCV 数据。
df = client.quant.ohlcv_batch(
    symbols=["000001", "600519", "000002"],
    market="cn",
    start_date="2024-01-01",
    end_date="2024-06-01"
)

print(df[["symbol", "date", "close", "volume"]])
数据按日期(降序)、股票代码排序。

kline_1m()

获取单个股票的 1 分钟 K 线数据。
df = client.quant.kline_1m(
    symbol="000001",
    start_datetime="2024-01-01 09:30:00",
    end_datetime="2024-01-01 15:00:00",
    market="cn"
)

print(df[["datetime", "open", "high", "low", "close", "volume"]])
参数:
参数类型必填说明
symbolstr股票代码
start_datetimestr开始时间(YYYY-MM-DD HH:MM:SS)
end_datetimestr结束时间(YYYY-MM-DD HH:MM:SS)
marketstr市场,默认 cn

kline_1m_batch()

批量获取多个股票的 1 分钟 K 线数据。
df = client.quant.kline_1m_batch(
    symbols=["000001", "600519", "000002"],
    start_datetime="2024-01-01 09:30:00",
    end_datetime="2024-01-01 15:00:00",
    market="cn"
)

print(df[["symbol", "datetime", "close", "volume"]])
数据按日期(升序)、股票代码排序。

minute()

获取单个股票的分钟数据。
df = client.quant.minute(
    symbol="000001",
    start_datetime="2024-01-01 09:30:00",
    end_datetime="2024-01-01 15:00:00",
    market="cn"
)

print(df[["datetime", "open", "high", "low", "close", "volume"]])
参数:
参数类型必填说明
symbolstr股票代码
start_datetimestr开始时间(YYYY-MM-DD HH:MM:SS)
end_datetimestr结束时间(YYYY-MM-DD HH:MM:SS)
marketstr市场,默认 cn

minute_batch()

批量获取多个股票的分钟数据。
df = client.quant.minute_batch(
    symbols=["000001", "600519", "000002"],
    start_datetime="2024-01-01 09:30:00",
    end_datetime="2024-01-01 15:00:00",
    market="cn"
)

print(df[["symbol", "datetime", "close", "volume"]])
数据按日期(升序)、股票代码排序。

回测 (Backtest)

backtest()

执行策略回测。
result = client.quant.backtest(
    start_date="2023-01-01",
    end_date="2024-01-01",
    symbol="000001",
    market="cn",
    entry_formula="CROSS(MA(CLOSE, 5), MA(CLOSE, 20))",  # 买入信号:MA5 上穿 MA20
    exit_formula="CROSSDOWN(MA(CLOSE, 5), MA(CLOSE, 20))",  # 卖出信号(可选)
    initial_cash=100000,  # 初始资金
    commission=0.0003,    # 佣金费率
    stop_loss=0.05,       # 止损 5%
    sizer_percent=99,     # 仓位 99%
    auto_close=True,      # 自动平仓
    labels={"rsi": "RSI(14)", "ma20": "MA(CLOSE, 20)"}  # 额外指标(可选)
)
参数:
参数类型必填默认值说明
start_datestr-回测开始日期(YYYY-MM-DD)
end_datestr-回测结束日期(YYYY-MM-DD)
symbolstr-股票代码
marketstrcn市场(cn/hk/us)
entry_formulastr-买入/开仓公式(结果 > 0 触发买入)
exit_formulastrNone卖出/平仓公式(结果 > 0 触发卖出)
initial_cashfloat100000初始资金
commissionfloat0佣金费率
stop_lossfloat0止损比例(0 表示不设置)
sizer_percentint99仓位百分比
auto_closeboolTrue是否自动平仓
labelsdict[str, str]None标签字典,返回额外指标值
`
返回结果:
{
    "success": True,
    "initial_cash": 100000,
    "final_cash": 115000,
    "total_return": 15000,
    "total_return_pct": 0.15,
    "max_drawdown": 0.08,
    "profit_factor": 1.5,
    "win_rate": 0.6,
    "total_trades": 10,
    "trades": [...]
}
使用示例:
# 1. 简单金叉策略(只有买入信号)
result = client.quant.backtest(
    start_date="2023-01-01",
    end_date="2024-01-01",
    symbol="000001",
    entry_formula="CROSS(MA(CLOSE, 5), MA(CLOSE, 20))"
)

print(f"总收益: {result['total_return']:.2f}")
print(f"收益率: {result['total_return_pct']:.2%}")
print(f"最大回撤: {result['max_drawdown']:.2%}")
print(f"胜率: {result['win_rate']:.2%}")
print(f"盈亏比: {result['profit_factor']:.2f}")
print(f"交易次数: {result['total_trades']}")

# 2. 买入和卖出信号都指定
result = client.quant.backtest(
    start_date="2023-01-01",
    end_date="2024-01-01",
    symbol="000001",
    entry_formula="CROSS(MA(CLOSE, 5), MA(CLOSE, 20))",      # 金叉买入
    exit_formula="CROSSDOWN(MA(CLOSE, 5), MA(CLOSE, 20))"    # 死叉卖出
)

# 3. RSI 超卖超买策略
result = client.quant.backtest(
    start_date="2023-01-01",
    end_date="2024-01-01",
    symbol="000001",
    entry_formula="RSI(14) < 30",   # RSI 低于 30 买入
    exit_formula="RSI(14) > 70"     # RSI 高于 70 卖出
)

# 4. 使用 labels 记录额外指标
result = client.quant.backtest(
    start_date="2023-01-01",
    end_date="2024-01-01",
    symbol="000001",
    entry_formula="CROSS(RSI(14), 30)",
    labels={
        "rsi": "RSI(14)",
        "ma20": "MA(CLOSE, 20)",
        "ma60": "MA(CLOSE, 60)"
    }
)
# 每日数据中会包含 rsi、ma20、ma60 的值

完整示例

技术分析工作流

from reportify_sdk import Reportify

client = Reportify(api_key="your-api-key")

# 1. 获取股票数据
df = client.quant.ohlcv("000001", start_date="2024-01-01")

# 2. 计算多个指标
rsi = client.quant.indicators_compute(["000001"], "RSI(14)")
macd = client.quant.indicators_compute(["000001"], "MACD()")
boll = client.quant.indicators_compute(["000001"], "BOLL(20, 2)")

# 3. 合并数据
import pandas as pd
data = df.merge(rsi[["date", "rsi"]], on="date")
data = data.merge(macd[["date", "dif", "dea", "macd"]], on="date")
data = data.merge(boll[["date", "upper", "mid", "lower"]], on="date")

print(data.tail())

选股并回测

# 1. 选股:RSI 超卖
oversold_stocks = client.quant.factors_screen(formula="RSI(14) < 30")
print(f"发现 {len(oversold_stocks)} 只超卖股票")

# 2. 对每只股票进行回测
for stock in oversold_stocks[:5]:  # 取前 5 只
    result = client.quant.backtest(
        start_date="2023-01-01",
        end_date="2024-01-01",
        symbol=stock["symbol"],
        entry_formula="CROSS(RSI(14), 30)"  # RSI 上穿 30 买入
    )
    print(f"{stock['symbol']}: 收益率 {result['total_return_pct']:.2%}")