文章声明:本文内容为个人业余研究所得,与任何单位或机构无关。文中提及的股票代码仅用于示例测试,不构成投资建议。投资存在风险,相关代码仅供学习使用,禁止用于商业用途。
近期有交流者反馈,ptrade平台缺乏足够的代码示例,导致在自主开发策略时难以入手。为此,我花费约一周时间整理并编写了一套ptrade交易教程。目前内容已完成一半左右,预计再用两周时间即可全部完善。后续可通过参考所提供的代码进行学习和实践,同时我也计划录制完整的量化交易教学视频,便于系统性掌握相关技能。
由于资料内容较为丰富,为方便查阅与获取源码,已将全部资源上线至专用网页,支持直接访问和下载。
用户可点击链接进入网页主界面,操作更直观,资源下载也更为便捷。
进入页面后,选择“ptrade源代码教程”选项即可查看对应教学内容。
点击“查看教程”按钮,即可浏览详细说明文档。
任选一个入口均可正常访问教程内容,结构清晰,易于导航。
如需获取源代码,请点击页面右下角的“源代码下载”按钮。
部分区域需要登录验证,输入指定账号密码后即可进入。授权码由后台统一管理,如有需要可按流程申请。
根据需求选择相应模块进行下载。第一个文件为完整源码压缩包,包含当前所有代码内容,后续仍在持续更新中。
点击目标条目后执行下载操作,过程简单快捷。
下载完成后,可直接打开文件并将代码复制到ptrade环境中运行调试。
以下为部分基础策略代码参考示例:
'''
ptrade西蒙斯逆回购
作者:西蒙斯量化
微信:xg_quant
时间:20250829
'''
import?math
import?pandas?as?pd
def?initialize(context):
? ??# 初始化策略
? ??#一天期的深圳逆回购标的
? ? g.stock='131810.SZ'
? ??#保留的资金,避免新股,可转债等申购
? ? g.cash=0
? ??print('开始运行逆回购策略*********************')
? ? run_daily(context, func=run_reverse_repurchase, time='14:55')
def?run_reverse_repurchase(context):
? ??'''
? ? 逆回购函数
? ? '''
? ? current_dt=context.blotter.current_dt
? ? current_dt=current_dt.strftime('%Y-%m-%d')
? ? account=get_xg_account(context)
? ??if?account.shape[0]>0:
? ? ? ? cash=account['可用金额'].tolist()[-1]
? ? ? ??print('可以金额****************',cash)
? ? ? ? cash=cash-g.cash
? ? ? ??#逆回购最低1000元10张一手
? ? ? ??if?cash>=1000:
? ? ? ? ? ? amount =?int(cash/1000)*10
? ? ? ? ? ??if?amount>=10:
? ? ? ? ? ? ? ??#全部逆回购卖出
? ? ? ? ? ? ? ? order(g.stock, -1*amount)
? ? ? ? ? ? ? ??print(current_dt,'逆回购回购成功')
? ? ? ? ? ??else:
? ? ? ? ? ? ? ??print(current_dt,'逆回购回购失败,低于最低数量')
? ? ? ??else:
? ? ? ? ? ?print(current_dt,'逆回购回购失败,低于最低金额')
? ??else:
? ? ? ??print(current_dt,'逆回购回购失败,没有金额')
def?get_xg_account(context):
? ??'''
? ? 获取账户数据
? ? '''
? ? df=pd.DataFrame()
? ? df['可用金额']=[context.portfolio.cash]
? ? df['总资产']=[context.portfolio.portfolio_value]
? ? df['持仓价值']=[context.portfolio.positions_value]
? ? df['已使用现金']=[context.portfolio.capital_used]
? ? df['当前收益比例']=[context.portfolio.returns]
? ? df['初始账户总资产']=[context.portfolio.pnl]
? ? df['开始时间']=[context.portfolio.start_date]
? ??return?df
def?get_xg_position(context):
? ??'''
? ? 获取持股数据
? ? '''
? ? data=pd.DataFrame()
? ? positions=context.portfolio.positions
? ? stock_list=list(set(positions.keys()))
? ??print('持股数量{}'.format(len(stock_list)))
? ??for?stock?in?stock_list:
? ? ? ? df=pd.DataFrame()
? ? ? ? df['证券代码']=[positions[stock].sid]
? ? ? ? df['可用数量']=[positions[stock].enable_amount]
? ? ? ? df['持有数量']=[positions[stock].amount]
? ? ? ? df['最新价']=[positions[stock].last_sale_price ]
? ? ? ? df['成本价']=[positions[stock].cost_basis ]
? ? ? ? df['今日买入']=[positions[stock].today_amount ]
? ? ? ? df['持股类型']=[positions[stock].business_type ?]
? ? ? ? data=pd.concat([data,df],ignore_index=True)
? ??'''
? ? if data.shape[0]>0:
? ? ? ? if g.is_del=='是':
? ? ? ? ? ? print('开始策略隔离**********')
? ? ? ? ? ? data['隔离']=data['证券代码'].apply(lambda x: '是' if x in g.stock_list else '不是')
? ? ? ? ? ? data=data[data['隔离']=='是']
? ? ? ? else:
? ? ? ? ? ? print('不开启策略隔离*********')
? ? '''
? ??return?data
def?get_xg_order(context):
? ??'''
? ? 获取委托数据
? ? '''
? ? orders=get_orders()
? ??print("委托数量{}".format(len(orders)))
? ? data=pd.DataFrame()
? ??if?len(orders)>0:
? ? ? ??for?ors?in?orders:
? ? ? ? ? ? df=pd.DataFrame()
? ? ? ? ? ? df['订单号']=[ors.id]
? ? ? ? ? ? df['订单产生时间']=[ors.dt]
? ? ? ? ? ? df['指定价格']=[ors.limit ]
? ? ? ? ? ? df['证券代码']=[ors.symbol ]
? ? ? ? ? ? df['委托数量']=[ors.amount ]
? ? ? ? ? ? df['订单生成时间']=[ors.created ]
? ? ? ? ? ? df['成交数量']=[ors.filled ]
? ? ? ? ? ? df['委托编号']=[ors.entrust_no]
? ? ? ? ? ? df['盘口档位']=[ors.priceGear ]
? ? ? ? ? ? df['订单状态']=[ors.status ]
? ? ? ? ? ? data=pd.concat([data,df],ignore_index=True)
? ??else:
? ? ? ? data=data
? ??return?data
def?get_xg_position_on(context,security=''):
? ??''''
? ? 获取单股的持股情况
? ? '''
? ? pos=get_positions(security=security)
? ? df=pd.DataFrame()
? ??if?len(pos)>0:
? ? ? ? df['证券代码']=[pos[security].sid]
? ? ? ? df['可以数量']=[pos[security].enable_amount]
? ? ? ? df['持有数量']=[pos[security].amount]
? ? ? ? df['最新价']=[pos[security].last_sale_price ]
? ? ? ? df['成本价']=[pos[security].cost_basis ]
? ? ? ? df['今日买入']=[pos[security].today_amount ]
? ? ? ? df['持股类型']=[pos[security].business_type ?]
? ??else:
? ? ? ? df=df
? ??return?df
'''
西蒙斯ptrade新股新债申购
作者:西蒙斯量化
微信:xg_quant
时间:20250831
代码只支持实盘,不支持回测
'''
from?datetime?import?datetime
def?initialize(context):
? ??# 初始化策略
? ??print('西蒙斯新股新债申购')
? ? run_daily(context, xms_ipo, time='14:50')
def?before_trading_start(context, data):
? ??'''
? ? 盘前
? ? '''
? ? current =datetime.now().strftime('%Y-%m-%d')
? ??print('开始运行西蒙斯新股新债申购策略',current)
def?xms_ipo(context):
? ??'''
? ? 西蒙斯新股新债申购
? ? 参数
? ? submarket_type:申购代码所属市场,不传时默认申购全部新股(int);
? ? black_stocks:黑名单股票,可以是单个股票或者股票列表,传入的黑名单股票将不做申购,不传时默认申购全部新股(str/list);
? ? 返回
? ? 返回dict类型,包含委托代码、委托编号、委托状态(委托失败为0,委托成功为1)、委托数量等信息(dict[str:dict[str:str,str:int,str:float],...])
? ? {'732116.SS': {'entrust_no': '205001', 'entrust_status': 1, 'redemption_amount': 1000}, '732100.SS': {'entrust_no': '205002'
? ? '''
? ??#申购全部的标的
? ? current =datetime.now().strftime('%Y-%m-%d')
? ??try:
? ? ? ? stats=ipo_stocks_order()
? ? ? ??print(current,'今天的申购结果',stats)
? ??except?Exception?as?e :
? ? ? ??print(current,'申购有问题')
def?after_trading_end(context, data):
? ??'''
? ? 盘后
? ? '''
? ? current =datetime.now().strftime('%Y-%m-%d')
? ??print('西蒙斯新股新债申购策略今天运行结束',current)
def?get_xg_position(context):
? ??'''
? ? 获取持股数据
? ? '''
? ? data=pd.DataFrame()
? ? positions=context.portfolio.positions
? ? stock_list=list(set(positions.keys()))
? ??print('持股数量{}'.format(len(stock_list)))
? ??for?stock?in?stock_list:
? ? ? ? df=pd.DataFrame()
? ? ? ? df['证券代码']=[positions[stock].sid]
? ? ? ? df['可用数量']=[positions[stock].enable_amount]
? ? ? ? df['持有数量']=[positions[stock].amount]
? ? ? ? df['最新价']=[positions[stock].last_sale_price ]
? ? ? ? df['成本价']=[positions[stock].cost_basis ]
? ? ? ? df['今日买入']=[positions[stock].today_amount ]
? ? ? ? df['持股类型']=[positions[stock].business_type ?]
? ? ? ? data=pd.concat([data,df],ignore_index=True)
? ??'''
? ? if data.shape[0]>0:
? ? ? ? if g.is_del=='是':
? ? ? ? ? ? print('开始策略隔离**********')
? ? ? ? ? ? data['隔离']=data['证券代码'].apply(lambda x: '是' if x in g.stock_list else '不是')
? ? ? ? ? ? data=data[data['隔离']=='是']
? ? ? ? else:
? ? ? ? ? ? print('不开启策略隔离*********')
? ? '''
? ??return?data
def?get_xg_order(context):
? ??'''
? ? 获取委托数据
? ? '''
? ? orders=get_orders()
? ??print("委托数量{}".format(len(orders)))
? ? data=pd.DataFrame()
? ??if?len(orders)>0:
? ? ? ??for?ors?in?orders:
? ? ? ? ? ? df=pd.DataFrame()
? ? ? ? ? ? df['订单号']=[ors.id]
? ? ? ? ? ? df['订单产生时间']=[ors.dt]
? ? ? ? ? ? df['指定价格']=[ors.limit ]
? ? ? ? ? ? df['证券代码']=[ors.symbol ]
? ? ? ? ? ? df['委托数量']=[ors.amount ]
? ? ? ? ? ? df['订单生成时间']=[ors.created ]
? ? ? ? ? ? df['成交数量']=[ors.filled ]
? ? ? ? ? ? df['委托编号']=[ors.entrust_no]
? ? ? ? ? ? df['盘口档位']=[ors.priceGear ]
? ? ? ? ? ? df['订单状态']=[ors.status ]
? ? ? ? ? ? data=pd.concat([data,df],ignore_index=True)
? ??else:
? ? ? ? data=data
? ??return?data
def?get_xg_position_on(context,security=''):
? ??''''
? ? 获取的持股情况
? ? '''
? ? pos=get_positions(security=security)
? ? df=pd.DataFrame()
? ??if?len(pos)>0:
? ? ? ? df['证券代码']=[pos[security].sid]
? ? ? ? df['可以数量']=[pos[security].enable_amount]
? ? ? ? df['持有数量']=[pos[security].amount]
? ? ? ? df['最新价']=[pos[security].last_sale_price ]
? ? ? ? df['成本价']=[pos[security].cost_basis ]
? ? ? ? df['今日买入']=[pos[security].today_amount ]
? ? ? ? df['持股类型']=[pos[security].business_type ?]
? ??else:
? ? ? ? df=df
? ??return?df
扫码加好友,拉您进群



收藏
