请 [注册] 或 [登录]  | 返回主站

量化交易吧 /  量化平台 帖子:3365793 新帖:0

一个长期策略,2008-2018

我是小编发表于:5 月 10 日 00:06回复(1)

引入函数

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

全部回复

0/140

量化课程

    移动端课程