问题描述
/
解决方案
报错原因分析
在编写量化策略时,遇到 NameError: name 'pro' is not defined 报错,通常是因为您在代码中使用了未定义的变量 pro。在量化交易领域,pro 经常被用作 Tushare Pro 数据接口的实例化对象(例如 pro = ts.pro_api())。
如果您将其他平台或本地基于 Tushare 编写的代码直接复制到 ptrade 平台中运行,而没有进行相应的初始化或替换,就会触发此报错。ptrade 平台拥有自己独立且完善的内置数据 API,通常不需要依赖外部的 Tushare 接口来获取常规的行情和财务数据。
解决办法与替代方案
为了在 ptrade 中顺利运行策略,强烈建议将外部数据接口替换为 ptrade 的原生 API。这不仅能解决报错,还能大幅提升数据获取的速度和稳定性。
1. 替代历史行情数据获取
如果您原本使用 pro.daily() 或类似接口获取 K 线数据,在 ptrade 中应替换为 get_history 或 get_price。
错误代码示例(Tushare 风格):
# 报错:name 'pro' is not defined
df = pro.daily(ts_code='600570.SH', start_date='20230101', end_date='20230131')
ptrade 正确代码示例:
def handle_data(context, data):
# 使用 get_history 获取过去 5 天的日线收盘价
# 注意:ptrade 中上证后缀为 .SS,深证为 .SZ
df = get_history(5, '1d', 'close', security_list='600570.SS', fq='pre', include=False)
log.info(df)
# 或者使用 get_price 获取指定日期区间的数据
price_df = get_price('600570.SS', start_date='20230101', end_date='20230131', frequency='1d')
log.info(price_df)
2. 替代财务数据获取
如果您原本使用 pro.income()、pro.balancesheet() 等接口获取财务报表,在 ptrade 中应替换为 get_fundamentals。
错误代码示例(Tushare 风格):
# 报错:name 'pro' is not defined
df = pro.balancesheet(ts_code='600570.SH', period='20221231')
ptrade 正确代码示例:
def before_trading_start(context, data):
# 使用 get_fundamentals 获取资产负债表中的总资产数据
# 获取 600570.SS 在 2022年12月31日 之前发布的最近一份财报数据
funda_data = get_fundamentals('600570.SS', 'balance_statement', 'total_assets', date='20221231')
log.info(funda_data)
3. 替代股票列表获取
如果您原本使用 pro.stock_basic() 获取股票列表,在 ptrade 中可以使用 get_Ashares 或 get_index_stocks。
ptrade 正确代码示例:
def initialize(context):
# 获取当前所有 A 股代码列表
all_stocks = get_Ashares()
# 获取沪深300成分股
hs300_stocks = get_index_stocks('000300.SS')
set_universe(hs300_stocks)
总结
在 ptrade 平台开发策略时,请务必查阅 ptrade API 文档,使用平台提供的 get_history、get_fundamentals、get_snapshot 等内置函数。这不仅能彻底解决 pro is not defined 的问题,还能确保您的策略在回测和实盘环境中高效、稳定地运行。