引入函数
import statsmodels.api as sm
import numpy as np
import matplotlib.pyplot as plt
import time
import pandas as pd
from datetime import date
from jqdata import *
设定全局变量
g.to_buy_list=[]
g.sell_list=[]
g.buy = 0
g.sell = 0
初始函数
def initialize (context):
set_backtest()
set_slip_fee(context)
run_daily(market_open, 'every_bar')
设定参数
def set_params():
g.days=0
g.refresh_rate=9
g.stocknum=3
回测条件
def set_backtest():
set_benchmark('000001.XSHG')
set_option('use_real_price', True)
log.set_level('order', 'error')
根据不同的时间段设置滑点与手续费
def set_slip_fee(context):
set_slippage(FixedSlippage(0))
dt=context.current_dt
if dt>datetime.datetime(2013,1, 1):
set_commission(PerTrade(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
elif dt>datetime.datetime(2011,1, 1):
set_commission(PerTrade(buy_cost=0.001, sell_cost=0.002, min_cost=5))
elif dt>datetime.datetime(2009,1, 1):
set_commission(PerTrade(buy_cost=0.002, sell_cost=0.003, min_cost=5))
else:
set_commission(PerTrade(buy_cost=0.003, sell_cost=0.004, min_cost=5))
开盘时运行函数
def market_open(context):
dt=context.current_dt
if ma_line(context,'000001.XSHG')=='buy' or ma_line(context,'000001.XSHG')=='stay':
stop_pro(context)
lists = choose(context)
buy_in(context,lists)
else:
stop_loss(context)
print(len(context.portfolio.positions))
选股函数
def choose(context):
g.to_buy_list=[]
df = get_fundamentals(query(
valuation.code, valuation.pe_ratio, valuation.market_cap, indicator.eps, indicator.inc_return, indicator.inc_net_profit_annual
).filter(
valuation.pe_ratio > 25,
valuation.pe_ratio < 30,
indicator.inc_revenue_annual > 25,
indicator.inc_net_profit_annual > 25,
indicator.eps > 0.3,
indicator.roe > 20
).order_by(
indicator.roe.desc()
).limit(
100), date=None)
mylist = pd.DataFrame(columns = ('code','order'))
i=0
for stock in df['code']:
mylist=mylist.set_value(len(mylist),['code','order'],[stock,i])
i=i 1
stocksort=mylist.sort('order')['code']
g.to_buy_list=list(stocksort)
return g.to_buy_list
买入函数
def buy_in(context,security):
cash = context.portfolio.cash
for sec in security:
if len(context.portfolio.positions)<10:
if sec not in context.portfolio.positions:
if cash >10000:
order_value(sec,10000)
else:
order_value(sec,cash)
else:
pass
else:
pass
卖出函数
def sell_out(context):
for sec in context.portfolio.positions:
order_target(sec,0)
大盘择时
def ma_line(context, security):
#000001.XSHG
# 获取指数的收盘价
close_data = attribute_history(security, 60, '1d', ['close'])
# 取得过去五天的平均价格
MA1 = close_data['close'][-1:]
MA1 = MA1.mean()
MA2 = close_data['close'][-2:-1]
MA2 = MA2.mean()
MA3 = close_data['close'][-3:-2]
MA3 = MA3.mean()
MA5 = close_data['close'][-2:-1]
MA5 = MA5.mean()
MA10 = close_data['close'][-10:]
MA10 = MA10.mean()
MA30 = close_data['close'][-30:]
MA30 = MA30.mean()
MA60 = close_data['close']
MA60 = MA60.mean()
if MA5>MA10 and MA10>MA30:
#print('Up')
return 'buy'
elif MA1/MA2<0.91:
#print('Down')
g.sell = 1
#print(g.sell, context.current_dt)
return 'sell'
else:
#print('Silence')
return 'stay'
个股止损函数
def stop_loss(context):
g.sell_list=[]
if len(context.portfolio.positions)>0:
for code in context.portfolio.positions:
high = high_price(code)
if context.portfolio.positions[code].price/high < 0.9:
order_target(code,0)
else:
pass
else:
pass
最高价函数
def high_price(sec):
close_data = attribute_history(sec, 60, '1d', ['close'])
high = max(close_data['close'])
return high
个股止盈
def stop_pro(context):
if len(context.portfolio.positions)>0:
for code in context.portfolio.positions:
if context.portfolio.positions[code].price/context.portfolio.positions[code].avg_cost>=1.3:
order_target(code,0)
else:
pass
else:
pass