Notebook
In [108]:
import numpy as np
import pandas as pd
import statsmodels
import statsmodels.api as sm
from statsmodels.tsa.stattools import coint
import matplotlib.pyplot as plt
pd.get_option("display.max_rows")

SecurityViolationTraceback (most recent call last)
<ipython-input-108-15955e5b4e6c> in <module>()
      5 from statsmodels.tsa.stattools import coint
      6 import matplotlib.pyplot as plt
----> 7 pd.get_option("display.max_rows")

/build/src/qexec_repo/qexec/algo/safety.py in __getattribute__(self, attr)
    149                             mute_greylist=mute_greylist,
    150                             module=module,
--> 151                             module_wrapper=self,
    152                         )
    153                 finally:

/build/src/qexec_repo/qexec/algo/safety.py in check_attribute_access(full_path, whitelist, name_blacklist, caller_fr, module, module_wrapper, msg, mute_greylist)
     99             violations=[{'message': strip_qexec_module_path(error_message),
    100                          'lineno': caller_fr.f_lineno,
--> 101                          'extra': extra}])
    102 
    103 

SecurityViolation: 0002 Security Violation(s): Accessing pd.get_option raised an AttributeError. Did you mean to access pd.get_store instead?
In [89]:
def find_cointegrated_pairs(data):
    n = data.shape[1]
    score_matrix = np.zeros((n, n))
    pvalue_matrix = np.ones((n, n))
    keys = data.keys()
    pairs = []
    for i in range(n):
        for j in range(i+1, n):
            S1 = data[keys[i]]
            S2 = data[keys[j]]
            result = coint(S1, S2)
            score = result[0]
            pvalue = result[1]
            score_matrix[i, j] = score
            pvalue_matrix[i, j] = pvalue
            if pvalue < 0.05:
                pairs.append((keys[i], keys[j]))
    return score_matrix, pvalue_matrix, pairs
def zscore(series):
    return (series - series.mean()) / np.std(series)
# Heatmap to show the p-values of the cointegration test between each pair of
# stocks. Only show the value in the upper-diagonal of the heatmap
scores, pvalues, pairs = find_cointegrated_pairs(prices_df)
# import seaborn
# seaborn.heatmap(pvalues, xticklabels=symbol_list, yticklabels=symbol_list, cmap='RdYlGn_r' 
#                , mask = (pvalues >= 0.05))
print pairs
[]

ALLY versus AXP

In [90]:
S1_Name = 'EAD'  # For positive Z-score, go LONG this one
S2_Name = 'MCI' # For negative Z-score, go LONG this one
S1 = prices_df[S1_Name]  
S2 = prices_df[S2_Name]  
score, pvalue, _ = coint(S1, S2)
pvalue
Out[90]:
0.23216401072020026
In [91]:
ratio = S1/S2
print "Ratios Mean: ", ratio.mean(), "   Ratios StDev: ", ratio.std()
ratio = S1/S2
ratio.plot()
plt.axhline(ratio.mean(), color='black')
plt.title(["Ratio: ", S1_Name, S2_Name, "Start: ", startdate, "   End: ", enddate], size = 20);
plt.xlabel('Date', size = 20)
plt.ylabel('Ratio', size = 20)
plt.tick_params(axis='y', labelsize=15)
plt.tick_params(axis='x', labelsize=15)
Ratios Mean:  0.518470636886    Ratios StDev:  0.0188097226549
In [92]:
print "Ratios Mean: ", ratio.mean(), "   Ratios StDev: ", ratio.std()
zscores = zscore(ratio)
zscores.plot()
plt.axhline(zscore(ratio).mean(), color='black')
plt.axhline(2.0, color='red', linestyle='--')
plt.axhline(-2.0, color='red', linestyle='--')
plt.title(["Zscore: ", S1_Name, S2_Name, "Start: ", startdate, "   End: ", enddate], size = 20);
plt.xlabel('Date', size = 20)
plt.xlabel('Date', size = 20)
plt.ylabel('Zscore', size = 20)
plt.ylim(-3.0, 3.0)
plt.tick_params(axis='y', labelsize=15)
plt.tick_params(axis='x', labelsize=15)
Ratios Mean:  0.518470636886    Ratios StDev:  0.0188097226549
In [103]:
print "Ratios Mean: ", ratio.mean(), "   Ratios StDev: ", ratio.std()
results = pd.DataFrame()
results['Ratios'] = ratio
results['Zscores'] = zscores
results = results[['Ratios', 'Zscores']]
results = results.dropna(subset=['Zscores'])
print "S1_Name: ", S1_Name, "    S2_Name: ", S2_Name
print results[360:413]
Ratios Mean:  0.518470636886    Ratios StDev:  0.0188097226549
S1_Name:  EAD     S2_Name:  MCI
                             Ratios   Zscores
2019-03-11 00:00:00+00:00  0.490750 -1.475547
2019-03-12 00:00:00+00:00  0.489215 -1.557230
2019-03-13 00:00:00+00:00  0.488469 -1.596923
2019-03-14 00:00:00+00:00  0.484382 -1.814491
2019-03-15 00:00:00+00:00  0.476179 -2.251137
2019-03-18 00:00:00+00:00  0.484046 -1.832358
2019-03-19 00:00:00+00:00  0.491609 -1.429786
2019-03-20 00:00:00+00:00  0.499581 -1.005452
2019-03-21 00:00:00+00:00  0.497588 -1.111570
2019-03-22 00:00:00+00:00  0.504363 -0.750922
2019-03-25 00:00:00+00:00  0.504644 -0.735962
2019-03-26 00:00:00+00:00  0.507270 -0.596187
2019-03-27 00:00:00+00:00  0.515543 -0.155842
2019-03-28 00:00:00+00:00  0.516820 -0.087884
2019-03-29 00:00:00+00:00  0.513118 -0.284913
2019-04-01 00:00:00+00:00  0.514025 -0.236612
2019-04-02 00:00:00+00:00  0.519370  0.047849
2019-04-03 00:00:00+00:00  0.521018  0.135615
2019-04-04 00:00:00+00:00  0.522013  0.188554
2019-04-05 00:00:00+00:00  0.522013  0.188554
2019-04-08 00:00:00+00:00  0.522717  0.226011
2019-04-09 00:00:00+00:00  0.519357  0.047167
2019-04-10 00:00:00+00:00  0.520646  0.115815
2019-04-11 00:00:00+00:00  0.523604  0.273257
2019-04-12 00:00:00+00:00  0.521923  0.183772
2019-04-15 00:00:00+00:00  0.522269  0.202157
2019-04-16 00:00:00+00:00  0.521635  0.168456
2019-04-17 00:00:00+00:00  0.516601 -0.099529
2019-04-18 00:00:00+00:00  0.511962 -0.346426
2019-04-22 00:00:00+00:00  0.505830 -0.672839
2019-04-23 00:00:00+00:00  0.508091 -0.552468
2019-04-24 00:00:00+00:00  0.510965 -0.399518
2019-04-25 00:00:00+00:00  0.514461 -0.213409
2019-04-26 00:00:00+00:00  0.510339 -0.432808
2019-04-29 00:00:00+00:00  0.512255 -0.330854
2019-04-30 00:00:00+00:00  0.514101 -0.232602
2019-05-01 00:00:00+00:00  0.514408 -0.216247
2019-05-02 00:00:00+00:00  0.514404 -0.216457
2019-05-03 00:00:00+00:00  0.499752 -0.996347
2019-05-06 00:00:00+00:00  0.507853 -0.565139
2019-05-07 00:00:00+00:00  0.501622 -0.896829
2019-05-08 00:00:00+00:00  0.500997 -0.930101
2019-05-09 00:00:00+00:00  0.499750 -0.996463
2019-05-10 00:00:00+00:00  0.501938 -0.880034
2019-05-13 00:00:00+00:00  0.497500 -1.116235
2019-05-14 00:00:00+00:00  0.498137 -1.082347
2019-05-15 00:00:00+00:00  0.495674 -1.213448
2019-05-16 00:00:00+00:00  0.492897 -1.361254
2019-05-17 00:00:00+00:00  0.491662 -1.427008
2019-05-20 00:00:00+00:00  0.486239 -1.715666
2019-05-21 00:00:00+00:00  0.486906 -1.680126
2019-05-22 00:00:00+00:00  0.489336 -1.550804
2019-05-23 00:00:00+00:00  0.500623 -0.949979
In [ ]:
 
In [ ]: