<jupyter_start><jupyter_text>EWA-EWC Johansen cointegration exampleThe johansen package is used to find a cointegrating relation between the ETFs EWA and EWC.<jupyter_code>%matplotlib inline
import matplotlib.pyplot as plt
import pickle
from johansen import Johansen
import numpy as np
# Fitting dates.
start_date = '2016/02/01'
end_date = '2016/05/30'

prices_df = pickle.load(open('ewa_ewc_df.p', 'rb'))
prices_df = prices_df.sort_values(by='date').set_index('date')

x = prices_df.loc[start_date:end_date].as_matrix()
x_centered = x - np.mean(x, axis=0)

johansen = Johansen(x_centered, model=2, significance_level=0)
eigenvectors, r = johansen.johansen()

print "r values are: {}".format(r)

vec = eigenvectors[:, 0]
vec_min = np.min(np.abs(vec))
vec = vec / vec_min

print "The first cointegrating relation: {}".format(vec)
# Test dates.
start_date_test = start_date
end_date_test = '2016/08/11'

plt.title("Cointegrated series")

# In-sample plot.
portfolio_insample = np.dot(x, vec)
plt.plot(portfolio_insample, '-')

# Test plot. 
x_test = prices_df.loc[start_date_test:end_date_test].as_matrix()
portfolio_test = np.dot(x_test, vec)
plt.plot(portfolio_test, '--')

# In sample mean and std. 
in_sample = np.dot(x, vec)
mean = np.mean(in_sample)
std = np.std(in_sample)
print np.mean(in_sample), np.std(in_sample)

# Plot the mean and one std above and below it.
plt.axhline(y=mean - std, color='r', ls='--', alpha=.5)
plt.axhline(y=mean, color='r', ls='--', alpha=.5)
plt.axhline(y=mean + std, color='r', ls='--', alpha=.5)

plt.show()

# Plot of original price series.
prices_df.loc[start_date_test:end_date_test].plot(title="Original price series", rot=15)<jupyter_output>5.34485443902 0.473875870038
{'fraction_non_alphanumeric': 0.1472822910578609, 'fraction_numerical': 0.03389830508474576, 'mean_word_length': 5.584615384615384, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '458919', 'license': 'MIT', 'n_tokens_mistral': 723, 'n_tokens_neox': 663, 'n_words': 149, 'path': 'johansen/examples/ewa_ewc_cointegration_example.ipynb', 'repo_name': 'iisayoo/johansen', 'size': '1711'}