Hi guys ,
I'm a beginner in HMM ...I've read that It makes a Detection Regime. First of all , what is a detection regime meaning ?
I've read that It prevents my algorithm from high volatility and thus It doesn't trade on it . So it is a way to handle better Money Management.
import pandas as pd
import pandas_datareader as web
data = web.DataReader("^GSPC","yahoo",start = "2004-11-19",end = "2018-11-19")
data.head()
rets = data['Close'].pct_change()[1:]
volume = data['Volume'][1:]
dates = data.index[1:]
close_v = volume
from hmmlearn import hmm
import matplotlib.pyplot as plt
model = hmm.GaussianHMM(n_components=2, covariance_type="full", n_iter=1000)
import numpy as np
X = np.column_stack([rets, np.log(volume)])
model.fit(X)
hidden_states = model.predict(X)
from matplotlib import cm
def plot_in_sample_hidden_states(hmm_model, df):
"""
Plot the adjusted closing prices masked by
the in-sample hidden states as a mechanism
to understand the market regimes.
"""
# Predict the hidden states array
hidden_states = hmm_model.predict(X)
# Create the correctly formatted plot
fig, axs = plt.subplots(
hmm_model.n_components,
sharex=True, sharey=True
)
colours = cm.rainbow(
np.linspace(0, 1, hmm_model.n_components)
)
for i, (ax, colour) in enumerate(zip(axs, colours)):
mask = hidden_states == i
ax.plot_date(
df.index[mask],
df["close_price"][mask],
".", linestyle='none',
c=colour
)
ax.set_title("Hidden State #%s" % i)
ax.grid(True)
plt.show()
plot_in_sample_hidden_states(model, data)
I've taken the code of this publication :
I got an error in the last line as following : "Boolean index has wrong length: 3524 instead of 3525"
Also , I'm working on Jupyter not QUANTOPIAN
Regards
Iheb