@Channelchan
2018-04-19T02:11:24.000000Z
字数 11468
阅读 51340
import pandas as pdUnion = pd.read_excel("Union.xlsx", index_col="trade_date")Intersection = pd.read_excel("Intersection.xlsx", index_col="trade_date")
Union
| 000001.SZ | 000002.SZ | 000008.SZ | 000009.SZ | 000012.SZ | 000024.SZ | 000027.SZ | 000039.SZ | 000046.SZ | 000060.SZ | ... | 601992.SH | 601997.SH | 601998.SH | 603000.SH | 603160.SH | 603288.SH | 603699.SH | 603858.SH | 603885.SH | 603993.SH | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| trade_date | |||||||||||||||||||||
| 20140103 | 1 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | ... | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 20140106 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | ... | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 20140107 | 0 | 1 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | ... | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 20140108 | 0 | 1 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | ... | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 20140109 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | ... | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
916 rows × 456 columns
from datetime import datetime, timedeltaimport numpy as npdef 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 signaldef get_daily_weight(data,period):data = data.fillna(0)weight_list = []for time_index, weight in data.iterrows():weight_result = (weight/weight.sum())weight_list.append(weight_result.to_dict())stock_df = pd.DataFrame(weight_list, index=data.index)if period>1:stock_df = pd.concat([pd.DataFrame(0,columns=stock_df.columns,index=list(range(1,period))),stock_df],axis=0)target = (pd.rolling_apply(stock_df, period, sum).dropna(how="all")/period).replace(0,np.nan)return target
Union_weight = get_daily_weight(change_columns_index(Union),period=30)Intersection_weight = get_daily_weight(change_columns_index(Intersection),period=30)Union_weight.head()
/home/xinger/anaconda3/envs/IIA/lib/python3.6/site-packages/ipykernel/__main__.py:25: FutureWarning: pd.rolling_apply is deprecated for DataFrame and will be removed in a future version, replace with
DataFrame.rolling(window=30,center=False).apply(func=<builtin_function_or_method>,args=<tuple>,kwargs=<dict>)
| 000001.XSHE | 000002.XSHE | 000008.XSHE | 000009.XSHE | 000012.XSHE | 000024.XSHE | 000027.XSHE | 000039.XSHE | 000046.XSHE | 000060.XSHE | ... | 601992.XSHG | 601997.XSHG | 601998.XSHG | 603000.XSHG | 603160.XSHG | 603288.XSHG | 603699.XSHG | 603858.XSHG | 603885.XSHG | 603993.XSHG |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2014-01-03 15:00:00 | 0.000412 | 0.000412 | NaN | NaN | NaN | 0.000412 | NaN | NaN | NaN | NaN | ... | 0.000412 | NaN | 0.000412 | NaN | NaN | NaN | NaN | NaN | NaN |
| 2014-01-06 15:00:00 | 0.000412 | 0.000823 | NaN | NaN | NaN | 0.000823 | NaN | NaN | NaN | NaN | ... | 0.000823 | NaN | 0.000412 | NaN | NaN | NaN | NaN | NaN | NaN |
| 2014-01-07 15:00:00 | 0.000412 | 0.001235 | NaN | NaN | 0.000412 | 0.001235 | NaN | NaN | NaN | NaN | ... | 0.001235 | NaN | 0.000412 | NaN | NaN | NaN | NaN | NaN | NaN |
| 2014-01-08 15:00:00 | 0.000412 | 0.001622 | NaN | NaN | 0.000799 | 0.001622 | NaN | NaN | NaN | NaN | ... | 0.001622 | NaN | 0.000412 | NaN | NaN | NaN | NaN | NaN | NaN |
| 2014-01-09 15:00:00 | 0.000412 | 0.002024 | NaN | NaN | 0.000799 | 0.002024 | NaN | NaN | NaN | NaN | ... | 0.002024 | NaN | 0.000412 | NaN | NaN | NaN | NaN | NaN | NaN |
5 rows × 456 columns
并集组合(不对冲)
import rqalphafrom rqalpha.api import *#读取文件位置def init(context):context.codes = Union_weightcontext.stocks = Nonecontext.pos_weight = 0.9scheduler.run_daily(find_pool)def find_pool(context, bar_dict):try:codes = context.codes.loc[context.now].dropna()context.stocks = codesexcept:context.stocks = Nonedef handle_bar(context, bar_dict):buy(context, bar_dict)def buy(context, bar_dict):pool = context.stocksif pool is not None:for ins, percentage in pool.items():order_target_percent(ins, percentage*context.pos_weight)for ins in context.portfolio.positions:if ins not in context.stocks:order_target_percent(ins, 0)config = {"base": {"start_date": "2014-01-03","end_date": "2018-01-31","accounts": {'stock':10000000},"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)
WARNING: better_exceptions will only inspect code from the command line
when using: `python -m better_exceptions'. Otherwise, only code
loaded from files will be inspected!

{'sys_analyser': {'benchmark_portfolio': cash market_value static_unit_net_value total_value \
date
2014-01-03 745.3 9999254.70 1.000 10000000.00
2014-01-06 745.3 9771663.60 1.000 9772408.90
2014-01-07 745.3 9768870.00 0.977 9769615.30
2014-01-08 745.3 9785937.15 0.977 9786682.45
2014-01-09 745.3 9699990.30 0.979 9700735.60
... ... ... ... ...
unit_net_value units
date
2014-01-03 1.000000 10000000.0
2014-01-06 0.977241 10000000.0
2014-01-07 0.976962 10000000.0
2014-01-08 0.978668 10000000.0
2014-01-09 0.970074 10000000.0
... ... ...
[991 rows x 6 columns],
'portfolio': cash market_value static_unit_net_value total_value \
date
2014-01-03 9736148.000 2.634470e+05 1.000 9.999595e+06
2014-01-06 9429722.000 5.606790e+05 1.000 9.990401e+06
2014-01-07 9125957.000 8.627950e+05 0.999 9.988752e+06
2014-01-08 8829838.000 1.151396e+06 0.999 9.981234e+06
2014-01-09 8517260.115 1.455680e+06 0.998 9.972940e+06
... ... ... ... ...
unit_net_value units
date
2014-01-03 0.999960 10000000.0
2014-01-06 0.999040 10000000.0
2014-01-07 0.998875 10000000.0
2014-01-08 0.998123 10000000.0
2014-01-09 0.997294 10000000.0
... ... ...
[991 rows x 6 columns],
'stock_account': cash dividend_receivable market_value total_value \
date
2014-01-03 9736148.000 0.0 2.634470e+05 9.999595e+06
2014-01-06 9429722.000 0.0 5.606790e+05 9.990401e+06
2014-01-07 9125957.000 0.0 8.627950e+05 9.988752e+06
2014-01-08 8829838.000 0.0 1.151396e+06 9.981234e+06
2014-01-09 8517260.115 0.0 1.455680e+06 9.972940e+06
... ... ... ... ...
transaction_cost
date
2014-01-03 405.000
2014-01-06 415.000
2014-01-07 410.000
2014-01-08 425.000
2014-01-09 440.885
... ...
[991 rows x 5 columns],
'stock_positions': avg_price last_price market_value order_book_id quantity symbol
date
2014-01-03 11.930 11.93 3579.0 000001.XSHE 300.0 平安银行
2014-01-03 7.840 7.84 3136.0 000002.XSHE 400.0 万科A
2014-01-03 20.190 20.19 2019.0 000024.XSHE 100.0 招商地产
2014-01-03 14.070 14.07 2814.0 000063.XSHE 200.0 中兴通讯
2014-01-03 5.150 5.15 3605.0 000069.XSHE 700.0 华侨城A
... ... ... ... ... ... ...
[159399 rows x 6 columns],
'summary': {'STOCK': 10000000.0,
'alpha': 0.060999999999999999,
'annualized_returns': 0.23100000000000001,
'benchmark': '000300.XSHG',
'benchmark_annualized_returns': 0.17000000000000001,
'benchmark_total_returns': 0.89300000000000002,
'beta': 0.94699999999999995,
'cash': 2080687.6529999999,
'downside_risk': 0.035999999999999997,
'end_date': '2018-01-22',
'information_ratio': 0.95199999999999996,
'max_drawdown': 0.40799999999999997,
'run_type': 'BACKTEST',
'sharpe': 0.81999999999999995,
'sortino': 5.4530000000000003,
'start_date': '2014-01-03',
'strategy_file': 'strategy.py',
'strategy_name': 'strategy',
'total_returns': 1.323,
'total_value': 23225390.339000002,
'tracking_error': 0.056000000000000001,
'unit_net_value': 2.323,
'units': 10000000.0,
'volatility': 0.23899999999999999},
'trades': commission exec_id last_price last_quantity \
datetime
2014-01-03 15:00:00 5.0000 1516788432 11.93 300.0
2014-01-03 15:00:00 5.0000 1516788433 7.84 400.0
2014-01-03 15:00:00 5.0000 1516788434 20.19 100.0
2014-01-03 15:00:00 5.0000 1516788435 14.07 200.0
2014-01-03 15:00:00 5.0000 1516788436 5.15 700.0
... ... ... ... ...
order_book_id order_id position_effect side symbol \
datetime
2014-01-03 15:00:00 000001.XSHE 1516788430 None BUY 平安银行
2014-01-03 15:00:00 000002.XSHE 1516788431 None BUY 万科A
2014-01-03 15:00:00 000024.XSHE 1516788432 None BUY 招商地产
2014-01-03 15:00:00 000063.XSHE 1516788433 None BUY 中兴通讯
2014-01-03 15:00:00 000069.XSHE 1516788434 None BUY 华侨城A
... ... ... ... ... ...
tax trading_datetime transaction_cost
datetime
2014-01-03 15:00:00 0.000 2014-01-03 15:00:00 5.0000
2014-01-03 15:00:00 0.000 2014-01-03 15:00:00 5.0000
2014-01-03 15:00:00 0.000 2014-01-03 15:00:00 5.0000
2014-01-03 15:00:00 0.000 2014-01-03 15:00:00 5.0000
2014-01-03 15:00:00 0.000 2014-01-03 15:00:00 5.0000
... ... ... ...
[90887 rows x 12 columns]}}
交集组合(不对冲)
import rqalphafrom rqalpha.api import *#读取文件位置def init(context):context.codes = Intersection_weightcontext.stocks = Nonecontext.pos_weight = 0.9scheduler.run_daily(find_pool)def find_pool(context, bar_dict):try:codes = context.codes.loc[context.now].dropna()context.stocks = codesexcept:context.stocks = Nonedef handle_bar(context, bar_dict):buy(context, bar_dict)def buy(context, bar_dict):pool = context.stocksif pool is not None:for ins, percentage in pool.items():order_target_percent(ins, percentage*context.pos_weight)for ins in context.portfolio.positions:if ins not in context.stocks:order_target_percent(ins, 0)config = {"base": {"start_date": "2014-01-03","end_date": "2018-01-31","accounts": {'stock':10000000},"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)

{'sys_analyser': {'benchmark_portfolio': cash market_value static_unit_net_value total_value \
date
2014-01-03 745.3 9999254.70 1.000 10000000.00
2014-01-06 745.3 9771663.60 1.000 9772408.90
2014-01-07 745.3 9768870.00 0.977 9769615.30
2014-01-08 745.3 9785937.15 0.977 9786682.45
2014-01-09 745.3 9699990.30 0.979 9700735.60
... ... ... ... ...
unit_net_value units
date
2014-01-03 1.000000 10000000.0
2014-01-06 0.977241 10000000.0
2014-01-07 0.976962 10000000.0
2014-01-08 0.978668 10000000.0
2014-01-09 0.970074 10000000.0
... ... ...
[991 rows x 6 columns],
'portfolio': cash market_value static_unit_net_value total_value \
date
2014-01-03 9706814.639 292951.0 1.000 9.999766e+06
2014-01-06 9400250.633 588600.0 1.000 9.988851e+06
2014-01-07 9097252.082 888252.0 0.999 9.985504e+06
2014-01-08 8790795.296 1184237.0 0.999 9.975032e+06
2014-01-09 8489710.813 1481302.0 0.998 9.971013e+06
... ... ... ... ...
unit_net_value units
date
2014-01-03 0.999977 10000000.0
2014-01-06 0.998885 10000000.0
2014-01-07 0.998550 10000000.0
2014-01-08 0.997503 10000000.0
2014-01-09 0.997101 10000000.0
... ... ...
[991 rows x 6 columns],
'stock_account': cash dividend_receivable market_value total_value \
date
2014-01-03 9706814.639 0.0 292951.0 9.999766e+06
2014-01-06 9400250.633 0.0 588600.0 9.988851e+06
2014-01-07 9097252.082 0.0 888252.0 9.985504e+06
2014-01-08 8790795.296 0.0 1184237.0 9.975032e+06
2014-01-09 8489710.813 0.0 1481302.0 9.971013e+06
... ... ... ... ...
transaction_cost
date
2014-01-03 234.361
2014-01-06 254.006
2014-01-07 259.550
2014-01-08 294.786
2014-01-09 287.483
... ...
[991 rows x 5 columns],
'stock_positions': avg_price last_price market_value order_book_id quantity symbol
date
2014-01-03 14.070 14.07 12663.0 000063.XSHE 900.0 中兴通讯
2014-01-03 6.920 6.92 12456.0 000961.XSHE 1800.0 中南建设
2014-01-03 6.820 6.82 12958.0 000983.XSHE 1900.0 西山煤电
2014-01-03 4.980 4.98 12948.0 600011.XSHG 2600.0 华能国际
2014-01-03 4.010 4.01 12832.0 600019.XSHG 3200.0 宝钢股份
... ... ... ... ... ... ...
[63607 rows x 6 columns],
'summary': {'STOCK': 10000000.0,
'alpha': 0.112,
'annualized_returns': 0.29199999999999998,
'benchmark': '000300.XSHG',
'benchmark_annualized_returns': 0.17000000000000001,
'benchmark_total_returns': 0.89300000000000002,
'beta': 0.88800000000000001,
'cash': 2606790.0210000002,
'downside_risk': 0.047,
'end_date': '2018-01-22',
'information_ratio': 1.242,
'max_drawdown': 0.34200000000000003,
'run_type': 'BACKTEST',
'sharpe': 1.0369999999999999,
'sortino': 5.077,
'start_date': '2014-01-03',
'strategy_file': 'strategy.py',
'strategy_name': 'strategy',
'total_returns': 1.831,
'total_value': 28310743.421,
'tracking_error': 0.076999999999999999,
'unit_net_value': 2.831,
'units': 10000000.0,
'volatility': 0.23000000000000001},
'trades': commission exec_id last_price last_quantity \
datetime
2014-01-03 15:00:00 10.1304 1516792677 14.07 900.0
2014-01-03 15:00:00 9.9648 1516792678 6.92 1800.0
2014-01-03 15:00:00 10.3664 1516792679 6.82 1900.0
2014-01-03 15:00:00 10.3584 1516792680 4.98 2600.0
2014-01-03 15:00:00 10.2656 1516792681 4.01 3200.0
... ... ... ... ...
order_book_id order_id position_effect side symbol \
datetime
2014-01-03 15:00:00 000063.XSHE 1516792676 None BUY 中兴通讯
2014-01-03 15:00:00 000961.XSHE 1516792677 None BUY 中南建设
2014-01-03 15:00:00 000983.XSHE 1516792678 None BUY 西山煤电
2014-01-03 15:00:00 600011.XSHG 1516792679 None BUY 华能国际
2014-01-03 15:00:00 600019.XSHG 1516792680 None BUY 宝钢股份
... ... ... ... ... ...
tax trading_datetime transaction_cost
datetime
2014-01-03 15:00:00 0.000 2014-01-03 15:00:00 10.1304
2014-01-03 15:00:00 0.000 2014-01-03 15:00:00 9.9648
2014-01-03 15:00:00 0.000 2014-01-03 15:00:00 10.3664
2014-01-03 15:00:00 0.000 2014-01-03 15:00:00 10.3584
2014-01-03 15:00:00 0.000 2014-01-03 15:00:00 10.2656
... ... ... ...
[40187 rows x 12 columns]}}