[关闭]
@Channelchan 2018-04-19T10:11:24.000000Z 字数 11468 阅读 51126

附:交并集投资组合回测结果

  1. import pandas as pd
  2. Union = pd.read_excel("Union.xlsx", index_col="trade_date")
  3. Intersection = pd.read_excel("Intersection.xlsx", index_col="trade_date")
  1. 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

  1. from datetime import datetime, timedelta
  2. import numpy as np
  3. def change_columns_index(signal):
  4. new_names = {}
  5. for c in signal.columns:
  6. if c.endswith('SZ'):
  7. new_names[c] = c.replace('SZ', 'XSHE')
  8. elif c.endswith('SH'):
  9. new_names[c] = c.replace('SH', 'XSHG')
  10. signal = signal.rename_axis(new_names, axis=1)
  11. signal.index = pd.Index(map(lambda x: datetime.strptime(str(x),"%Y%m%d") , signal.index))
  12. signal.index = pd.Index(map(lambda x: x+timedelta(hours=15) , signal.index))
  13. return signal
  14. def get_daily_weight(data,period):
  15. data = data.fillna(0)
  16. weight_list = []
  17. for time_index, weight in data.iterrows():
  18. weight_result = (weight/weight.sum())
  19. weight_list.append(weight_result.to_dict())
  20. stock_df = pd.DataFrame(weight_list, index=data.index)
  21. if period>1:
  22. stock_df = pd.concat([pd.DataFrame(0,columns=stock_df.columns,index=list(range(1,period))),stock_df],axis=0)
  23. target = (pd.rolling_apply(stock_df, period, sum).dropna(how="all")/period).replace(0,np.nan)
  24. return target
  1. Union_weight = get_daily_weight(change_columns_index(Union),period=30)
  2. Intersection_weight = get_daily_weight(change_columns_index(Intersection),period=30)
  3. 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

并集组合(不对冲)

  1. import rqalpha
  2. from rqalpha.api import *
  3. #读取文件位置
  4. def init(context):
  5. context.codes = Union_weight
  6. context.stocks = None
  7. context.pos_weight = 0.9
  8. scheduler.run_daily(find_pool)
  9. def find_pool(context, bar_dict):
  10. try:
  11. codes = context.codes.loc[context.now].dropna()
  12. context.stocks = codes
  13. except:
  14. context.stocks = None
  15. def handle_bar(context, bar_dict):
  16. buy(context, bar_dict)
  17. def buy(context, bar_dict):
  18. pool = context.stocks
  19. if pool is not None:
  20. for ins, percentage in pool.items():
  21. order_target_percent(ins, percentage*context.pos_weight)
  22. for ins in context.portfolio.positions:
  23. if ins not in context.stocks:
  24. order_target_percent(ins, 0)
  25. config = {
  26. "base": {
  27. "start_date": "2014-01-03",
  28. "end_date": "2018-01-31",
  29. "accounts": {'stock':10000000},
  30. "benchmark": "000300.XSHG"
  31. },
  32. "extra": {
  33. "log_level": "error",
  34. },
  35. "mod": {
  36. "sys_analyser": {
  37. #"enabled": True,
  38. "plot": True
  39. }
  40. }
  41. }
  42. 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!

output_5_1.png-85.3kB

{'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]}}

交集组合(不对冲)

  1. import rqalpha
  2. from rqalpha.api import *
  3. #读取文件位置
  4. def init(context):
  5. context.codes = Intersection_weight
  6. context.stocks = None
  7. context.pos_weight = 0.9
  8. scheduler.run_daily(find_pool)
  9. def find_pool(context, bar_dict):
  10. try:
  11. codes = context.codes.loc[context.now].dropna()
  12. context.stocks = codes
  13. except:
  14. context.stocks = None
  15. def handle_bar(context, bar_dict):
  16. buy(context, bar_dict)
  17. def buy(context, bar_dict):
  18. pool = context.stocks
  19. if pool is not None:
  20. for ins, percentage in pool.items():
  21. order_target_percent(ins, percentage*context.pos_weight)
  22. for ins in context.portfolio.positions:
  23. if ins not in context.stocks:
  24. order_target_percent(ins, 0)
  25. config = {
  26. "base": {
  27. "start_date": "2014-01-03",
  28. "end_date": "2018-01-31",
  29. "accounts": {'stock':10000000},
  30. "benchmark": "000300.XSHG"
  31. },
  32. "extra": {
  33. "log_level": "error",
  34. },
  35. "mod": {
  36. "sys_analyser": {
  37. #"enabled": True,
  38. "plot": True
  39. },
  40. }
  41. }
  42. rqalpha.run_func(init=init, handle_bar=handle_bar, config=config)

output_7_0.png-85.9kB

{'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]}}
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注