1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
| from youngquant.api import * from youngquant import exec_strategy from yqdata.services.factor import *
import yqdata.services as yq import pandas as pd import numpy as np import datetime import statsmodels.api as sm import warnings import talib warnings.filterwarnings('ignore') config = { "base": { "start_date": "2021-01-01", "end_date": "2021-06-30", "frequency": "1d", "benchmark": "000300.XSHG", "accounts": { "stock": 1000000 } }, "extra": { "log_level": "error", }, "mod": { "sys_analyser": { "enabled": True, "plot": True }, "mongodb": { "enabled": True, } } }
def find_order_stocks(context, bar_dict): ''' 根据选股思路确定本月想下单的股票池,存入context.yq_order_stocks ''' df_tscodes = yq.concept.sw_detail(index_code='801156.SI') ts_codes = df_tscodes['con_code'] factors_dict = {} start_time = (context.now - datetime.timedelta(days=context.observation)).strftime("%Y%m%d") end_time = context.now.strftime("%Y%m%d") print('start_time = ',start_time) print('end_time = ',end_time) for ts_code in ts_codes: yq_code = ts_code.replace('SH', 'XSHG').replace('SZ', 'XSHE') if instruments(yq_code).days_from_listed() > context.observation and not any(is_suspended(yq_code, context.observation)): Size = yq.basic.daily_basic(ts_code=ts_code, start_date=start_time, end_date=end_time, fields='total_mv') Log_Size = np.log(Size['total_mv'].mean()) query_body = { "_source": ["ts_code", "turnover_rate_f", "trade_date"], "query": { "bool": { "must": [ {"match_phrase": {"ts_code": ts_code}}, {"exists": {"field": "turnover_rate_f"}}, {"range": {"trade_date": {"gte": start_time, "lte": end_time}}} ] } }, "size": 10000 } df = yq.common.query(index='daily_basic', body=query_body) Liquidity = np.log(df["turnover_rate_f"].sum()) dff = get_finance_factor(ts_code=ts_code,start_date=start_time, end_date=end_time,factors='debt_to_asset_ratio_ttm,book_leverage_ttm,market_leverage_ttm') if not dff.empty: dff.fillna(0, inplace=True) DTOA_mean = dff['debt_to_asset_ratio_ttm'].mean() BLEV_mean = dff['book_leverage_ttm'].mean() MLEV_mean = dff['market_leverage_ttm'].mean() Leverage = 0.35*DTOA_mean+0.27*BLEV_mean+0.38*MLEV_mean else: Leverage = 0
df_btop = yq.basic.daily_basic(ts_code=ts_code, start_date=start_time, end_date=end_time, fields='ts_code,pb') df_btop['btop']= 1/df_btop['pb'] Book_to_price =df_btop['btop'].mean() df = pd.DataFrame() df_var = yq.basic.daily_basic(ts_code=ts_code, start_date=start_time, end_date=end_time, fields='close') df['daily_return'] = df_var['close'].pct_change() df = df.drop(df.index[0]) halflife = 12 ewma = df['daily_return'].ewm(halflife=halflife).mean()
Residual_Volatility = np.sum(((df['daily_return'] - ewma) ** 2) * np.exp(-np.arange(len(df)) / halflife)) / np.sum(np.exp(-np.arange(len(df)) / halflife))
factors_dict[ts_code] = {'Size':Log_Size,'Liquidity':Liquidity,'Book_to_price': Book_to_price,'Leverage': Leverage,'Volatility': Residual_Volatility} factors_df = pd.DataFrame(factors_dict).T
factors_df['Size_rank'] = factors_df['Size'].rank(ascending=False) factors_df['Leverage_rank'] = factors_df['Leverage'].rank() factors_df['Liquidity_rank'] = factors_df['Liquidity'].rank(ascending=False) factors_df['Book_to_price_rank'] = factors_df['Book_to_price'].rank(ascending=False) factors_df['Volatility_rank'] = factors_df['Volatility'].rank(ascending=False)
topM, topN = context.topM, context.topN alternative_stocks = factors_df.query('Volatility_rank < @topM & Size_rank < @topM & Book_to_price_rank < @topM & Liquidity_rank < @topM & Leverage_rank < @topM' ) alternative_stocks['total_rank'] = alternative_stocks[['Size_rank', 'Book_to_price_rank', 'Liquidity_rank','Leverage_rank','Volatility_rank']].mean(axis=1).rank()
order_stocks = alternative_stocks.query('total_rank < @topN').index context.yq_order_stocks = [stock.replace('SH','XSHG').replace('SZ','XSHE') for stock in order_stocks] SHORTPERIOD = 12 LONGPERIOD = 26 SMOOTHPERIOD = 9 OBSERVATION = 200 for stock in context.yq_order_stocks: pricefilter = history_bars(stock,OBSERVATION,'1d','close',adjust_type='pre') macd, signal, hist = talib.MACD(pricefilter, SHORTPERIOD, LONGPERIOD, SMOOTHPERIOD) if macd[-1] - signal[-1] < 0: context.yq_order_stocks.remove(stock) def sink_stock(context, bar_dict): '''卖出本月未入选的股票,买入新入选的股票''' stock_to_sell = set(context.portfolio.positions) - set(context.yq_order_stocks) target_percent = 1 / len(context.yq_order_stocks) for stock in stock_to_sell: order_target_percent(stock, 0) for stock in context.yq_order_stocks: order_target_percent(stock, target_percent)
def price_in(context,bar_dict): '''用上一交易日的收盘价近似本月第一个交易日的开盘价,即成交价''' data0=[] for stock in context.yq_order_stocks: open0=history_bars(stock,1,'1d','close',adjust_type='pre') data0.append(open0) context.data0=data0 def stop_losing(context,bar_dict): '''止损''' for i in range(len(context.yq_order_stocks)): lossdata=history_bars(context.yq_order_stocks[i],1,'1d','close',adjust_type='pre') if lossdata < context.data0[i]*0.7: order_target_percent(context.yq_order_stocks[i], 0) def initialize(context): context.observation = 30 context.topM = 200 context.topN = 10 scheduler.run_monthly(find_order_stocks, tradingday=1, time_rule='before_trading') scheduler.run_monthly(sink_stock, tradingday=1, time_rule=market_open(hour=0)) scheduler.run_monthly(price_in,tradingday=1) scheduler.run_daily(stop_losing) def handle_data(context, bar_dict): pass
exec_strategy(initialize=initialize, handle_data=handle_data, config=config)
|