使用JoinQuant编写量化策略需要具备一定的金融知识和编程基础:
如何通过实现一个最简单的策略?
下面对用户需要实现几个函数做下简单介绍:
1. [initialize](https://www.joinquant.com/api#initialize)
初始化方法,在整个回测、模拟实盘中最开始执行一次,用于初始一些全局变量,如设置基准、交易的手续费、股票池或滑点等等。示例如下:
def initialize(context):
# 设定沪深300为基准
set_benchmark('000300.XSHG')
# 调用此函数设置手续费,每笔交易时的手续费是, 买入时万分之三,卖出时万分之三加千分之一印花税, 每笔交易最低扣5块钱
set_commission(PerTrade(buy_cost=0.0001, sell_cost=0.001, min_cost=5))
# 调用此函数设置滑点
set_slippage(PriceRelatedSlippage(0.002))
2. [handle_data](https://www.joinquant.com/api#handledata)
该函数每个单位时间会调用一次, 如果按天回测,则每天调用一次,如果按分钟,则每分钟调用一次。
函数内部就是你的交易思路,详情可参考示例代码。
3. [before_trading_start](https://www.joinquant.com/api#beforetradingstart-可选) 和 [after_trading_end](https://www.joinquant.com/api#aftertradingend-可选)(可选)
这两个函数与handle_data基本相同,只是没有传入data参数。before_trading_start 会在每天开始交易前被调用一次,而after_trading_end 会在每天结束交易后被调用一次。
如何使用自定义消息?
JoinQuant提供了微信消息推送的功能,API为send_message
教程见:send_message用法
实例代码:
(1) 清仓止损(发送消息)
def before_trading_start(context):
g.is_stop = dp_stoploss(kernel=2, n=10, zs=0.03)
if g.is_stop:
if len(context.portfolio.positions.keys())>0:
for stock in context.portfolio.positions.keys():
order_target(stock, 0)
send_message("清仓")
return
(2) 购买股票(发送股票池)
def before_trading_start(context):
g.is_stop = dp_stoploss(kernel=2, n=10, zs=0.03)
df = get_fundamentals(query(
valuation.code, valuation.market_cap
).filter(
valuation.code.in_(chosed_stocks)
).order_by(
# 按市值降序排列
valuation.market_cap.asc()
))
g.per_buylist = list(df['code'])
send_message(g.per_buylist)