#小策略,策略逻辑是在金叉时候买进,死叉时候卖出,所谓金叉死叉是两条均线的交叉,当短期均线上穿长期均线为金叉,反之为死叉
#下面是策略代码及结构
# 导入函数库
from jqdata import *
# 初始化函数
def initialize(context):
# 设定沪深300作为基准
set_benchmark('000300.XSHG')
# True为开启动态复权模式,使用真实价格交易
set_option('use_real_price', True)
# 股票类交易手续费是:买入时佣金万分之三,卖出时佣金万分之三加千分之一印花税, 每笔交易佣金最低扣5块钱
set_order_cost(OrderCost(open_tax=0, close_tax=0.001, \
open_commission=0.0003, close_commission=0.0003,\
close_today_commission=0, min_commission=5), type='stock')
#华谊股票
g.security='300027.XSHE'
#设置每天运行
run_daily(handle)
def handle(context):
security=g.security
n5=5
n20=20
# 获取股票的收盘价
close_data = attribute_history(security, n20, '1d',"close",df=False)
print(close_data)
# 取得过去 ma_n1 天的平均价格
ma_n5 = close_data['close'][-n5:].mean()
# 取得过去 ma_n2 天的平均价格
ma_n20 = close_data['close'][-n20:].mean()
print(ma_n5,ma_n20)
# 取得当前的现金
cash = context.portfolio.available_cash
# 如果当前有余额
if ma_n5 > ma_n20:
# 用所有 cash 买入股票,order_value是买卖价值
order_value(security, cash)
# 记录这次买入
log.info("Buying %s" % security)
# 如果n5日均线小于n20日均线,并且目前有头寸
elif ma_n5 < ma_n20 and context.portfolio.positions[security].closeable_amount > 0:
# 全部卖出,order_target是买卖数量
order_target(security, 0)
# 记录这次卖出
log.info("Selling %s" % (security))
# 绘制n5日均线价格
record(ma_n5=ma_n5)
# 绘制n20日均线价格
record(ma_n20=ma_n20)
#整体结果在12-16年回测测试结果效益不错,阿尔法贝塔最大回撤也还行,难点是在策略和框架的使用和调用,这就是这次的双均线策略记录