joinquant-docs
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinese聚宽策略开发
JoinQuant Strategy Development
基于本目录离线文档,为聚宽官网(回测 / 模拟 / 研究)编写 Python 策略。回答 API 问题时必须先查阅本地文档,不得凭记忆编造函数签名或参数。
与 jqdatasdk 的区别:在官网策略环境使用;jqdata是本地 Python 库,API 略有不同,且不能在官网回测/模拟/研究中使用。jqdatasdk
Based on the offline documents in this directory, write Python strategies for the JoinQuant official website (backtesting / paper trading / research). When answering API questions, you must consult the local documents first and must not fabricate function signatures or parameters from memory.
Difference from jqdatasdk:is used in the official website strategy environment;jqdatais a local Python library with slightly different APIs, and cannot be used in the official website's backtesting/paper trading/research modules.jqdatasdk
文档查阅流程
Document Consultation Process
- 确定问题类型,按 reference.md 定位文件
- 用 Grep/Read 搜索目标函数名或中文关键词(如 、
get_price、order_target)市盈率 - 交叉验证:API 行为查 ,字段/表结构查
api.md,踩坑查data/*.mdfaq.md - 给出答案时引用文档中的调用方法、参数、返回值与示例代码
需要写策略框架? → api.md「开始写策略」「策略程序架构」
需要查数据 API? → api.md「数据获取函数」+ data/ 对应品种文档
需要下单/持仓? → api.md「交易函数」「对象」
需要财务/估值数据? → data/Stock.md(run_query + valuation/fundamentals 表)
需要行业/概念选股? → data/plateData.md + api.md get_industry_stocks 等
需要技术指标? → data/technicalanalysis.md(from jqlib.technical_analysis import *)
需要 Alpha 因子? → data/Alpha101.md、data/Alpha191.md
需要自定义因子? → fator.md(jqfactor.Factor、calc_factors)
需要因子看板数据? → data/factor_values.md- Determine the question type, locate the file according to reference.md
- Search with Grep/Read for the target function name or Chinese keywords (e.g., ,
get_price, "price-earnings ratio")order_target - Cross-validation: Check API behavior in , field/table structure in
api.md, and troubleshooting indata/*.mdfaq.md - When providing answers, cite the calling method, parameters, return values and sample code from the documents
Need to write a strategy framework? → api.md "Start Writing Strategies" "Strategy Program Architecture"
Need to check data APIs? → api.md "Data Retrieval Functions" + corresponding product documents in data/
Need to place orders/check positions? → api.md "Trading Functions" "Objects"
Need financial/valuation data? → data/Stock.md (run_query + valuation/fundamentals tables)
Need industry/concept stock selection? → data/plateData.md + api.md get_industry_stocks etc.
Need technical indicators? → data/technicalanalysis.md (from jqlib.technical_analysis import *)
Need Alpha factors? → data/Alpha101.md, data/Alpha191.md
Need custom factors? → fator.md (jqfactor.Factor, calc_factors)
Need factor dashboard data? → data/factor_values.md策略骨架
Strategy Skeleton
最小可运行结构:
python
undefinedMinimum runnable structure:
python
undefined导入聚宽函数库
Import JoinQuant function library
import jqdata
def initialize(context):
g.security = '000001.XSHE'
set_benchmark('000300.XSHG')
set_option('use_real_price', True) # 开启动态复权(真实价格),建议开启
run_daily(trade, time='open') # 或 time='every_bar' / '9:30'
def trade(context):
security = g.security
close_data = attribute_history(security, 5, '1d', ['close'])
MA5 = close_data['close'].mean()
current_price = close_data['close'][-1]
cash = context.portfolio.available_cash
if current_price > 1.01 * MA5:
order_value(security, cash)
elif current_price < MA5 and context.portfolio.positions[security].closeable_amount > 0:
order_target(security, 0)undefinedimport jqdata
def initialize(context):
g.security = '000001.XSHE'
set_benchmark('000300.XSHG')
set_option('use_real_price', True) # Enable dynamic forward adjustment (real price), recommended to enable
run_daily(trade, time='open') # Or time='every_bar' / '9:30'
def trade(context):
security = g.security
close_data = attribute_history(security, 5, '1d', ['close'])
MA5 = close_data['close'].mean()
current_price = close_data['close'][-1]
cash = context.portfolio.available_cash
if current_price > 1.01 * MA5:
order_value(security, cash)
elif current_price < MA5 and context.portfolio.positions[security].closeable_amount > 0:
order_target(security, 0)undefined生命周期函数
Lifecycle Functions
| 函数 | 说明 |
|---|---|
| 全局初始化,仅运行一次;用 |
| 定时任务; |
| 按回测频率驱动;不建议与 run_daily 混用 |
| 开盘前(9:00) |
| 收盘后(15:30) |
带 ♠ 标识的 API 仅支持回测/模拟,不能在研究模块调用。 模块在研究与回测环境均可使用。
jqdata| Function | Description |
|---|---|
| Global initialization, runs only once; use |
| Scheduled tasks; |
| Driven by backtesting frequency; not recommended to use with run_daily |
| Before market opens (9:00) |
| After market closes (15:30) |
APIs marked with ♠ are only supported in backtesting/paper trading and cannot be called in the research module. The module can be used in both research and backtesting environments.
jqdata证券代码规范
Security Code Specifications
| 市场 | 后缀 | 示例 |
|---|---|---|
| 上海证券交易所 | | |
| 深圳证券交易所 | | |
| 中金所 | | |
| 大商所 | | |
| 上期所 | | |
| 郑商所 | | |
| 场外基金 | | |
期货策略需将 的 设为对应主力合约(如 ),以匹配夜盘开盘时间。
run_dailyreference_securityIF9999.CCFX| Market | Suffix | Example |
|---|---|---|
| Shanghai Stock Exchange | | |
| Shenzhen Stock Exchange | | |
| CFFEX | | |
| DCE | | |
| SHFE | | |
| CZCE | | |
| OTC Fund | | |
For futures strategies, set the parameter of to the corresponding main contract (e.g., ) to match the night trading opening time.
reference_securityrun_dailyIF9999.CCFX常用 API 速查
Common API Quick Reference
行情与历史
Market Quotes and History
python
get_price(security, start_date, end_date, frequency='daily', fields=None, fq='pre')
attribute_history(security, count, unit, fields) # 回测环境,不含当天
history(count, unit, field, security_list, df=True)
get_bars(security, count, unit, fields, include_now=True)python
get_price(security, start_date, end_date, frequency='daily', fields=None, fq='pre')
attribute_history(security, count, unit, fields) # Backtesting environment, does not include the current day
history(count, unit, field, security_list, df=True)
get_bars(security, count, unit, fields, include_now=True)标的池与板块
Security Pool and Sectors
python
get_all_securities(types=['stock'], date=None) # date 防未来函数
get_index_stocks('000300.XSHG', date=None)
get_industry_stocks('C15', date=None)
get_concept_stocks('GN036', date=None)
set_universe([...]) # 设置后 history 可不传 security_listpython
get_all_securities(types=['stock'], date=None) # date prevents look-ahead bias
get_index_stocks('000300.XSHG', date=None)
get_industry_stocks('C15', date=None)
get_concept_stocks('GN036', date=None)
set_universe([...]) # After setting, security_list does not need to be passed to history财务数据(SQL 查询)
Financial Data (SQL Query)
python
from jqdata import *
q = query(valuation).filter(valuation.code == '000001.XSHE')
df = get_fundamentals(q, date='2015-10-15')python
from jqdata import *
q = query(valuation).filter(valuation.code == '000001.XSHE')
df = get_fundamentals(q, date='2015-10-15')或 run_query(单次最多 4000 行,不可连表)
Or run_query (maximum 4000 rows per query, join tables not allowed)
df = finance.run_query(query(finance.STK_XXX).filter(...).limit(4000))
undefineddf = finance.run_query(query(finance.STK_XXX).filter(...).limit(4000))
undefined交易
Trading
python
order(security, amount) # 按股数,正买负卖
order_value(security, value) # 按金额
order_target(security, amount) # 调到目标股数
order_target_value(security, value) # 调到目标市值
order_target_percent(security, percent) # 调到目标仓位比例A 股买入数量须为 100 整数倍(科创板 200 起);卖光持仓时不受限。每日最多 10000 笔订单。
python
order(security, amount) # By share count, positive for buy, negative for sell
order_value(security, value) # By amount
order_target(security, amount) # Adjust to target share count
order_target_value(security, value) # Adjust to target market value
order_target_percent(security, percent) # Adjust to target position ratioA-share buy quantity must be multiples of 100 (200 for STAR Market); no restriction when selling all holdings. Maximum 10000 orders per day.
技术指标
Technical Indicators
python
from jqlib.technical_analysis import *python
from jqlib.technical_analysis import *check_date 策略中建议用 context.current_dt,避免盘中取当日收盘指标产生未来数据
In strategies, it is recommended to use context.current_dt for check_date to avoid look-ahead bias caused by retrieving the day's closing indicator during trading hours
result = MACD(security_list, check_date=context.current_dt, SHORT=12, LONG=26, MID=9)
undefinedresult = MACD(security_list, check_date=context.current_dt, SHORT=12, LONG=26, MID=9)
undefined自定义因子
Custom Factors
python
from jqfactor import Factor, calc_factors
class MyFactor(Factor):
name = 'my_factor'
max_window = 5
dependencies = ['close']
def calc(self, data):
return data['close'].mean()
factors = calc_factors(securities, [MyFactor()], start_date, end_date)详见 与 、。
fator.mddata/Alpha101.mddata/Alpha191.mdpython
from jqfactor import Factor, calc_factors
class MyFactor(Factor):
name = 'my_factor'
max_window = 5
dependencies = ['close']
def calc(self, data):
return data['close'].mean()
factors = calc_factors(securities, [MyFactor()], start_date, end_date)See and , for details.
fator.mddata/Alpha101.mddata/Alpha191.md关键注意事项
Key Notes
防止未来函数
Prevent Look-ahead Bias
- 、
get_all_securities(date=...)等必须传入历史时点的get_index_stocks(..., date=...),不能用未来日期date - /
history取天数据时不包含当天;要当天数据需取分钟级attribute_history - 技术指标 只精确到日期时返回收盘值,盘中调用当天会产生未来数据
check_date - 财务数据默认按公告日期处理,注意 的
get_fundamentals参数含义date
- ,
get_all_securities(date=...), etc. must pass a historical point-in-timeget_index_stocks(..., date=...), cannot use future datesdate - /
historydo not include the current day when retrieving daily data; to get current day data, retrieve minute-level dataattribute_history - When for technical indicators is only accurate to the date, it returns the closing value; calling it during trading hours for the current day will cause look-ahead bias
check_date - Financial data is processed by announcement date by default, pay attention to the meaning of the parameter in
dateget_fundamentals
运行频率
Execution Frequency
- 优先使用 ,避免与
run_daily混用handle_data - 频率与回测设置一致
run_daily(func, time='every_bar') - 的
run_weekly/monthly可避免晚注册时的就近执行force=False
- Prioritize using , avoid mixing with
run_dailyhandle_data - frequency is consistent with backtesting settings
run_daily(func, time='every_bar') - in
force=Falsecan avoid near execution when registered laterun_weekly/monthly
数据查询限制
Data Query Limits
- /
run_query单次最多返回 4000 行get_fundamentals - 不支持连表查询
run_query - 默认行情为前复权;为不复权
fq=None
- /
run_queryreturn a maximum of 4000 rows per queryget_fundamentals - does not support join table queries
run_query - Default market quotes are forward-adjusted; means no adjustment
fq=None
环境与产品区分
Environment and Product Differentiation
| 产品 | 使用场景 |
|---|---|
| 回测、模拟、研究 |
| 本地量化研究,不能在官网策略中 import |
| Product | Usage Scenario |
|---|---|
| Backtesting, paper trading, research |
| Local quantitative research, cannot be imported in official website strategies |
按场景选文档
Select Documents by Scenario
| 场景 | 首先阅读 | 深入查阅 |
|---|---|---|
| 新手写第一个策略 | | |
| 股票选股 + 财务 | | |
| 指数成分股策略 | | |
| 行业/概念轮动 | | |
| 期货策略 | | |
| 期权策略 | | |
| 基金/ETF | | |
| 可转债 | | — |
| 宏观数据 | | — |
| 技术分析指标 | | — |
| 因子选股 | | |
| 融资融券 | | |
| 报错/数据疑问 | | |
| Scenario | First Read | Further Consultation |
|---|---|---|
| Newcomer writing first strategy | | |
| Stock selection + financial data | | |
| Index component strategy | | |
| Industry/concept rotation | | |
| Futures strategy | | |
| Options strategy | | |
| Fund/ETF | | |
| Convertible bonds | | — |
| Macro data | | — |
| Technical analysis indicators | | — |
| Factor-based stock selection | | |
| Margin trading | Margin trading section in | Margin trading-specific functions in |
| Errors/data questions | | "Notes" in |
策略示例
Strategy Examples
完整示例见 末尾「策略示例」:均线策略、多股票持仓、追涨策略、万圣节效应等。
api.mdComplete examples can be found in the "Strategy Examples" section at the end of : moving average strategy, multi-stock holding, momentum chasing strategy, Halloween effect, etc.
api.md文档更新
Document Update
本地数据字典由脚本从官网同步:
bash
bun scripts/get-joinquant-docs.tsThe local data dictionary is synchronized from the official website via script:
bash
bun scripts/get-joinquant-docs.ts强制覆盖已有 md:FORCE_UPDATE=1 bun scripts/get-joinquant-docs.ts
Force overwrite existing md files: FORCE_UPDATE=1 bun scripts/get-joinquant-docs.ts
undefinedundefined附加资源
Additional Resources
- 完整文档索引:reference.md
- 平台 API 全文:api.md
- 常见问题:faq.md
- 因子分析:fator.md
- Complete document index: reference.md
- Full platform API: api.md
- Frequently Asked Questions: faq.md
- Factor Analysis: fator.md