四、知识
五、代码
# 导入函数库 import math import talib as tl import pandas as pd import numpy as np from datetime import timedelta # 设定最大显示行数、列数为10000 pd.set_option('display.max_rows', 10000) # 初始化函数,设定基准等等 def initialize(context): # 初始化此策略 # 设置要操作的股票池为空,每天需要不停变化股票池 set_universe([]) # 设置手续费,买入时万分之三,卖出时万分之三加千分之一印花税, 每笔交易最低扣5块钱 # set_commission(PerTrade(buy_cost=0.0003, sell_cost=0.0013, min_cost=5)) # 设置风险基准为沪深300指数 g.riskbench = '000300.XSHG' # 设置基准对比为沪深300指数 set_benchmark(g.riskbench) # 初始化当日买卖列表 g.stock_buy = [] g.stock_sell = [] g.stock_hold = [] # 初始化综合风险结果 g.ris = 10 g.ar = 1 # 记录真实RSI_F和AR g.RIS_T = 0 g.AR_T = 0 # 初始化持仓比例 g.hold_radio = 0 g.hold_limit = 0 # 仓位控制趋势 g.hold_dir = 0 # 初始化风险仓位表 risk_radio为基准持仓比例,risk_hold为是否可长期持仓标志 d = {'risk_radio' : pd.Series([90, 75, 70, 45, 20], index = [50, 40, 30, 20, 10]), 'risk_radio_limit' : pd.Series([100, 100, 100, 60, 40], index = [50, 40, 30, 20, 10])} g.con_df_risk = pd.DataFrame(d) # 初始化风险变化趋势数据 g.risk_day1 = 0 g.risk_day2 = 0 g.risk_day3 = 0 # 风险累积累值 g.risk_count = 0 # 初始化日期 g.d_yesterday = '' g.d_today = '' # 初始化风险参数 g.con_FAST_RSI = 20 g.con_SLOW_RSI = 60 g.con_AR_COUNT = 26 # 以4天为期间计算AR值(普通为26天),反应长期趋势 # 去除创业版 g.stock1 = get_index_stocks('399006.XSHE') g.stock2 = get_index_stocks('399012.XSHE') # 关闭部分log log.set_level('order', 'error') ## 运行函数(reference_security为运行时间的参考标的;传入的标的只做种类区分,因此传入'000300.XSHG'或'510300.XSHG'是一样的) # 开盘时运行 run_monthly(handle,1) def handle(context): industrys = ['A01','A02','A03','A04','A05','B06','B07','B08','B09','B11', 'C13','C14','C15','C17','C18','C19','C20','C21','C22','C23', 'C24','C25','C26','C27','C28','C29','C30','C31','C32','C33', 'C34','C35','C36','C37','C38','C39','C40','C41','C42', 'D44','D45','D46','E47','E48','E50','F51','F52', 'G53','G54','G55','G56','G58','G59','H61','H62', 'I63','I64','I65','J66','J67','J68','J69','K70','L71','L72', 'M73','M74','N77','N78','P82','Q83','R85','R86','R87','S90'] df_industrys = pd.DataFrame(index = ['DH4', 'DT4', 'CHANGE', 'SORT_DH4' ,'SORT_DT4']) stocks = get_industry_stocks('A01') df_list = get_price(stocks, start_date = g.d_today, end_date = g.d_today, frequency = 'daily', fields = ['close', 'pre_close'],panel=False) df_close = history(4, unit='1d', field='close', security_list = stocks) df_close = df_close.append(df_list['close']) df_pre_close = history(4, unit='1d', field='pre_close', security_list = stocks) df_pre_close = df_pre_close.append(df_list['pre_close']) df_dustry = (df_close - df_pre_close) / df_pre_close df_dustry = df_dustry.T.sum() / len(stocks) #df.T表示行与列对调,之前是日期,股票1,股票2这样的形式 sum_DH4 = df_dustry.head(4).sum() #取最近4天的总和 sum_DT4 = df_dustry.tail(4).sum() #取最近2天的,以及close,preclose(但这两个数为0?) df_dustry = pd.DataFrame([sum_DH4, sum_DT4, 0, 0, 0], index = ['DH4', 'DT4', 'CHANGE', 'SORT_DH4' ,'SORT_DT4'], columns = ['industry']) #concat函数是在pandas底下的方法,可以将数据根据不同的轴作简单的融合 df_industrys = pd.concat([df_industrys, df_dustry], axis = 1, join_axes = [df_industrys.index]) print(df_industrys)