I am creating a model for finding hidden states using the example of the sp500 price time series. my task is to find two states on the training and test set.
library(quantmod)
library(plotly)
library(depmixS4)
# train sample
getSymbols("^GSPC", from="2015-01-01", to="2019-01-30")
# test sample
getSymbols("^GSPC", from="2015-01-01", to="2019-01-30")
# Calculate differenced logarithmic returns using S&P500 Close prices
sp500_temp = diff(log(Cl(GSPC)))
sp500_returns = as.numeric(sp500_temp)
# Fit Hidden Markov Model to S&P500 returns, with two “states”
hidden_markov_model <- depmix(sp500_returns ~ 1, family = gaussian(), nstates = 2, data = data.frame(sp500_returns=sp500_returns))
model_fit <- fit(hidden_markov_model)
# Calculate posterior probabilities for each of the market states
posterior_probabilities <- posterior(model_fit)
q <- cbind(GSPC, posterior_probabilities$state)
In the variable q prices and their corresponding states.
further, I want to apply the results obtained in the training set to the test set and determine the states in it, but I don’t understand how to do this so that dont fitting model again
Perhaps I misunderstood the concept of hidden states of markov, so I ask for help in solving the problem