After reading this tutorial I am trying to replicate the results in R studio.
https://inovancetech.com/hmm-tutorial-1.html as someone new to R.
The code works until I try and plot the last set of graphs shown in "The probability of each regime separately" I am not familiar with ggplot and no code is provided for this and using the code below I get the error:
Error: Aesthetics must be either length 1 or the same as the data (994): x
Code from R Studio I am using below - any help on this appreciated thank you.
Date <- as.character(EURUSD1d[,1]) DateTS <- as.POSIXlt(Date, format = "%Y.%m.%d %H:%M:%S") #create date and time objects TSData <- data.frame(EURUSD1d[,2:5],row.names = DateTS) TSData <- as.xts(TSData) #build time series data ATRindicator <- ATR(TSData[,2:4],n=14) #calc the indicator ATR <- ATRindicator[,2] #take just the ATR LogReturns <- log(EURUSD1d$Close) - log(EURUSD1d$Open) #calc log returns ModelData <- data.frame(LogReturns,ATR) #create data frame for hmm ModelData <- ModelData[-c(1:14),] #remove data where indicators are being calculated colnames(ModelData) <- c("LogReturns","ATR") #name the columns set.seed(1) HMM <- depmix(list(LogReturns~1,ATR~1),data=ModelData,nstates=3,family=list(gaussian(),gaussian())) #We’re setting the LogReturns and ATR as our response variables, using the data frame we just built, want to set 3 different regimes, and setting the response distributions to be gaussian. HMMfit <- fit(HMM, verbose = FALSE) #fit our model to data set print(HMMfit) #compare log likelihood as well as AIC and BIC values to help choose the model print(HMMfit) #we can compare the log Likelihood as well as the AIC and BIC values to help choose our model summary(HMMfit) MMpost<-posterior(HMMfit) #find the posterior odds for each state over our data set head(HMMpost) #we can see that we now have the probability for each state for everyday as well as the highest probability class. # Creating graph library(ggplot2) theme_set(theme_minimal()) # source dataset head(HMMpost) # Basic line plot ggplot(data = HMMpost, aes(x = Date, y = S1))+ geom_line(color = "#00AFBB", size = 2)