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_params()
# 设置回测
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):
# 将滑点设置为0)
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)
#print(len(context.portfolio.positions))
#print(lists)
#elif ma_line(context,'000001.XSHG')=='stay':
#pass
#print(len(context.portfolio.positions))
else:
#sell_out(context)
stop_loss(context)
#print(len(context.portfolio.positions))
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.eps < 0.6,
indicator.roe > 20
).order_by(
# 按roe降序排列
indicator.roe.desc()
).limit(
# 最多返回100个
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)
#print(len(g.to_buy_list))
## 获取持仓列表
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'])
# 取得过去60天的最高价格
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
本社区仅针对特定人员开放
查看需注册登录并通过风险意识测评
5秒后跳转登录页面...
移动端课程