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
| import numpy as np import pandas as pd from jqdata import *
instruments_code_bank = get_industry_stocks('I64')[0:15] prices_temp = pd.DataFrame() start_date = '2020-01-01' end_date = '2022-04-29' for c in instruments_code_bank: c_daily = get_price(c, start_date, end_date) c_daily['code'] = c prices_temp = pd.concat([prices_temp, c_daily])
prices_temp_code_close = prices_temp[['code', 'close']]
mode_num = np.argmax(np.bincount([len(i) for i in [prices_temp_code_close[prices_temp_code_close.code == c] for c in instruments_code_bank]]))
price_dict_all = dict(list(prices_temp_code_close.groupby('code')['close']))
price_dict = dict(filter(lambda x: len(x[1]) == mode_num, price_dict_all.items())) instruments_code = list(price_dict.keys())
import matplotlib.pyplot as plt import statsmodels.api as sm import seaborn as sns
def get_pearson_r(price_dict): n = len(price_dict) keys = list(price_dict.keys()) r_matrix = np.ones((n, n)) for i in range(n): stock1 = price_dict[keys[i]] for j in range(i+1, n): stock2 = price_dict[keys[j]] r = stock1.corr(stock2) r_matrix[i, j] = r return r_matrix
def find_cointegrated_pairs(price_dict): n = len(price_dict) pvalue_matrix = np.ones((n, n)) keys = list(price_dict.keys()) mode_num = np.argmax(np.bincount([len(i) for i in list(price_dict.values())])) pairs = [] for i in range(n): stock1 = price_dict[keys[i]] if len(stock1) != mode_num: continue for j in range(i+1, n): stock2 = price_dict[keys[j]] if len(stock2) != mode_num: continue result = sm.tsa.stattools.coint(stock1, stock2) pvalue = result[1] pvalue_matrix[i, j] = pvalue if pvalue < 0.05: pairs.append((keys[i], keys[j], pvalue)) return pvalue_matrix, pairs
pvalues, pairs = find_cointegrated_pairs(price_dict) pairs_df = pd.DataFrame(pairs, index=range(0, len(pairs)), columns=list(['comp1', 'comp2', 'pvalue']))
pairs_df = pairs_df.sort_values(by='pvalue') pairs_df
plt.rcParams['figure.figsize'] = [15, 8] sns.heatmap(1-pvalues, xticklabels=instruments_code, yticklabels=instruments_code, cmap='RdYlGn_r', mask=(pvalues == 1))
company_choose = [pairs_df.iloc[0].comp1, pairs_df.iloc[0].comp2] print(company_choose) x = price_dict[company_choose[0]] y = price_dict[company_choose[1]] x = np.log(x) X = sm.add_constant(x) y = np.log(y) result = (sm.OLS(y, X)).fit() result.summary()
import matplotlib.pyplot as plt p1 = get_price('000676.XSHE', start_date, end_date, fields='close')
st = np.log(y) - np.log(x) * 1.3584 fig, ax = plt.subplots(figsize=(8,6)) ax.plot(x, y, 'o', label="data") ax.plot(x, result.fittedvalues, 'r', label="OLS") ax.legend(loc='best')
open_num = 1.5 close_num = 0.5
position = 0 capital = 1000000 fee_rate = 0.0005
trade_log = []
for i in range(len(resid)): if position == 0: if resid[i] > mean + open_num * std: position = -1 x_price = x[i] * (1 + fee_rate) y_price = y[i] * (1 - fee_rate) x_amount = capital / 2 / x_price y_amount = capital / 2 / y_price trade_log.append([i, 'Open', -1, x_price, y_price, x_amount, y_amount]) elif resid[i] < mean - open_num * std: position = 1 x_price = x[i] * (1 - fee_rate) y_price = y[i] * (1 + fee_rate) x_amount = capital / 2 / x_price y_amount = capital / 2 / y_price trade_log.append([i, 'Open', 1, x_price, y_price, x_amount, y_amount]) elif position == -1: if resid[i] < mean + close_num * std: position = 0 x_price = x[i] * (1 - fee_rate) y_price = y[i] * (1 + fee_rate) trade_log.append([i, 'Close', 0, x_price, y_price]) elif position == 1: if resid[i] > mean - close_num * std: position = 0 x_price = x[i] * (1 + fee_rate) y_price = y[i] * (1 - fee_rate) trade_log.append([i, 'Close', 0, x_price, y_price])
trade_log = pd.DataFrame(trade_log, columns=['Date', 'Operation', 'Position', 'x Price', 'y Price', 'x Quantity', 'y Quantity']) trade_log['Profit'] = 0 trade_log['Cumulative Profit'] = 0 for i in range(1, len(trade_log)): if trade_log.loc[i, 'Operation'] == 'Close': trade_log.loc[i, 'Profit'] = (trade_log.loc[i-1, 'x Price'] - trade_log.loc[i, 'x Price']) * trade_log.loc[i-1, 'x Quantity'] + (trade_log.loc[i, 'y Price'] - trade_log.loc[i-1, 'y Price']) * trade_log.loc[i-1, 'y Quantity'] trade_log.loc[i, 'Cumulative Profit'] = trade_log.loc[i-1, 'Cumulative Profit'] + trade_log.loc[i, 'Profit'] else: trade_log.loc[i, 'Cumulative Profit'] = trade_log.loc[i-1, 'Cumulative Profit']
print(trade_log)
plt.plot(trade_log['Date'], trade_log['Cumulative Profit']) plt.xlabel('Date') plt.ylabel('Cumulative Return') plt.title('Market Neutral Strategy') plt.show()
|