【量化投资】策略三(聚宽)
from jqlib.technical_analysis import *
def initialize(context):
g.stocksnum = 5 # 持有最小市值股票数
g.period = 10 # 轮动频率
log.set_level('order', 'error')
run_daily(daily, time='before_open') # 周期循环daily
run_daily(mktopen, time='every_bar')
g.days = 1 # 记录策略进行到第几天,初始为1
g.holdpct = 1
def trade(context, buylist):
# 对于每个当下持有的股票进行判断:现在是否已经不在buylist里,如果是则卖出
for stock in context.portfolio.positions:
if stock not in buylist: # 如果stock不在buylist
order_target(stock, 0) # 调整stock的持仓为0,即卖出
# 将总资产(现金+股票)除以持股数
position_per_stk = g.holdpct * context.portfolio.total_value / g.stocksnum
# 调整buylist中的每个股票持仓价值为position_per_stk
for stock in buylist:
order_target_value(stock, position_per_stk)
# 止损
def stop(context):
# 循环查看持仓的每个股票
for stock in context.portfolio.positions:
# 如果股票最新价格除以平均成本小于0.8,即亏损超过20%
if context.portfolio.positions[stock].price / context.portfolio.positions[stock].avg_cost < 0.8:
# 调整stock的持仓为0,即卖出
order_target(stock, 0)
# 输出日志:股票名 止损
print "\n%s 止损" % stock
def pick(context):
date = context.current_dt.strftime("%Y-%m-%d")
# # 获取上证指数和深证综指的成分股代码并连接,即为全A股市场所有股票
# scu = get_index_stocks('') + get_index_stocks('')
scu = get_industry_stocks('HY007') + get_industry_stocks('801180') + get_concept_stocks('GN069')
# 选出在scu内的股票的股票代码,并按照当前时间市值从小到大排序
df = get_fundamentals(query(
valuation.code, valuation.market_cap
).filter(
valuation.code.in_(scu)
).order_by(
valuation.market_cap.desc()
), date=date
)
# 取出前名的股票代码,并转成list类型,buylist为选中的股票
buylist = list(df['code'][:g.stocksnum])
return buylist
def mktopen(context):
# 每分钟止损
stop(context)
def mkt_index(context):
mktindex = history(count=1, field='close', security_list=[''])
mktindex = mktindex.ix[-1, '']
date =context.current_dt.strftime("%Y-%m-%d")
ma20 = MA([''], check_date=date, timeperiod=20)
ma20 = ma20['']
if mktindex > ma20:
return 1
return 0.5
def daily(context):
# 判断策略进行天数是否能被轮动频率整除余1
if g.days % g.period == 1:
buylist = pick(context)
g.holdpct = mkt_index(context)
trade(context, buylist)
else:
pass # 什么也不做
g.days = g.days + 1 # 策略经过天数增加1