@Channelchan
2018-01-13T02:50:28.000000Z
字数 5153
阅读 85989
from jaqs.data.dataapi import DataApifrom jaqs.data import DataViewfrom jaqs.research import SignalDiggerimport numpy as npfrom datetime import datetimeimport pandas as pdfrom datetime import timedeltaimport warningswarnings.filterwarnings("ignore")dataview_folder = 'JAQS_Data/hs300'dv = DataView()dv.load_dataview(dataview_folder)
D:\Anaconda3\lib\site-packages\statsmodels\compat\pandas.py:56: FutureWarning: The pandas.core.datetools module is deprecated and will be removed in a future version. Please use the pandas.tseries module instead.
from pandas.core import datetools
Dataview loaded successfully.
def change_columns_index(signal):new_names = {}for c in signal.columns:if c.endswith('SZ'):new_names[c] = c.replace('SZ', 'XSHE')elif c.endswith('SH'):new_names[c] = c.replace('SH', 'XSHG')signal = signal.rename_axis(new_names, axis=1)signal.index = pd.Index(map(lambda x: datetime.strptime(str(x),"%Y%m%d") , signal.index))signal.index = pd.Index(map(lambda x: x+timedelta(hours=15), signal.index))return signal
mask = dv.get_ts('mask_fundamental')group = change_columns_index(dv.get_ts('group'))ROE_Data = change_columns_index(dv.get_ts('roe').shift(1, axis=0)[mask==0])prices = change_columns_index(dv.get_ts('close_adj'))
def get_largest(df, n=20):largest_list = []for time_index, value in df.iterrows():largest_list.append(dict.fromkeys(value.nlargest(n).index,1))largest_df = pd.DataFrame(largest_list, index = df.index)return largest_df
stock_df = get_largest(ROE_Data).dropna(how='all', axis=1)
stock_df.to_excel('roe_backtest.xlsx')
import numpy as npimport talib as taimport pandas as pdimport rqalphafrom rqalpha.api import *#读取文件位置def init(context):context.codes = stock_dfcontext.stocks = []context.SHORTPERIOD = 20# scheduler.run_weekly(find_pool, tradingday=1)scheduler.run_daily(find_pool)def find_pool(context, bar_dict):try:codes = context.codes.loc[context.now]except KeyError:returnstocks = codes.index[codes == 1]context.stocks = stocksdef handle_bar(context, bar_dict):buy(context, bar_dict)def buy(context, bar_dict):pool = context.stocks# print (pool)if pool is not None:stocks_len = len(pool)for stocks in context.portfolio.positions:if stocks not in pool:order_target_percent(stocks, 0)for codes in pool:try:price = history_bars(codes, context.SHORTPERIOD+10, '1d', 'close')short_avg = ta.SMA(price, context.SHORTPERIOD)cur_position = context.portfolio.positions[codes].quantityif short_avg[-1]<short_avg[-3] and cur_position > 0:order_target_value(codes, 0)if short_avg[-1] > short_avg[-3]:order_target_percent(codes, 1.0/stocks_len)except Exception:passconfig = {"base": {"start_date": "2015-09-01","end_date": "2017-12-30","accounts": {'stock':1000000},"benchmark": "000300.XSHG"},"extra": {"log_level": "error",},"mod": {"sys_analyser": {"enabled": True,"plot": True}}}rqalpha.run_func(init=init, handle_bar=handle_bar, config=config)

def get_largest_weight(df, n=20):largest_list = []for time_index, value in df.iterrows():largest_list.append(value.nlargest(n).to_dict())largest_df = pd.DataFrame(largest_list, index = df.index)return largest_df
largest_weight = get_largest_weight(ROE_Data)
weight_list = []for time_index, weight in largest_weight.iterrows():weight[weight<0]=0weiht_result = (weight/weight.sum())weight_list.append(weiht_result.to_dict())weight_df = pd.DataFrame(weight_list, index=largest_weight.index)
import numpy as npimport talib as taimport pandas as pdimport rqalphafrom rqalpha.api import *#读取文件位置def init(context):context.codes = weight_dfcontext.hs300 = '000300.XSHG'context.SHORTPERIOD = 20context.stocks = {}scheduler.run_daily(find_pool)# scheduler.run_weekly(find_pool,tradingday=3)def find_pool(context, bar_dict):codes = context.codes.loc[context.now].dropna()if codes is not None:context.stocks = codeselse:context.stocks = {}def handle_bar(context, bar_dict):buy(context, bar_dict)def buy(context, bar_dict):pool = context.stocksif pool is not None:for stocks in context.portfolio.positions:if stocks not in pool:order_target_percent(stocks, 0)for codes, target in pool.items():try:price = history_bars(codes, context.SHORTPERIOD+10, '1d', 'close')short_avg = ta.SMA(price, context.SHORTPERIOD)cur_position = context.portfolio.positions[codes].quantityif short_avg[-1]<short_avg[-3] and cur_position > 0:order_target_value(codes, 0)if short_avg[-1] > short_avg[-3]:order_target_percent(codes, target)except Exception:passconfig = {"base": {"start_date": "2015-09-01","end_date": "2017-12-30","accounts": {'stock':1000000},"benchmark": "000300.XSHG"},"extra": {"log_level": "error",},"mod": {"sys_analyser": {"enabled": True,"plot": True}}}rqalpha.run_func(init=init, handle_bar=handle_bar, config=config)

安装链接: https://github.com/xingetouzi/rqalpha-mod-optimization
import loggingfrom rqalpha_mod_optimization.optimizer import SimpleOptimizeApplicationfrom rqalpha_mod_optimization.parallel import set_parallel_method, ParallelMethodparams = {'SHORTPERIOD': range(5,40,5),}config = {"extra": {"log_level": "verbose",},"base": {"start_date": "2015-09-01","end_date": "2017-12-30","accounts": {'stock':1000000},"matching_type": "next_bar","benchmark": "000300.XSHG","frequency": "1d",}}if __name__ == "__main__":try:set_parallel_method(ParallelMethod.DASK)result = SimpleOptimizeApplication(config).open("ROE_MA_Strategy.py").optimize(params)print(result.sort_values(by=["sharpe"], ascending=False))except Exception as e:logging.exception(e)print("******POOL TERMINATE*******")
