一、简单的量化策略Demo
二、双均线策略Demo
一、简单的量化策略Demo
设置股票池为沪深300的所有成分股(沪深300:从上海和深圳选出的有代表性的300支股票)
如果当前股价小于10/股且当前不持仓,则买入;
如果当前股价比买入时上涨了25%,则清仓止盈;
如果当前股价比买入时下跌了10%,则清仓止损。

# 导入函数库 import jqdata # 初始化函数,设定基准等等,入市之前干的事 def initialize(context): # 保存沪深300的300支股票在全局变量g里 g.security = get_index_stocks('000300.XSHG') # 开启动态复权模式(真实价格),模拟盘使用真实价格成交 set_option('use_real_price', True) #set_benchmark('000300.XSHG') # 股票类每笔交易时的手续费是:买入时佣金万分之三,卖出时佣金万分之三加千分之一印花税, 每笔交易佣金最低扣5块钱 set_order_cost(OrderCost(close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5), type='stock') # 设置基准收益,一般写一个指数,基准收益与策略收益对比 # 基准一般表示大盘走势 set_benchmark('000300.XSHG') # handle_data函数是在每个交易日执行一次,从2016-06-01至2016-12-31 def handle_data(context, data): # 获取某股票的开盘价 #print(get_current_data()['000001.XSHE'].day_open) # 获取某股票当前时间的前count天的历史数据 #attribute_history(security, count) #下单,每天买100股 #order('000001.XSHE', 100) #下单,买10000块钱的股票 #order_value('000001.XSHE', 10000) #买到300股,之前是100股例如。为0表示全卖 #order_target('000001.XSHE',300) #买到10000块钱价值的股票,例如之前值2000块 #order_target_value('000001.XSHE',10000) # 一般情况下,是先买后买 tobuy = [] for stock in g.security: # 当天股票开盘价 p = get_current_data()[stock].day_open # 这支股票持有多少股 amount = context.portfolio.positions[stock].total_amount # a_cost是开仓的每只股票成本 a_cost = context.portfolio.positions[stock].avg_cost if amount > 0 and p >= a_cost * 1.25: order_target(stock, 0) #止盈 if amount > 0 and p <= a_cost * 0.9: order_target(stock, 0) #止损 if p <= 10.0 and amount == 0: tobuy.append(stock) # 要买的股票 cash_per_stock = context.portfolio.available_cash / len(tobuy) for stock in tobuy: order_value(stock, cash_per_stock)
二、双均线策略Demo

import jqdata # 初始化函数,设定基准等等 def initialize(context): # 设定沪深300作为基准 set_benchmark('000300.XSHG') # 开启动态复权模式(真实价格) set_option('use_real_price', True) # 过滤掉order系列API产生的比error级别低的log log.set_level('order', 'error') ### 股票相关设定 ### # 股票类每笔交易时的手续费是:买入时佣金万分之三,卖出时佣金万分之三加千分之一印花税, 每笔交易佣金最低扣5块钱 set_order_cost(OrderCost(close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5), type='stock') g.security = ['601318.XSHG'] g.p1 = 5 g.p2 = 10 def handle_data(context, data): for stock in g.security: # 金叉死叉交替出现,当出现第一次5日>10日表示金叉来了,出现第一次10日>5日表示死叉来了 # 金叉:如果5日均线>10日均线并且不持仓 # 死叉:如果如果5日均线<10日均线并且持仓 df = attribute_history(stock, g.p2) ma10 = df['close'].mean() ma5 = df['close'][-5:].mean() if ma10 > ma5 and stock in context.portfolio.positions: #死叉卖出 order_target(stock, 0) print('卖出') if ma10 < ma5 and stock not in context.portfolio.positions: #金叉买入 order_target_value(stock, context.portfolio.available_cash) print('买入')