├── data ├── DJIRM.RData ├── SP500RM.RData └── DJIRealizedMeasures.rda ├── tests ├── testthat.R └── testthat │ └── test_HARModel.R ├── src ├── HARDataCreationC.h ├── fastlmcoef.cpp ├── Makevars ├── Makevars.win ├── HARSimC.cpp ├── HarDatacreationC.cpp └── RcppExports.cpp ├── README.md ├── man ├── SP500RM.Rd ├── DJIRM.Rd ├── HARModel-package.Rd ├── DJIRealizedMeasures.Rd ├── uncondmean.Rd ├── SandwichNeweyWest.Rd ├── HARDataCreationC.Rd ├── HARsimulate.Rd ├── HARSim-class.Rd ├── HARModel-class.Rd ├── HARForecast-class.Rd ├── HARestimate.Rd └── HARforecast.Rd ├── R ├── RcppExports.R ├── HARSimulate.R ├── ClassMethods.R ├── HARestimate.R └── HARForecast.R ├── DESCRIPTION ├── NAMESPACE ├── ChangeLog └── Using HARModel.R /data/DJIRM.RData: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/emilsjoerup/HARModel/HEAD/data/DJIRM.RData -------------------------------------------------------------------------------- /data/SP500RM.RData: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/emilsjoerup/HARModel/HEAD/data/SP500RM.RData -------------------------------------------------------------------------------- /tests/testthat.R: -------------------------------------------------------------------------------- 1 | library(testthat) 2 | library(HARModel) 3 | 4 | test_check("HARModel") 5 | 6 | 7 | -------------------------------------------------------------------------------- /data/DJIRealizedMeasures.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/emilsjoerup/HARModel/HEAD/data/DJIRealizedMeasures.rda -------------------------------------------------------------------------------- /src/HARDataCreationC.h: -------------------------------------------------------------------------------- 1 | #ifndef HARDataCreationC_H 2 | #define HARDataCreationC_H 3 | arma::mat HARDataCreationC(arma::vec vRealizedMeasure , arma::vec vLags, int h); 4 | #endif 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HARModel 2 | 3 | An implementation of the Heterogeneous AutoRegressive model from Corsi(2009) 4 | 5 | If you find any bugs or think improvements can be made, please contact me at: 6 | 7 | emilsjoerup@live.dk 8 | 9 | -------------------------------------------------------------------------------- /src/fastlmcoef.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace arma; 4 | //[[Rcpp::export]] 5 | 6 | 7 | 8 | 9 | arma::vec fastLMcoef(arma::mat X, arma::colvec y){ 10 | arma::vec coef = arma::solve(X, y); 11 | return(coef); 12 | //only returns the coefficients, taken from Dirk Eddelbuettel 13 | } 14 | -------------------------------------------------------------------------------- /man/SP500RM.Rd: -------------------------------------------------------------------------------- 1 | \name{SP500RM} 2 | \alias{SP500RM} 3 | \docType{data} 4 | \title{ 5 | SP500 Realized Measures 6 | } 7 | \description{ 8 | Realized measures from the SP500 index from April 1997 to August 2013. 9 | } 10 | 11 | \format{ 12 | A large \code{xts} object. 13 | } 14 | 15 | \source{ 16 | http://public.econ.duke.edu/~ap172/code.html 17 | } 18 | \references{ 19 | Bollerslev, T., A. J. Patton, and R. Quaedvlieg, 2016, 20 | Exploiting the Errors: A Simple Approach for Improved Volatility Forecasting, 21 | Journal of Econometrics, 192, 1-18. 22 | } 23 | 24 | \keyword{datasets} 25 | -------------------------------------------------------------------------------- /R/RcppExports.R: -------------------------------------------------------------------------------- 1 | # Generated by using Rcpp::compileAttributes() -> do not edit by hand 2 | # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 3 | 4 | HARDataCreationC <- function(vRealizedMeasure, vPeriods, h = 1L) { 5 | .Call(`_HARModel_HARDataCreationC`, vRealizedMeasure, vPeriods, h) 6 | } 7 | 8 | HARMatCombine <- function(mA, mB) { 9 | .Call(`_HARModel_HARMatCombine`, mA, mB) 10 | } 11 | 12 | HARSimC <- function(iLength, vLags, dConst, coef, dSigma) { 13 | .Call(`_HARModel_HARSimC`, iLength, vLags, dConst, coef, dSigma) 14 | } 15 | 16 | fastLMcoef <- function(X, y) { 17 | .Call(`_HARModel_fastLMcoef`, X, y) 18 | } 19 | 20 | -------------------------------------------------------------------------------- /man/DJIRM.Rd: -------------------------------------------------------------------------------- 1 | \name{DJIRM} 2 | \alias{DJIRM} 3 | \docType{data} 4 | \title{ 5 | Dow Jones Realized Measures 6 | } 7 | \description{ 8 | Realized measures for the Dow Jones Industial index from 2001 to september 2018 9 | } 10 | 11 | \format{ 12 | A large \code{xts} object 13 | } 14 | \details{ 15 | See the website of the data set for details. 16 | } 17 | \source{ 18 | https://realized.oxford-man.ox.ac.uk/data 19 | } 20 | \references{ 21 | Heber, Gerd, Asger Lunde, Neil Shephard and Kevin Sheppard (2009) "Oxford-Man Institute's realized library", 22 | Oxford-Man Institute, University of Oxford. 23 | Library version: 0.3 24 | } 25 | \keyword{datasets} 26 | -------------------------------------------------------------------------------- /man/HARModel-package.Rd: -------------------------------------------------------------------------------- 1 | \name{HARModel-package} 2 | \alias{HARModel-package} 3 | \alias{HARModel} 4 | \docType{package} 5 | \title{ 6 | \packageTitle{HARModel} 7 | } 8 | \description{ 9 | \packageDescription{HARModel} 10 | } 11 | \details{ 12 | The DESCRIPTION file: 13 | \packageDESCRIPTION{HARModel} 14 | \packageIndices{HARModel} 15 | } 16 | \author{ 17 | \packageAuthor{HARModel} 18 | 19 | Maintainer: \packageMaintainer{HARModel} 20 | } 21 | \references{ 22 | Corsi, F. 2009, A Simple Approximate Long-Memory Model 23 | of Realized Volatility, \emph{Journal of Financial Econometrics}, 174--196 .\cr 24 | } 25 | \keyword{ Heterogeneous Autoregressive model } 26 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: HARModel 2 | Type: Package 3 | Title: Heterogeneous Autoregressive Models 4 | Version: 1.0 5 | Date: 2019-08-30 6 | Author: Emil Sjoerup 7 | Maintainer: Emil Sjoerup 8 | Description: Estimation, simulation, and forecasting using the HAR model from Corsi(2009) and extensions. 9 | BugReports: https://github.com/emilsjoerup/HARModel/issues 10 | URL: https://github.com/emilsjoerup/HARModel 11 | License: GPL-3 12 | Imports: Rcpp (>= 0.12.17) , xts, zoo, sandwich 13 | LinkingTo: Rcpp, RcppArmadillo 14 | NeedsCompilation: yes 15 | Depends: R (>= 2.10), methods 16 | Suggests: testthat 17 | Packaged: 2019-08-31 11:11:12 UTC; emils 18 | -------------------------------------------------------------------------------- /src/Makevars: -------------------------------------------------------------------------------- 1 | 2 | ## With R 3.1.0 or later, you can uncomment the following line to tell R to 3 | ## enable compilation with C++11 (where available) 4 | ## 5 | ## Also, OpenMP support in Armadillo prefers C++11 support. However, for wider 6 | ## availability of the package we do not yet enforce this here. It is however 7 | ## recommended for client packages to set it. 8 | ## 9 | ## And with R 3.4.0, and RcppArmadillo 0.7.960.*, we turn C++11 on as OpenMP 10 | ## support within Armadillo prefers / requires it 11 | CXX_STD = CXX11 12 | 13 | PKG_CXXFLAGS = $(SHLIB_OPENMP_CXXFLAGS) 14 | PKG_LIBS = $(SHLIB_OPENMP_CXXFLAGS) $(LAPACK_LIBS) $(BLAS_LIBS) $(FLIBS) 15 | RcppArmadilloCxxFlags = $(ARMA_NO_DEBUG) 16 | -------------------------------------------------------------------------------- /src/Makevars.win: -------------------------------------------------------------------------------- 1 | 2 | ## With R 3.1.0 or later, you can uncomment the following line to tell R to 3 | ## enable compilation with C++11 (where available) 4 | ## 5 | ## Also, OpenMP support in Armadillo prefers C++11 support. However, for wider 6 | ## availability of the package we do not yet enforce this here. It is however 7 | ## recommended for client packages to set it. 8 | ## 9 | ## And with R 3.4.0, and RcppArmadillo 0.7.960.*, we turn C++11 on as OpenMP 10 | ## support within Armadillo prefers / requires it 11 | CXX_STD = CXX11 12 | 13 | PKG_CXXFLAGS = $(SHLIB_OPENMP_CXXFLAGS) 14 | PKG_LIBS = $(LAPACK_LIBS) $(BLAS_LIBS) $(FLIBS) $(SHLIB_OPENMP_CXXFLAGS) 15 | RcppArmadilloCxxFlags = $(ARMA_NO_DEBUG) 16 | -------------------------------------------------------------------------------- /man/DJIRealizedMeasures.Rd: -------------------------------------------------------------------------------- 1 | \name{DJIRealizedMeasures} 2 | \alias{DJIRealizedMeasures} 3 | \docType{data} 4 | \title{ 5 | Dow Jones Realized Measures 6 | } 7 | \description{ 8 | Realized measures 9 | } 10 | 11 | \format{ 12 | A large \code{xts} object containing trading data for the Dow Jones Industial index from 2001 to september 2018 13 | } 14 | \details{ 15 | See the website of the data set for details. 16 | } 17 | \source{ 18 | https://realized.oxford-man.ox.ac.uk/data 19 | } 20 | \references{ 21 | Heber, Gerd, Asger Lunde, Neil Shephard and Kevin Sheppard (2009) "Oxford-Man Institute's realized library", 22 | Oxford-Man Institute, University of Oxford. 23 | Library version: 0.3 24 | \url{https://realized.oxford-man.ox.ac.uk/data} 25 | } 26 | \keyword{datasets} 27 | -------------------------------------------------------------------------------- /src/HARSimC.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "HARDataCreationC.h" 3 | using namespace arma; 4 | 5 | 6 | // [[Rcpp::export]] 7 | 8 | arma::mat HARSimC(int iLength, arma::vec vLags, double dConst , arma::vec coef, double dSigma){ 9 | 10 | int iMaxLags = max(vLags); 11 | int iLags = vLags.size(); 12 | double uncondmean = dConst/(1-sum(coef)); 13 | arma::vec vEps = arma::randn(iLength) * dSigma; 14 | arma::mat mSim(iLength + 2*iMaxLags , iLags+1); mSim.fill(uncondmean); 15 | 16 | for(int i=iMaxLags+1; i 2 | 3 | using namespace arma; 4 | 5 | //[[Rcpp::export]] 6 | arma::mat HARDataCreationC(arma::vec vRealizedMeasure , arma::vec vPeriods, int h = 1){ 7 | int iT = vRealizedMeasure.size(); 8 | int iLags = vPeriods.size(); 9 | int iMaxLags = max(vPeriods); 10 | arma::mat mHARData((iT - iMaxLags-h+1) , (iLags + 1)); 11 | int k = 0; 12 | if(vPeriods[0] == 1){ 13 | mHARData.col(1) = vRealizedMeasure(arma::span(iMaxLags-1 , (iT - h-1))); 14 | k = 1; 15 | } 16 | 17 | for(int i = k; i iRowsB){ 46 | mA.shed_rows(0, iRowsA-iRowsB-1); 47 | } 48 | if(iRowsA < iRowsB){ 49 | mB.shed_rows(0, iRowsB-iRowsA-1); 50 | } 51 | 52 | mC = join_rows(mA, mB); 53 | 54 | return(mC); 55 | 56 | 57 | 58 | } 59 | -------------------------------------------------------------------------------- /man/HARSim-class.Rd: -------------------------------------------------------------------------------- 1 | \name{HARSim-class} 2 | \alias{HARSim-class} 3 | \alias{show,HARSim-method} 4 | \alias{plot,HARSim,missing-method} 5 | \alias{uncmean,HARSim-method} 6 | \alias{coef,HARSim-method} 7 | \docType{class} 8 | \title{ 9 | HARSim 10 | } 11 | \description{ 12 | Class for HARSim object 13 | } 14 | \section{Objects from the Class}{A virtual Class: No objects may be created from it} 15 | \section{Slots}{ 16 | \describe{ 17 | \item{\code{simulation}:}{Object of class \code{numeric} containing the simulated series} 18 | \item{\code{info}:}{Object of class \code{list} cointaining:} 19 | \itemize{ 20 | \item{\code{len}:} Object of class \code{numeric} containing the length of the simulated series 21 | \item{\code{periods}:} Object of class \code{numeric} containing the lag-vector used for simulation 22 | \item{\code{coefficients}:} Object of class \code{numeric} containing the coefficients used for simulation 23 | \item{\code{errorTermSD}:} Object of class \code{numeric} containing the standard error of the error term 24 | \item{\code{elapsedTime}:} Object of class \code{difftime} containing the time elapsed in seconds} 25 | } 26 | } 27 | 28 | \section{Methods}{ 29 | \describe{ 30 | \item{\code{show}:}{\code{signature(object = "HARSim")}: Shows summary} 31 | \item{\code{plot}:}{\code{signature(x = "HARSim" , y = "missing")}: Plot the forecasted series and observed series as well as the residuals} 32 | \item{\code{uncmean}:}{\code{signature(object = "HARSim")}: Extracts the unconditional mean from the simulation} 33 | \item{\code{coef}:}{\code{signature(object = "HARSim")}: Extracts the coefficients from the simulation} 34 | }} 35 | \author{Emil Sjoerup} 36 | \keyword{classes} -------------------------------------------------------------------------------- /ChangeLog: -------------------------------------------------------------------------------- 1 | 2019-01-24 Emil Sjoerup 2 | *DESCRIPTION (Version): New version is 0.2 3 | *NAMESPACE (exports):No longer exports HARDataCreationC 4 | *NAMESPACE importFrom("methods" , "missingArg") added 5 | *Added HAR-J, HARQ, and HARQ-J models to estimation and forecasting 6 | *Add ellipsis to plotting to increase user control 7 | *Improve plotting routines by using xts 8 | *Bug fix in forecasting. 9 | *Forecasts are now output as a named matrix 10 | *Remove function HARMonteCarlo 11 | *Rename uncondmean to uncmean 12 | 2019-03-19 Emil Sjoerup 13 | *DESCRIPTION (Version): New version is 0.3 14 | *Change many of the names used in the package, now the nomenclature is much cleaner. 15 | *Fix typo in HARQ-J where JumpForecast was named JumpFOrecast 16 | *Added some methods that work with "lm" objects that I thought may be useful (wrappers for the "lm" model of HARModel) 17 | 2019-04-13 Emil Sjoerup 18 | *Added windowType argument to HARForecast() to allow for expanding window estimation when forecasting. 19 | *Bugfix in plotting models with non-xts objects. 20 | *Implemented the TV-HAR model 21 | 2019-05-08 Emil Sjoerup 22 | *Re-organized the HARestimate and HARforecast functions to have less repeated code. 23 | *Implement method forc to extract the forecasted series. 24 | 2019-07-02 Emil Sjoerup 25 | *Fix plotting method, the colors and legend was in the wrong order. Now lines() is used instead of plot.xts(cbind) 26 | 2019-08-14 Emil Sjoerup 27 | *Finish implementing the h-models i.e. weekly or monthly RV estimation 28 | *Implemented h-forecasting i.e. weekly or monthly RV forecasting (only 1 period ahead.) 29 | 2019-08-14 Emil Sjoeurp 30 | *Change the name from iNAhead and iNRoll to nAhead and nRoll respectively 31 | *Change shift over to camelCase where appropriate 32 | 2019-08-19 Emil Sjoerup 33 | *DESCRIPTION (version): New version is 1.0 as the API has changed. 34 | *Move to camelCase for all user-level interactions with the software. 35 | -------------------------------------------------------------------------------- /man/HARModel-class.Rd: -------------------------------------------------------------------------------- 1 | \name{HARModel-class} 2 | \alias{HARModel-class} 3 | \alias{show,HARModel-method} 4 | \alias{plot,HARModel,missing-method} 5 | \alias{uncmean,HARModel-method} 6 | \alias{uncmean,ANY-method} 7 | \alias{uncmean} 8 | \alias{coef,HARModel-method} 9 | \alias{sandwichNeweyWest,HARModel-method} 10 | \alias{sandwichNeweyWest,ANY-method} 11 | \alias{sandwichNeweyWest} 12 | \alias{qlike,HARModel-method} 13 | \alias{qlike,ANY-method} 14 | \alias{qlike} 15 | \alias{logLik,HARModel-method} 16 | \alias{confint,HARModel-method} 17 | \alias{residuals,HARModel-method} 18 | \alias{summary,HARModel-method} 19 | \alias{fitted.values,HARModel-method} 20 | 21 | 22 | 23 | \docType{class} 24 | \title{ 25 | HARModel 26 | } 27 | \description{ 28 | Class for HARModel objects 29 | } 30 | \section{Objects from the Class}{A virtual Class: No objects may be created from it.} 31 | \section{Slots}{ 32 | \describe{ 33 | \item{\code{model}:}{Object of class \code{lm}. Contains the linear model fitted.} 34 | \item{\code{info}:}{Object of class \code{list} cointaining:} 35 | \itemize{\item{\code{periods}:} \code{numeric} containing the lags used to create the model. If the type isn't "HAR", then the related periods-(RQ) and/or (J) will also be included. 36 | \item{\code{dates}:} \code{Date} object containing the dates for which the estimation was done, only applicable if the Model was estimated using an "xts" object.} 37 | } 38 | } 39 | \section{Methods}{ 40 | \describe{ 41 | \item{\code{show}:}{\code{signature(object = "HARModel")} Shows summary} 42 | \item{\code{plot}:}{\code{signature(x = "HARModel", y = "missing")}: Plots the observed values with fitted values overlayed} 43 | \item{\code{uncmean}:}{\code{signature(object = "HARModel")}: Extracts the unconditional mean from the Model, only available when type = "HAR"} 44 | \item{\code{coef}:}{\code{signature(object = "HARModel")}: Extracts the coefficients from the Model} 45 | \item{\code{sandwichNeweyWest}:}{\code{signature(object = "HARModel")}: Utilize the \code{sandwich} package to create newey west standard errors} 46 | \item{\code{qlike}:}{\code{signature(object = "HARModel")}: Calculate the in sample 'qlike' loss function for a HARModel object} 47 | \item{\code{logLik}:}{A wrapper for the "lm" subclass of the HARModel object} 48 | \item{\code{confint}:}{A wrapper for the "lm" subclass of the HARModel object} 49 | \item{\code{residuals}:}{A wrapper for the "lm" subclass of the HARModel object} 50 | \item{\code{summary}:}{A wrapper for the "lm" subclass of the HARModel object} 51 | 52 | }} 53 | \author{Emil Sjoerup} 54 | \keyword{classes} -------------------------------------------------------------------------------- /man/HARForecast-class.Rd: -------------------------------------------------------------------------------- 1 | \name{HARForecast-class} 2 | \alias{HARForecast-class} 3 | \alias{show,HARForecast-method} 4 | \alias{plot,HARForecast,missing-method} 5 | \alias{uncmean,HARForecast-method} 6 | \alias{coef,HARForecast-method} 7 | \alias{qlike,HARForecast-method} 8 | \alias{forecastRes,HARForecast-method} 9 | \alias{forecastRes,ANY-method} 10 | \alias{forecastRes} 11 | \alias{getForc,HARForecast-method} 12 | \alias{getForc,ANY-method} 13 | \alias{getForc} 14 | \docType{class} 15 | \title{ 16 | HARForecast 17 | } 18 | \description{ 19 | Class for HARForecast object 20 | } 21 | \section{Objects from the Class}{A virtual Class: No objects may be created from it} 22 | \section{Slots}{ 23 | \describe{ 24 | \item{\code{model}:}{Object of class \code{HARModel}. see \link{HARModel} } 25 | \item{\code{forecast}:}{Object of class \code{matrix} containing the forecasted series} 26 | \item{\code{info}:}{Object of class \code{list} cointaining:} 27 | \itemize{\item{\code{elapsedTime}:} Object of class \code{difftime} containing the time elapsed in seconds 28 | \item{\code{rolls}:} \code{Integer} containing the amount of rolls done in the forecasting routine 29 | \item{\code{horizon}:} \code{Integer} containing the length of the horizon used for forecasting during each of the rolls} 30 | \item{\code{data}:}{Object of class \code{list} containing:} 31 | \itemize{\item{\code{dates}:}Object of type \code{Integer} or \code{Date} containing the indices of the forecasted series either in integer or date format 32 | \item{\code{observations}:}Object of type \code{numeric} or \code{xts} containing the in-sample observations 33 | \item{\code{forecastComparison}:} Object of type \code{numeric} or \code{xts} containing the observations kept out of sample for the first roll 34 | } 35 | } 36 | } 37 | 38 | \section{Methods}{ 39 | \describe{ 40 | \item{\code{show}:}{\code{signature(object = "HARForecast")}: Shows summary} 41 | \item{\code{plot}:}{\code{signature(x = "HARForecast", y = "missing")}: Plot the out of sample observed series with the forecasts overlayed} 42 | \item{\code{uncmean}:}{\code{signature(object = "HARForecast")}: Extracts the unconditional mean from the Model} 43 | \item{\code{coef}:}{\code{signature(object = "HARForecast")}: Extracts the coefficients from the first estimated Model} 44 | \item{\code{qlike}:}{\code{signature(object = "HARForecast")}: Calculate the out of sample 'qlike' loss function for a HARForecast object} 45 | \item{\code{forecastres}:}{\code{signature(object = "HARForecast")}: Retrieve the forecast residuals from HARForecast object} 46 | \item{\code{forc}:}{\code{signature(object = "HARForecast")}: Retrieve the forecasted series.} 47 | }} 48 | \author{Emil Sjoerup} 49 | \keyword{classes} -------------------------------------------------------------------------------- /src/RcppExports.cpp: -------------------------------------------------------------------------------- 1 | // Generated by using Rcpp::compileAttributes() -> do not edit by hand 2 | // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 3 | 4 | #include 5 | #include 6 | 7 | using namespace Rcpp; 8 | 9 | // HARDataCreationC 10 | arma::mat HARDataCreationC(arma::vec vRealizedMeasure, arma::vec vPeriods, int h); 11 | RcppExport SEXP _HARModel_HARDataCreationC(SEXP vRealizedMeasureSEXP, SEXP vPeriodsSEXP, SEXP hSEXP) { 12 | BEGIN_RCPP 13 | Rcpp::RObject rcpp_result_gen; 14 | Rcpp::RNGScope rcpp_rngScope_gen; 15 | Rcpp::traits::input_parameter< arma::vec >::type vRealizedMeasure(vRealizedMeasureSEXP); 16 | Rcpp::traits::input_parameter< arma::vec >::type vPeriods(vPeriodsSEXP); 17 | Rcpp::traits::input_parameter< int >::type h(hSEXP); 18 | rcpp_result_gen = Rcpp::wrap(HARDataCreationC(vRealizedMeasure, vPeriods, h)); 19 | return rcpp_result_gen; 20 | END_RCPP 21 | } 22 | // HARMatCombine 23 | arma::mat HARMatCombine(arma::mat mA, arma::mat mB); 24 | RcppExport SEXP _HARModel_HARMatCombine(SEXP mASEXP, SEXP mBSEXP) { 25 | BEGIN_RCPP 26 | Rcpp::RObject rcpp_result_gen; 27 | Rcpp::RNGScope rcpp_rngScope_gen; 28 | Rcpp::traits::input_parameter< arma::mat >::type mA(mASEXP); 29 | Rcpp::traits::input_parameter< arma::mat >::type mB(mBSEXP); 30 | rcpp_result_gen = Rcpp::wrap(HARMatCombine(mA, mB)); 31 | return rcpp_result_gen; 32 | END_RCPP 33 | } 34 | // HARSimC 35 | arma::mat HARSimC(int iLength, arma::vec vLags, double dConst, arma::vec coef, double dSigma); 36 | RcppExport SEXP _HARModel_HARSimC(SEXP iLengthSEXP, SEXP vLagsSEXP, SEXP dConstSEXP, SEXP coefSEXP, SEXP dSigmaSEXP) { 37 | BEGIN_RCPP 38 | Rcpp::RObject rcpp_result_gen; 39 | Rcpp::RNGScope rcpp_rngScope_gen; 40 | Rcpp::traits::input_parameter< int >::type iLength(iLengthSEXP); 41 | Rcpp::traits::input_parameter< arma::vec >::type vLags(vLagsSEXP); 42 | Rcpp::traits::input_parameter< double >::type dConst(dConstSEXP); 43 | Rcpp::traits::input_parameter< arma::vec >::type coef(coefSEXP); 44 | Rcpp::traits::input_parameter< double >::type dSigma(dSigmaSEXP); 45 | rcpp_result_gen = Rcpp::wrap(HARSimC(iLength, vLags, dConst, coef, dSigma)); 46 | return rcpp_result_gen; 47 | END_RCPP 48 | } 49 | // fastLMcoef 50 | arma::vec fastLMcoef(arma::mat X, arma::colvec y); 51 | RcppExport SEXP _HARModel_fastLMcoef(SEXP XSEXP, SEXP ySEXP) { 52 | BEGIN_RCPP 53 | Rcpp::RObject rcpp_result_gen; 54 | Rcpp::RNGScope rcpp_rngScope_gen; 55 | Rcpp::traits::input_parameter< arma::mat >::type X(XSEXP); 56 | Rcpp::traits::input_parameter< arma::colvec >::type y(ySEXP); 57 | rcpp_result_gen = Rcpp::wrap(fastLMcoef(X, y)); 58 | return rcpp_result_gen; 59 | END_RCPP 60 | } 61 | 62 | static const R_CallMethodDef CallEntries[] = { 63 | {"_HARModel_HARDataCreationC", (DL_FUNC) &_HARModel_HARDataCreationC, 3}, 64 | {"_HARModel_HARMatCombine", (DL_FUNC) &_HARModel_HARMatCombine, 2}, 65 | {"_HARModel_HARSimC", (DL_FUNC) &_HARModel_HARSimC, 5}, 66 | {"_HARModel_fastLMcoef", (DL_FUNC) &_HARModel_fastLMcoef, 2}, 67 | {NULL, NULL, 0} 68 | }; 69 | 70 | RcppExport void R_init_HARModel(DllInfo *dll) { 71 | R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); 72 | R_useDynamicSymbols(dll, FALSE); 73 | } 74 | -------------------------------------------------------------------------------- /man/HARestimate.Rd: -------------------------------------------------------------------------------- 1 | \name{HAREstimate} 2 | \alias{HAREstimate} 3 | \title{ 4 | HAR estimation 5 | } 6 | \description{ 7 | HAR estimation 8 | } 9 | \usage{ 10 | HAREstimate(RM, BPV = NULL, RQ = NULL, periods = c(1,5,22), 11 | periodsJ = NULL, periodsRQ = NULL, type = "HAR", 12 | insanityFilter = TRUE, h = 1) 13 | } 14 | \arguments{ 15 | \item{RM}{ 16 | A \code{numeric} containing a realized measure of the integrated volatility. 17 | } 18 | \item{BPV}{ 19 | A \code{numeric} containing the estimate of the continuous part of the integrated volatility used for \code{HARJ} and \code{HARQ-J} types. 20 | } 21 | \item{RQ}{ 22 | A \code{numeric} containing the realized quarticity used for \code{HARQ} and \code{HARQ-J} types. 23 | } 24 | \item{periods}{ 25 | A \code{numeric} denoting which lags should be used in the estimation, standard of \code{c(1,5,22)} is in line with Corsi(2009). 26 | } 27 | \item{periodsJ}{ 28 | A \code{numeric} denoting which lags should be used in Jump estimation, if applicable. 29 | } 30 | \item{periodsRQ}{ 31 | A \code{numeric} denoting which lags should be used in Realized Quarticity estimation, if applicable. 32 | } 33 | \item{type}{ 34 | A \code{character} denoting which type of HAR model to estimate. 35 | } 36 | \item{insanityFilter}{ 37 | A \code{logical} denoting whether the insanity filter should be used for the fitted values of the estimation see Bollerslev, Patton & Quaedvlieg(2016) footnote 17. 38 | } 39 | \item{h}{ 40 | A \code{integer} denoting the whether and how much to aggregate the realized variance estimator, if h = 5 the model is for the weekly volatility and if h = 22, the model is for the monthly volatility, the default of 1 designates no aggregation. 41 | } 42 | } 43 | \value{ 44 | A \code{\linkS4class{HARModel}} object 45 | } 46 | \details{ 47 | The estimates for the HARQ and HARQ-J models differ slightly from the results of BPQ (2016). This is due to a small difference in the demeaning approach for the realized quarticity. Here, the demeaning is done with mean(RQ) over all periods. 48 | } 49 | \references{ 50 | Corsi, F. 2009, A Simple Approximate Long-Memory Model 51 | of Realized Volatility, \emph{Journal of Financial Econometrics}, 174--196.\cr 52 | Bollerslev, T., Patton, A., Quaedvlieg, R. 2016, Exploiting the errors: A simple approach for improved volatility forecasting, \emph{Journal of Econometrics }, vol.192, issue 1, 1-18. \cr 53 | } 54 | \author{ 55 | Emil Sjoerup 56 | } 57 | \examples{ 58 | #Vanilla HAR from Corsi(2009) 59 | #load data 60 | data("SP500RM") 61 | SP500rv = SP500RM$RV 62 | #Estimate the HAR model: 63 | FitHAR = HAREstimate(RM = SP500rv, periods = c(1,5,22)) 64 | 65 | #extract the estimated coefficients: 66 | coef(FitHAR) 67 | #plot the fitted values 68 | plot(FitHAR) 69 | 70 | #calculate the Q-like loss-function: 71 | mean(qlike(FitHAR)) 72 | 73 | 74 | 75 | 76 | #HAR-J: 77 | #load data 78 | data("SP500RM") 79 | SP500rv = SP500RM$RV 80 | SP500bpv = SP500RM$BPV 81 | 82 | #Estimate the HAR-J model: 83 | FitHARJ = HAREstimate(RM = SP500rv, BPV = SP500bpv, 84 | periods = c(1,5,22), periodsJ = c(1,5,22), type = "HARJ" ) 85 | 86 | #Calculate the Q-like loss-function: 87 | mean(qlike(FitHARJ)) 88 | 89 | 90 | 91 | 92 | #HAR-Q of BPQ(2016) with weekly aggregation 93 | #load data 94 | data("SP500RM") 95 | SP500rv = SP500RM$RV 96 | SP500rq = SP500RM$RQ 97 | #Estimate the HAR-Q model: 98 | FitHARQ = HAREstimate(RM = SP500rv, RQ = SP500rq, periods = c(1,5,22), 99 | periodsRQ = c(1,5,22), type = "HARQ", h = 5) 100 | #Show the model: 101 | show(FitHARQ) 102 | 103 | #Extract the coefficients: 104 | HARQcoef = coef(FitHARQ) 105 | 106 | 107 | 108 | 109 | #HARQ-J of BPQ(2016) with monthly aggregation 110 | #load data 111 | data("SP500RM") 112 | SP500rv = SP500RM$RV 113 | SP500rq = SP500RM$RQ 114 | SP500bpv = SP500RM$BPV 115 | 116 | #Estimate the HARQ-J model: 117 | FitHARQJ = HAREstimate(RM = SP500rv, BPV = SP500bpv, 118 | RQ = SP500rq, periods = c(1,5,22), 119 | periodsJ = c(1), periodsRQ = c(1), 120 | type = "HARQ-J", h = 22) 121 | #show the model: 122 | show(FitHARQJ) 123 | 124 | 125 | 126 | } -------------------------------------------------------------------------------- /Using HARModel.R: -------------------------------------------------------------------------------- 1 | #Using HAR model Package 2 | rm(list = ls()) 3 | 4 | library(HARModel) 5 | data("SP500RM") 6 | 7 | SP500rv = SP500RM$RV 8 | SP500rq = SP500RM$RQ 9 | SP500bpv = SP500RM$BPV 10 | 11 | #######################Estimation####################### 12 | HARFit = HAREstimate(SP500rv, periods = c(1,5,22)) 13 | 14 | CHARFit = HAREstimate(SP500rv, BPV = SP500bpv, periods = c(1,5,22), type = "CHAR") 15 | 16 | CHARQFit = HAREstimate(SP500rv, BPV = SP500bpv, RQ = SP500rq, 17 | periods = c(1,5,22), periodsRQ = c(1), type = "CHARQ") 18 | 19 | HARJFit = HAREstimate(RM = SP500rv, BPV = SP500bpv, 20 | periods = c(1,5,22), periodsJ = c(1), type = "HARJ" ) 21 | 22 | HARQFit = HAREstimate(RM = SP500rv, RQ = SP500rq, 23 | periods = c(1,5,22 ), periodsRQ = c(1), type = "HARQ") 24 | 25 | FullHARQFit = HAREstimate(RM = SP500rv, RQ = SP500rq, 26 | periods = c(1,5,22 ), periodsRQ = c(1,5,22), type = "HARQ") 27 | 28 | HARQJFit = HAREstimate(RM = SP500rv, BPV = SP500bpv, RQ = SP500rq, 29 | periods = c(1,5,22), periodsJ = c(1,5,22), 30 | periodsRQ = c(1), type = "HARQ-J") 31 | 32 | FullHARQJFit = HAREstimate(RM = SP500rv, BPV = SP500bpv, RQ = SP500rq, 33 | periods = c(1,5,22), periodsJ = c(1,5,22), 34 | periodsRQ = c(1,5,22), type = "HARQ-J") 35 | 36 | plot(HARQFit) 37 | 38 | summary(HARQFit) #Wrapper for the lm submodel 39 | 40 | logLik(HARQFit) #Wrapper for the lm submodel 41 | 42 | confint(HARQFit) #Wrapper for the lm submodel 43 | #Q-like: 44 | mean(qlike(HARFit)) 45 | mean(qlike(HARQFit)) 46 | 47 | 48 | 49 | #######################Forecasting####################### 50 | 51 | HARForc = HARForecast(SP500rv, periods = c(1,5,22), 52 | nRoll = 3096, nAhead = 50, type = "HAR" ) 53 | 54 | HARIForc = HARForecast(SP500rv, periods = c(1,5,22) , 55 | nRoll = 3096, nAhead = 1, type = "HAR", windowType = "increasing" ) 56 | 57 | HARJForc = HARForecast(SP500rv, BPV = SP500bpv, periods = c(1,5,22), 58 | periodsJ = c(1) ,nRoll = 3096, 59 | nAhead = 50, type = "HARJ" ) 60 | 61 | HARJIForc = HARForecast(SP500rv, BPV = SP500bpv, periods = c(1,5,22), 62 | periodsJ = c(1) ,nRoll = 3096,nAhead = 1, 63 | type = "HARJ", windowType = "increasing" ) 64 | 65 | FULLHARJForc = HARForecast(SP500rv, BPV = SP500bpv, periods = c(1,5,22), 66 | periodsJ = c(1,5,22) ,nRoll = 3096,nAhead = 1, type = "HARJ" ) 67 | 68 | HARQForc = HARForecast(SP500rv, RQ = SP500rq, periods = c(1,5,22), 69 | periodsRQ = c(1), nRoll = 3096, nAhead = 1,type = "HARQ" ) 70 | 71 | FULLHARQForc = HARForecast(SP500rv, RQ= SP500rq, periods = c(1,5,22), 72 | periodsRQ = c(1,5,22), 73 | nRoll = 3096, nAhead = 1,type = "HARQ") 74 | 75 | HARQJForc = HARForecast(SP500rv, RQ = SP500rq, BPV = SP500bpv, 76 | periods = c(1,5,22), periodsJ = c(1), periodsRQ = c(1), 77 | nRoll = 3096,nAhead = 1, type = "HARQ-J") 78 | 79 | CHARForc = HARForecast(SP500rv, RQ = SP500rq, BPV = SP500bpv, 80 | periods = c(1,5,22), periodsJ = c(1), periodsRQ = c(1), 81 | nRoll = 3096,nAhead = 1, type = "CHAR") 82 | 83 | CHARQForc = HARForecast(SP500rv, RQ = SP500rq, BPV = SP500bpv, 84 | periods = c(1,5,22), periodsJ = c(1), periodsRQ = c(1), 85 | nRoll = 3096,nAhead = 1, type = "CHARQ") 86 | 87 | #Plot: 88 | plot(HARForc) 89 | 90 | #To get the forecasted series of a HARForecast object: 91 | forecast = getForc(HARForc) 92 | 93 | #To get the forecast residualse: 94 | forcRes = forecastRes(HARForc) 95 | 96 | ##Select loss functions from updated table 4 of BPQ: 97 | 98 | mean(forecastRes(HARJForc)^2)/mean(forecastRes(HARForc)^2) 99 | mean(forecastRes(HARQForc)^2)/mean(forecastRes(HARForc)^2) 100 | mean(forecastRes(CHARForc)^2)/mean(forecastRes(HARForc)^2) 101 | 102 | 103 | mean(qlike(HARJForc))/mean(qlike(HARForc)) 104 | mean(qlike(HARQForc))/mean(qlike(HARForc))#Slightly different from BPQ due to how I do the averaging vs how they do it (Both schemes make sense!) 105 | mean(qlike(CHARForc))/mean(qlike(HARForc)) 106 | 107 | 108 | #######################Simulation####################### 109 | set.seed(123) 110 | lSim = HARSimulate(len = 4.5e4, periods = c(1,5,22), 111 | coef = c(0.1, 0.38, 0.28, 0.28), errorTermSD = 0.01) 112 | 113 | plot(lSim) 114 | 115 | FitSim = HAREstimate(lSim@simulation, periods = c(1,5,22)) 116 | 117 | plot(FitSim) 118 | -------------------------------------------------------------------------------- /man/HARforecast.Rd: -------------------------------------------------------------------------------- 1 | \name{HARForecast} 2 | \alias{HARForecast} 3 | \title{ 4 | HAR forecasting 5 | } 6 | \description{ 7 | Rolling out of sample forecasting of a HAR model. 8 | } 9 | \usage{ 10 | HARForecast(RM, BPV= NULL, RQ = NULL , periods = c(1,5,22), 11 | periodsJ = NULL, periodsRQ = NULL, nRoll=10 , nAhead=1 , type = "HAR", 12 | windowType = "rolling", insanityFilter = TRUE, h = 1) 13 | } 14 | \arguments{ 15 | \item{RM}{ 16 | An \code{xts} object containing a realized measure of the integrated volatility. 17 | } 18 | \item{BPV}{ 19 | A \code{numeric} containing the jump proportion of the realized measure used for \code{HARJ} and \code{HARQ-J} types. 20 | } 21 | \item{RQ}{ 22 | A \code{numeric} containing the realized quarticity used for \code{HARQ} and \code{HARQ-J} types. 23 | } 24 | \item{periods}{ 25 | A vector denoting which lags should be used in the estimation, standard of \code{c(1,5,22)} is in line with Corsi(2009). 26 | } 27 | \item{periodsJ}{ 28 | A \code{numeric} denoting which lags should be used in Jump estimation, if applicable. 29 | } 30 | \item{periodsRQ}{ 31 | A \code{numeric} denoting which lags should be used in Realized Quarticity estimation, if applicable. 32 | } 33 | \item{nRoll}{ 34 | How many rolling forecasts should be performed. 35 | } 36 | \item{nAhead}{ 37 | The length of each rolling forecast. 38 | } 39 | \item{type}{ 40 | A \code{character} denoting which type of HAR model to estimate. 41 | } 42 | \item{windowType}{ 43 | A \code{character} denoting which kind of window to use, either "rolling"/"fixed" or "increasing"/"expanding". 2-letter abbreviations can be used. 44 | } 45 | \item{insanityFilter}{ 46 | A \code{logical} denoting whether the insanity filter should be used for the forecasted values see Bollerslev, Patton & Quaedvlieg(2016) footnote 17. 47 | } 48 | \item{h}{ 49 | A \code{integer} denoting the whether and how much to aggregate the realized variance estimator, if h = 5 the model is forecasting the weekly volatility and if h = 22, the model is forecasting the monthly volatility, the default of 1 designates no aggregation.. 50 | } 51 | } 52 | \value{ 53 | A \code{\linkS4class{HARForecast}} object 54 | } 55 | \details{ 56 | Not all models in this package are 'complete', which means some models use AR(1) processes to forecast e.g. realized quarticity in order to construct more than one step ahead forecasts. 57 | 58 | The maximumm lag of the continuous or quarticity data must be lower than the maximum of the realized measure lag vector, the other cases are not implemented. 59 | 60 | The estimates for the \code{HARQ} and \code{HARQ-J} models differ slightly from the results of BPQ (2016). This is due to a small difference in the demeaning approach for the realized quarticity. Here, the demeaning is done with mean(RQ) over all periods. 61 | 62 | If \code{h} is greater than 1, then \code{nAhead} must be one, as multi-period ahead forecasts have not been implemented. 63 | 64 | 65 | } 66 | \references{ 67 | Corsi, F. 2009, A Simple Approximate Long-Memory Model 68 | of Realized Volatility, \emph{Journal of Financial Econometrics}, 174--196.\cr 69 | Bollerslev, T., Patton, A., Quaedvlieg, R. 2016, Exploiting the errors: A simple approach for improved volatility forecasting, \emph{Journal of Econometrics }, vol.192 , issue 1, 1-18. \cr 70 | } 71 | \author{ 72 | Emil Sjoerup 73 | } 74 | \seealso{ 75 | See Also \code{\link{HAREstimate}} 76 | } 77 | \examples{ 78 | #HAR of Corsi(2009) 79 | #load data: 80 | data("SP500RM") 81 | SP500rv = SP500RM$RV 82 | 83 | ForecastHAR = HARForecast(SP500rv, periods = c(1,5,22), nRoll =50, 84 | nAhead = 50, type = "HAR") 85 | 86 | #plot the forecasted series along with the actual realizations: 87 | plot(ForecastHAR) 88 | 89 | #Calculate the MSE: 90 | mean(forecastRes(ForecastHAR)^2) 91 | 92 | #Calculate the Q-like loss function: 93 | mean(qlike(ForecastHAR)) 94 | 95 | 96 | 97 | 98 | #HARJ 99 | #load data: 100 | data("SP500RM") 101 | SP500rv = SP500RM$RV 102 | SP500bpv = SP500RM$BPV 103 | 104 | 105 | ForecastHARJ = HARForecast(SP500rv, BPV = SP500bpv, periods = c(1,5,22), 106 | periodsJ = c(1,5,22) ,nRoll = 50, 107 | nAhead = 50, type = "HARJ") 108 | 109 | #Show the model: 110 | show(ForecastHARJ) 111 | 112 | #Extract the forecasted series: 113 | forc = getForc(ForecastHARJ) 114 | 115 | 116 | 117 | 118 | #HARQ BPQ(2016) 119 | #load data 120 | data("SP500RM") 121 | SP500rv = SP500RM$RV 122 | SP500rq = SP500RM$RQ 123 | 124 | ForecastHARQ = HARForecast(SP500rv, RQ= SP500rq, periods = c(1,5,22), 125 | periodsRQ = c(1,5,22), nRoll = 50, nAhead = 50, 126 | type = "HARQ") 127 | 128 | 129 | 130 | 131 | 132 | #HARQ-J BPQ(2016) with weekly aggregation. 133 | #load data 134 | data("SP500RM") 135 | SP500rv = SP500RM$RV 136 | SP500rq = SP500RM$RQ 137 | SP500bpv = SP500RM$BPV 138 | 139 | ForecastHARQJ = HARForecast(SP500rv, RQ = SP500rq, BPV = SP500bpv, 140 | periods = c(1,5,22), periodsJ = c(1,5,22), 141 | periodsRQ = c(1,5,22), nRoll = 50, 142 | nAhead = 1, type = "HARQ-J", h = 5) 143 | 144 | } 145 | \keyword{ HAR } 146 | \keyword{ forecast } 147 | -------------------------------------------------------------------------------- /tests/testthat/test_HARModel.R: -------------------------------------------------------------------------------- 1 | # estimation tests 2 | library(testthat) 3 | suppressPackageStartupMessages(library(HARModel)) 4 | context("HARModel tests") 5 | 6 | test_that("estimation tests", { 7 | data("SP500RM") 8 | SP500rv = SP500RM$RV 9 | SP500rq = SP500RM$RQ 10 | SP500bpv = SP500RM$BPV 11 | SP500tpq = SP500RM$TPQ 12 | FitHAR = HAREstimate(SP500rv, periods = c(1,5,22)) 13 | 14 | FitTVHAR = HAREstimate(SP500rv, periods = c(1,5,22), type = "TV-HAR") 15 | 16 | FitCHAR = HAREstimate(SP500rv, BPV = SP500bpv, periods = c(1,5,22), type = "CHAR") 17 | 18 | FitCHARQ = HAREstimate(SP500rv, BPV = SP500bpv, RQ = SP500tpq, periods = c(1,5,22), periodsRQ = c(1), type = "CHARQ") 19 | 20 | FitHARJ = HAREstimate(RM = SP500rv, BPV = SP500bpv, 21 | periods = c(1,5,22), periodsJ = c(1), type = "HARJ" ) 22 | 23 | 24 | FitHARQ = HAREstimate(RM = SP500rv, RQ = SP500rq, periods = c(1,5,22 ), 25 | periodsRQ = c(1), type = "HARQ") 26 | 27 | FitFullHARQ = HAREstimate(RM = SP500rv, RQ = SP500rq, periods = c(1,5,22 ), 28 | periodsRQ = c(1,5,22), type = "HARQ") 29 | 30 | FitHARQJ = HAREstimate(RM = SP500rv, BPV = SP500bpv, 31 | RQ = SP500rq, periods = c(1,5,22), 32 | periodsJ = c(1,5,22), periodsRQ = c(1), type = "HARQ-J") 33 | 34 | FitFullHARQJ = HAREstimate(RM = SP500rv, BPV = SP500bpv, 35 | RQ = SP500rq, periods = c(1,5,22), 36 | periodsJ = c(1,5,22), periodsRQ = c(1,5,22), type = "HARQ-J") 37 | 38 | 39 | expect_equal(round(coef(FitHAR), digits = 7), 40 | c("beta0" = 0.1123142, "beta1" = 0.2273436,"beta5" = 0.4903494, "beta22" = 0.1863766)) 41 | expect_equal(coef(FitCHARQ), c("beta0" = -0.006432962, "beta1" = 0.583432070, "beta5" = 0.418886906, 42 | "beta22" = 0.113096324, "beta_q1" = -0.541018770)) 43 | expect_equal(coef(FitFullHARQJ), c("beta0" =-0.01978921, "beta1" = 0.56971635, "beta5"= 0.46751653, "beta22" = 0.02578378, 44 | "beta_q1" = -0.32592648, "beta_q5" = 0.04371038, "beta_q22" = -0.11871874, "beta_j1" = -0.12456935, 45 | "beta_j5" = -1.58884086, "beta_j22" = 1.67095035)) 46 | expect_equal(mean(qlike(FitTVHAR)), 0.133913) 47 | expect_equal(mean(qlike(FitHARQ)), 0.13577366) 48 | expect_equal(mean(qlike(FitFullHARQ)), 0.13801195) 49 | expect_equal(mean(residuals(FitHARQ)^2), 2.35696246) 50 | expect_equal(mean(residuals(FitFullHARQ)^2), 2.35455696) 51 | expect_equal(mean(residuals(FitCHARQ)^2)/mean(residuals(FitHAR)^2), 0.9368255) 52 | expect_equal(mean(residuals(FitHARJ)^2)/mean(residuals(FitHAR)^2), 0.96833979) 53 | 54 | } 55 | ) 56 | 57 | 58 | test_that("forecasting tests", { 59 | data("SP500RM") 60 | SP500rv = SP500RM$RV 61 | SP500rq = SP500RM$RQ 62 | SP500bpv = SP500RM$BPV 63 | SP500tpq = SP500RM$TPQ 64 | nAhead = 1 65 | nRoll = 3096 66 | 67 | ###Rolling window forecasting: 68 | 69 | ForcHAR = HARForecast(SP500rv, periods = c(1,5,22) ,nRoll = nRoll, nAhead = nAhead, type = "HAR" ) 70 | 71 | 72 | ForcHARJ = HARForecast(SP500rv, BPV = SP500bpv, periods = c(1,5,22), 73 | periodsJ = c(1) ,nRoll = nRoll, 74 | nAhead = nAhead, type = "HARJ" ) 75 | 76 | 77 | ForcCHAR = HARForecast(SP500rv, BPV = SP500bpv, periods = c(1,5,22), 78 | nRoll = nRoll, nAhead = nAhead, 79 | type = "CHAR") 80 | 81 | 82 | ForcFULLHARQ = HARForecast(SP500rv, RQ= SP500rq, periods = c(1,5,22), 83 | periodsRQ = c(1,5,22), nRoll = nRoll, nAhead = nAhead, 84 | type = "HARQ") 85 | 86 | ###Increasing window forecasting: 87 | 88 | 89 | ForcHARI = HARForecast(SP500rv, periods = c(1,5,22) ,nRoll = nRoll, 90 | nAhead = 1, type = "HAR", windowType = "increasing" ) 91 | 92 | ForcHARQI = HARForecast(SP500rv, RQ = SP500rq, periods = c(1,5,22), 93 | periodsRQ = c(1), nRoll = nRoll, nAhead = nAhead, 94 | type = "HARQ", windowType = "increasing") 95 | 96 | ForcCHARQI = HARForecast(SP500rv, BPV = SP500bpv, RQ = SP500tpq, periods = c(1,5,22), 97 | periodsRQ = c(1), nRoll = nRoll, nAhead = nAhead, 98 | type = "CHARQ", windowType = "increasing") 99 | 100 | 101 | 102 | 103 | 104 | ###BPQ table for out of sample forecasts 105 | #Rolling window: 106 | 107 | expect_equal(mean(forecastRes(ForcHARJ)^2)/mean(forecastRes(ForcHAR)^2), 0.91751679) 108 | expect_equal(mean(forecastRes(ForcFULLHARQ)^2)/mean(forecastRes(ForcHAR)^2), 0.792906786) 109 | expect_equal(mean(forecastRes(ForcCHAR)^2) / mean(forecastRes(ForcHAR)^2), 0.95830776) 110 | expect_equal(mean(qlike(ForcHARJ))/mean(qlike(ForcHAR)), 1.01151469) 111 | expect_equal(mean(qlike(ForcCHAR))/mean(qlike(ForcHAR)), 1.02005358) 112 | 113 | #Increasing window: 114 | 115 | expect_equal(mean(forecastRes(ForcHARQI)^2) / mean(forecastRes(ForcHARI)^2), 0.89439887) 116 | expect_equal(mean(qlike(ForcHARQI))/mean(qlike(ForcHARI)), 0.88091626) 117 | 118 | }) 119 | -------------------------------------------------------------------------------- /R/ClassMethods.R: -------------------------------------------------------------------------------- 1 | setClass("HARModel", slots = c("model", "info")) 2 | setClass("HARForecast", slots = c("model", "forecast", "info", "data" )) 3 | setClass("HARSim", slots = c("simulation", "info")) 4 | 5 | setMethod("show", signature(object = "HARModel") , function(object) { 6 | coefficients = coef(object) 7 | 8 | cat("\n----------------------------------HARModel-------------------------------\n") 9 | cat("\n Observations used:", length(object@model$res),"\n", "Maximum lags",max(object@info$periods , object@info$periodsJ), "\n") 10 | if(object@info$type == "HARJ"){ 11 | cat("\n Jump observations used", max(object@info$periodsJ), "\n") 12 | } 13 | cat(paste("\n Specification:")) 14 | cat("\n Type:" , object@info$type) 15 | cat("\n Lags:", object@info$periods) 16 | if(object@info$type == "HARJ"){ 17 | cat("\n Lags used for the jump component:", object@info$periodsJ) 18 | } 19 | if(object@info$type == "HARQ"){ 20 | cat("\n Realized Quarticity lags:", object@info$periodsRQ) 21 | } 22 | cat("\n") 23 | cat(paste("\n Estimates:\n")) 24 | cat("\n") 25 | cat("\n") 26 | print(round(coefficients , 6) , digits = 4) 27 | cat("\n") 28 | cat("\n") 29 | cat("R-squared: ", round(summary(object)$r.squared, 4)) 30 | cat("\n") 31 | cat("Adjusted R-squared: ", round(summary(object)$adj.r.squared, 4)) 32 | cat("\n-------------------------------------------------------------------------\n") 33 | }) 34 | 35 | setMethod("show" , signature(object = "HARForecast") , function(object){ 36 | cat("\n First model estimated:") 37 | show(object@model) 38 | cat("\n-------------------------------HARForecast-------------------------------\n") 39 | cat("\n Forecast specification:" , object@info[["windowType"]], "\n") 40 | cat("\n Length of rolls:" , dim(object@forecast)[1],"\n") 41 | cat("\n Rolls performed:" , dim(object@forecast)[2],"\n") 42 | cat("\n Elapsed Time:" , round(as.double(object@info[["elapsedTime"]] , units = "secs" ) , digits = 3) , "seconds\n") 43 | cat("\n-------------------------------------------------------------------------\n") 44 | }) 45 | 46 | setMethod("show" , signature(object = "HARSim") , function(object){ 47 | coefficients = coef(object) 48 | cat("\n----------------------------------HARSim---------------------------------\n") 49 | cat("\n Simulation length:" , object@info$Length,"\n") 50 | cat("\n Standard deviation of the error term:", object@info[["errorTermSD"]],"\n") 51 | cat("\n Lags used:", object@info$periods, "\n") 52 | cat("\n Coefficients:\n") 53 | print(round(coefficients , 6) , digits = 4) 54 | cat("\n") 55 | cat("\n Elapsed Time:" , round(as.double(object@info[["elapsedTime"]] , units = "secs" ) , digits = 3) , "seconds\n") 56 | cat("\n-------------------------------------------------------------------------\n") 57 | }) 58 | 59 | setMethod("plot" , signature(x= "HARModel", y = "missing"), 60 | function(x, legend.loc = "topright", 61 | col = 1:2, lwd= 2, lty = c(1,2), 62 | main = NULL, 63 | legend.names = c("Realized Measure" , "Fitted values"), yaxis.right = FALSE, ...){ 64 | 65 | vY = xts(x@model$model$`mData[, 1]`, order.by = x@info$dates) 66 | vFitted.Val = xts(as.numeric(x@model$fitted.values), order.by = index(vY)) 67 | if(is.null(main)) { 68 | main = paste("Observed vs. fitted based on model: ", x@info$type) 69 | h = x@info$h 70 | if(h!=1){ 71 | main = paste(main, "\n h=", h) 72 | } 73 | } 74 | plot(vY, main = main, col = col[1], yaxis.right = yaxis.right, ...) 75 | lines(vFitted.Val, col = col[2]) 76 | addLegend(legend.loc = legend.loc, legend.names = legend.names, 77 | col = col, lwd = lwd) 78 | 79 | }) 80 | 81 | setMethod("plot" , signature(x = "HARForecast", y = "missing"), 82 | function(x, legend.loc = "topright", 83 | legend.names = c("Realized Measure","Forecasted Values"), main =NULL, 84 | col = 1:2, lwd= 2, lty = c(1,2), yaxis.right = FALSE,...){ 85 | vForecastComp = x@data$`forecastComparison` 86 | vRollingForecastplot = getForc(x) 87 | if(is.null(main)) main = paste("Observed vs. forecasted based on model: ", x@info$type) 88 | plot(vForecastComp, col = col[1], main = main, yaxis.right = yaxis.right, ...) 89 | lines(vRollingForecastplot, col = col[2]) 90 | addLegend(legend.loc = legend.loc, legend.names = legend.names, col = col, lwd = lwd) 91 | 92 | }) 93 | 94 | setMethod("plot" , signature(x = "HARSim" , y = "missing"), 95 | function(x , length = "ALL" , ctrl = "start", main = "Simulated RV", ...){ 96 | vY = xts(x@simulation , order.by = as.Date(1:length(x@simulation), origin = "1970/01/01")) 97 | if(length == "ALL"){ 98 | plot(vY , main = main, ...) 99 | } 100 | else if (ctrl == "start" & is(length,"numeric")){ 101 | plot(vY[1:length], main = main, ...) 102 | }else if(ctrl == "end" & is(length,"numeric")){ 103 | plot(vY[(length(vY) - length):length(vY)], main = main, ... ) 104 | } 105 | 106 | }) 107 | 108 | setMethod("coef" , signature(object = "HARModel") , function(object){ 109 | vCoef = object@model$coefficients 110 | return(vCoef) 111 | }) 112 | 113 | setMethod("coef" , signature(object = "HARForecast") , function(object){ 114 | vCoef = object@model@model$coefficients 115 | return(vCoef) 116 | }) 117 | 118 | setMethod("coef" , signature(object = "HARSim") , function(object){ 119 | vCoef = object@info$Coefficients 120 | return(vCoef) 121 | }) 122 | 123 | 124 | setGeneric("uncmean", function(object) 125 | standardGeneric("uncmean") 126 | ) 127 | 128 | setMethod("uncmean" , signature(object = "HARModel") , function(object){ 129 | if(object@info[["type"]]!="HAR"){ 130 | print("Unconditional mean is only implemented for HAR type") 131 | return(NULL) 132 | } 133 | vCoef = coef(object) 134 | uncmean = vCoef[1]/(1-sum(vCoef[-1])) 135 | names(uncmean) = "" 136 | return(c("Unconditional Mean" = uncmean)) 137 | }) 138 | 139 | setMethod("uncmean" , signature(object = "HARForecast") , function(object){ 140 | if(!object@info[["type"]]=="HAR"){ 141 | print("Unconditional mean is only implemented for HAR type") 142 | return(NULL) 143 | } 144 | vCoef = coef(object) 145 | uncmean = vCoef[1]/(1-sum(vCoef[2:length(vCoef)])) 146 | names(uncmean) = "" 147 | return(c("Unconditional Mean" = uncmean)) 148 | }) 149 | 150 | setMethod("uncmean" , signature(object = "HARSim") , function(object){ 151 | vCoef = coef(object) 152 | uncmean = vCoef[1]/(1-sum(vCoef[-1])) 153 | names(uncmean) = "" 154 | return(c("Unconditional Mean" = uncmean)) 155 | }) 156 | 157 | setGeneric("sandwichNeweyWest", function(object , lags) 158 | standardGeneric("sandwichNeweyWest") 159 | ) 160 | 161 | setMethod("sandwichNeweyWest" , signature(object = "HARModel") , function(object , lags = 5){ 162 | if(missingArg(lags)){ 163 | lags = 5 164 | } 165 | cat("\n-------------------Newey-West Standard errors----------------\n") 166 | mVarCovar = sandwich::NeweyWest(object@model , lags) 167 | coefficients = coef(object) 168 | cat(paste("\n Newey-West Standard errors using a lag order of ", lags , ":\n", sep="")) 169 | mPrint = rbind(coefficients , "Standard errors" = diag(mVarCovar), 170 | "T-Statistics" = coefficients/diag(mVarCovar), "P-values" = dt(coefficients/diag(mVarCovar) , 171 | df=object@model$df.residual)) 172 | print(round(mPrint,6 ) ,5 ) 173 | cat("\n-------------------------------------------------------------\n") 174 | return("HACmatrix" = mVarCovar) 175 | }) 176 | 177 | setGeneric("getForc", function(object, whichStep = 1) 178 | standardGeneric("getForc") 179 | ) 180 | 181 | setMethod("getForc", signature(object = "HARForecast"), function(object, whichStep = 1){ 182 | vDates = object@data$forecastDates + whichStep-1 183 | vForc = xts(object@forecast[whichStep,], vDates) 184 | return(vForc) 185 | }) 186 | 187 | setGeneric("forecastRes", function(object) 188 | standardGeneric("forecastRes") 189 | ) 190 | 191 | 192 | setMethod("forecastRes", signature(object = "HARForecast"), function(object){ 193 | vRes = getForc(object) - object@data$forecastComparison 194 | return(vRes) 195 | }) 196 | 197 | 198 | setGeneric("qlike", function(object) 199 | standardGeneric("qlike") 200 | ) 201 | 202 | setMethod("qlike", signature(object = "HARModel"), function(object){ 203 | RM = object@model$model[,1] #extract RM from model 204 | FV = object@model$fitted.values 205 | qLike = RM/FV - log(RM / FV) - 1 206 | return(qLike) 207 | } 208 | ) 209 | 210 | setMethod("qlike", signature(object = "HARForecast"), function(object){ 211 | RM = object@data$forecastComparison #extract observed RM 212 | FV = getForc(object) 213 | qLike = RM/FV - log(RM / FV) - 1 214 | return(qLike) 215 | } 216 | ) 217 | 218 | ###Methods that work with "lm" objects that I thought may be useful. 219 | ###Wrappers from the HARModel to "lm" 220 | setMethod("logLik" , signature(object = "HARModel") , function(object, ...){ 221 | out = logLik(object@model, ...) 222 | return(out) 223 | }) 224 | 225 | setMethod("confint" , signature(object = "HARModel") , function(object, parm, level = 0.95, ...){ 226 | out = confint(object@model, parm = parm, level = level, ...) 227 | return(out) 228 | }) 229 | 230 | setMethod("residuals" , signature(object = "HARModel") , function(object, ...){ 231 | out = residuals(object@model, ...) 232 | return(out) 233 | }) 234 | 235 | setMethod("summary" , signature(object = "HARModel") , function(object, ...){ 236 | out = summary(object@model,...) 237 | out$call = as.name("lm(y ~ x)") 238 | return(out) 239 | }) 240 | 241 | setMethod("fitted.values", signature(object = "HARModel"), function(object, ...){ 242 | out = fitted.values(object@model, ...) 243 | return(out) 244 | }) 245 | -------------------------------------------------------------------------------- /R/HARestimate.R: -------------------------------------------------------------------------------- 1 | HAREstimate = function(RM, BPV = NULL, RQ = NULL, periods = c(1,5,22), periodsJ = NULL, periodsRQ = NULL, 2 | type = "HAR" , insanityFilter = TRUE, h = 1){ 3 | 4 | iT = length(RM) 5 | Info = list() 6 | vImplementedTypes = c("HAR" , "HARJ" , "HARQ" , "HARQ-J", "CHAR", "CHARQ", "TV-HAR") 7 | if(!(type %in% vImplementedTypes)){ 8 | cat("type argument not correctly specifiec or is not implemented, available types are:", paste(dQuote(vImplementedTypes))) 9 | return(NULL) 10 | } 11 | if(length(periodsRQ) > length(periods)){ 12 | stop("periodsRQ cannot be longer than periods") 13 | } 14 | vDates = as.Date((max(periods)+h):iT, origin = "1970/01/01") 15 | if(is(RM,"xts")){ 16 | vDates = index(RM) 17 | vDates = vDates[(max(periods)+h):(iT)] 18 | } 19 | if(h %% 1 != 0 | h < 1){ 20 | stop("h must be a positive integer") 21 | } 22 | 23 | ##### Type: "HAR" - vanilla 24 | if(type == "HAR"){ 25 | mData = HARDataCreationC(RM, periods, h) 26 | coefNames = paste("beta", c(0,periods) , sep="") 27 | Info = list("periods" = periods , "type" = type, "dates" = vDates) 28 | } 29 | ##### Type: "HAR" - vanilla end 30 | 31 | 32 | ##### Type: "HARJ" 33 | if(type == "HARJ"){ 34 | mData = HARDataCreationC(RM, periods, h) 35 | JumpComponent = pmax(RM - BPV,0) 36 | if(is.null(periodsJ)){ 37 | periodsJ = periods 38 | } 39 | mJumpData = HARDataCreationC(JumpComponent , periodsJ, h = h) 40 | mData = HARMatCombine(mA = mData, mB = mJumpData[,-1, drop = FALSE]) 41 | coefNames = c(paste("beta", c(0,periods), sep="") , paste("j" , periodsJ, sep ="")) 42 | 43 | Info = list("periods" = periods , "preiodsJ" = periodsJ , "type" = type, "dates" = vDates) 44 | 45 | 46 | } 47 | ##### Type: "HARJ" end 48 | 49 | ##### Type: "HARQ" 50 | if(type == "HARQ"){ 51 | mData = HARDataCreationC(RM, periods, h) 52 | if(is.null(periodsRQ)){ 53 | periodsRQ = periods 54 | } 55 | if(h!=1 & length(periodsRQ) == 1){ 56 | if(!h %in% periods){ 57 | stop("h is not in periods, that is not allowed as of now when periodsRQ is of length 1") 58 | } 59 | mAuxData = matrix(1, nrow = length(RQ) - 2*h +1, ncol = length(periods)) 60 | mAuxData[,h == periods] = as.matrix(HARDataCreationC(RQ , c(h), h))[,-1] 61 | meanAux = mean(sqrt(RQ)) 62 | mAuxData[, h == periods] = sqrt(mAuxData[,h == periods]) - meanAux 63 | 64 | mData = HARMatCombine(mData, mAuxData[,h == periods, drop = FALSE]) 65 | mData[,-(1:(length(periods) +1))] = mData[,-(1:(length(periods) +1))] * 66 | mData[,c(FALSE, h==periods, rep(FALSE, length(periodsRQ)))] ##interaction term 67 | coefNames = c(paste("beta",c(0,periods), sep="") , paste("beta_q" , h, sep ="")) 68 | }else{ 69 | mAuxData = as.matrix(HARDataCreationC(RQ , periodsRQ, h)) 70 | meanAux = mean(sqrt(RQ)) 71 | mAuxData = sqrt(mAuxData) - meanAux 72 | 73 | mData = HARMatCombine(mData, mAuxData[,-1, drop = FALSE]) 74 | 75 | mData[,-(1:(length(periods) +1))] = mData[,-(1:(length(periods) +1))] * mData[,2:(length(periodsRQ)+1)] ##interaction term 76 | coefNames = c(paste("beta",c(0,periods), sep="") , paste("beta_q" , periodsRQ, sep ="")) 77 | } 78 | 79 | Info = list("periods" = periods , "periodsRQ" = periodsRQ , "type" = type, "dates" = vDates) 80 | 81 | } 82 | ##### Type: "HARQ" end 83 | 84 | ##### Type: "HARQ-J" 85 | if(type == "HARQ-J"){ 86 | mData = HARDataCreationC(RM, periods, h) 87 | JumpComponent = pmax(RM - BPV,0) 88 | if(is.null(periodsRQ)){ 89 | periodsRQ = periods 90 | } 91 | if(is.null(periodsJ)){ 92 | periodsJ = periods 93 | } 94 | 95 | 96 | if(h!=1 & length(periodsRQ) == 1){ 97 | if(!h %in% periods){ 98 | stop("h is not in periods, that is not allowed as of now when periodsRQ is of length 1") 99 | } 100 | mAuxData = matrix(1, nrow = length(RQ) - 2*h +1, ncol = length(periods)) 101 | mAuxData[,h == periods] = as.matrix(HARDataCreationC(RQ , c(h), h))[,-1] 102 | meanAux = mean(sqrt(RQ)) 103 | mAuxData[, h == periods] = sqrt(mAuxData[,h == periods]) - meanAux 104 | 105 | mData = HARMatCombine(mData, mAuxData[,h == periods, drop = FALSE]) 106 | mData[,-(1:(length(periods) +1))] = mData[,-(1:(length(periods) +1))] * 107 | mData[,c(FALSE, h==periods, rep(FALSE, length(periodsRQ)))] ##interaction term 108 | coefNames = c(paste("beta",c(0,periods), sep="") , paste("beta_q" , h, sep ="")) 109 | }else{ 110 | mAuxData = as.matrix(HARDataCreationC(RQ , periodsRQ, h)) 111 | meanAux = mean(sqrt(RQ)) 112 | mAuxData = sqrt(mAuxData) - meanAux 113 | 114 | mData = HARMatCombine(mData, mAuxData[,-1, drop = FALSE]) 115 | 116 | mData[,-(1:(length(periods) +1))] = mData[,-(1:(length(periods) +1))] * mData[,2:(length(periodsRQ)+1)] ##interaction term 117 | coefNames = c(paste("beta",c(0,periods), sep="") , paste("beta_q" , periodsRQ, sep ="")) 118 | } 119 | 120 | 121 | mJumpData = HARDataCreationC(JumpComponent , periodsJ, h) 122 | mData = HARMatCombine(mData, mJumpData[,-1,drop = FALSE]) 123 | 124 | coefNames = c(coefNames, paste("beta_j" , periodsJ , sep = "")) 125 | Info = list("periods" = periods , "periodsRQ" = periodsRQ, "periodsJ" = periodsJ, "type" = type, "dates" = vDates) 126 | 127 | } 128 | #####Type: "HARQ-J" end 129 | 130 | if(type == "CHAR"){ 131 | mData = cbind(RM[(max(periods)+h):(iT)], HARDataCreationC(BPV, periods, h)[,-1]) #Aggregate the explanatory variables 132 | if(h != 1){ 133 | mData[,1] = HARDataCreationC(RM, periods, h)[,1] #Aggregate the dependent variable too 134 | } 135 | coefNames = paste("beta", c(0,periods) , sep="") 136 | Info = list("periods" = periods , "type" = type, "dates" = vDates) 137 | 138 | }#####Type: "CHAR" end 139 | 140 | ##### Type: "CHARQ" - BPQ 141 | if(type == "CHARQ"){ 142 | mData = cbind(RM[(max(periods)+h):(iT)], HARDataCreationC(BPV, periods, h)[,-1]) 143 | mAuxData = as.matrix(HARDataCreationC(RQ , periodsRQ, h)) 144 | meanAux = mean(sqrt(RQ)) 145 | mAuxData = sqrt(mAuxData) - meanAux 146 | 147 | mData = HARMatCombine(mData, mAuxData[,-1, drop = FALSE]) 148 | mData[,-(1:(length(periods) +1))] = mData[,-(1:(length(periods) +1))] * mData[,2:(length(periodsRQ)+1)] 149 | 150 | 151 | coefNames = c(paste("beta",c(0,periods), sep="") , paste("beta_q" , periodsRQ, sep ="")) 152 | Info = list("Lags" = periods , "RQLags" = periodsRQ , "type" = type, "dates" = vDates) 153 | 154 | 155 | }####Type: "CHARQ" - end 156 | 157 | ####Type: "TV-HAR" 158 | if(type == "TV-HAR"){ 159 | mData = HARDataCreationC(RM, periods, h) 160 | mData = cbind(mData[,1], mData[,2] , abs(mData[,2] - mData[,ncol(mData)]) * mData[,2], mData[,3:ncol(mData)]) 161 | coefNames = c("beta", "gamma", "alpha", paste("beta", periods[-1] , sep="")) 162 | Info = list("Lags" = periods , "type" = type, "dates" = vDates) 163 | }####Type: "TV-HAR" -end 164 | 165 | model = lm(mData[,1] ~ mData[,-1]) 166 | if(insanityFilter){ 167 | model$fitted.values = HARinsanityFilter(model$fitted.values , 0 , max(mData[,1]) , mean(mData[,1]) ) 168 | } 169 | names(model$coefficients) = coefNames 170 | Info$h = h 171 | HARModel = new("HARModel" , "model" = model ,"info" = Info) 172 | 173 | return(HARModel) 174 | 175 | } 176 | 177 | 178 | #######Fast estimation routine which returns only the coefficients, it is used for forecasting and cuts down the time a lot. 179 | #######These functions are undocumented and not exported 180 | 181 | FASTHARestimate = function(RM , periods, h = 1){ 182 | 183 | mData = HARDataCreationC(RM , periods, h) 184 | vCoef = fastLMcoef(cbind(1,mData[-nrow(mData),-1]) , mData[-nrow(mData),1]) 185 | #leave the last row out of the estimation and pass it back to form the forecast 186 | return(list("coefficients" = vCoef, "mData" = mData)) 187 | } 188 | 189 | FASTHARJestimate = function(RM, JumpComponent, periods, periodsJ, h = 1 ){ 190 | mData = HARDataCreationC(RM , periods, h) 191 | 192 | mJumpData = HARDataCreationC(JumpComponent , periodsJ, h) 193 | 194 | mData = HARMatCombine(mA = mData, mB = mJumpData[,-1, drop = FALSE]) 195 | vCoef = fastLMcoef(cbind(1,mData[-nrow(mData),-1]) , mData[-nrow(mData),1]) 196 | #leave the last row out of the estimation and pass it back to form the forecast 197 | return(list("coefficients" = vCoef, "mData" = mData)) 198 | 199 | } 200 | 201 | FASTHARQestimate =function(RM, RQ, periods, periodsRQ = NULL, h = 1){ 202 | if(is.null(periodsRQ)){ 203 | periodsRQ = periods 204 | } 205 | 206 | mData = HARDataCreationC(RM , periods , h) 207 | 208 | if(h!=1 & length(periodsRQ) == 1){ 209 | mAuxData = matrix(1, nrow = length(RQ) - 2*h +1, ncol = length(periods)) 210 | mAuxData[,h == periods] = as.matrix(HARDataCreationC(RQ , c(h), h))[,-1] 211 | meanAux = mean(sqrt(RQ)) 212 | mAuxData[, h == periods] = sqrt(mAuxData[,h == periods]) - meanAux 213 | 214 | mData = HARMatCombine(mData, mAuxData[,h == periods, drop = FALSE]) 215 | mData[,-(1:(length(periods) +1))] = mData[,-(1:(length(periods) +1))] * 216 | mData[,c(FALSE, h==periods, rep(FALSE, length(periodsRQ)))] ##interaction term 217 | 218 | }else{ 219 | mAuxData = as.matrix(HARDataCreationC(RQ , periodsRQ, h)) 220 | meanAux = mean(sqrt(RQ)) 221 | mAuxData = sqrt(mAuxData) - meanAux 222 | 223 | mData = HARMatCombine(mData, mAuxData[,-1, drop = FALSE]) 224 | 225 | mData[,-(1:(length(periods) +1))] = mData[,-(1:(length(periods) +1))] * mData[,2:(length(periodsRQ)+1)] ##interaction term 226 | 227 | } 228 | 229 | vCoef = fastLMcoef(cbind(1,mData[-nrow(mData),-1]) , mData[-nrow(mData),1]) 230 | #leave the last row out of the estimation and pass it back to form the forecast 231 | return(list("coefficients" = vCoef, "mData" = mData)) 232 | 233 | } 234 | 235 | 236 | FASTHARQJestimate = function(RM , RQ , JumpComponent , periods , periodsRQ , periodsJ, h = 1){ 237 | mData = HARDataCreationC(RM , periods, h) 238 | mJumpData = HARDataCreationC(JumpComponent , periodsJ, h) 239 | if(h!=1 & length(periodsRQ) == 1){ 240 | mAuxData = matrix(1, nrow = length(RQ) - 2*h +1, ncol = length(periods)) 241 | mAuxData[,h == periods] = as.matrix(HARDataCreationC(RQ , c(h), h))[,-1] 242 | meanAux = mean(sqrt(RQ)) 243 | mAuxData[, h == periods] = sqrt(mAuxData[,h == periods]) - meanAux 244 | 245 | mData = HARMatCombine(mData, mAuxData[,h == periods, drop = FALSE]) 246 | mData[,-(1:(length(periods) +1))] = mData[,-(1:(length(periods) +1))] * 247 | mData[,c(FALSE, h==periods, rep(FALSE, length(periodsRQ)))] ##interaction term 248 | 249 | }else{ 250 | mAuxData = as.matrix(HARDataCreationC(RQ , periodsRQ, h)) 251 | meanAux = mean(sqrt(RQ)) 252 | mAuxData = sqrt(mAuxData) - meanAux 253 | 254 | mData = HARMatCombine(mData, mAuxData[,-1, drop = FALSE]) 255 | 256 | mData[,-(1:(length(periods) +1))] = mData[,-(1:(length(periods) +1))] * mData[,2:(length(periodsRQ)+1)] ##interaction term 257 | 258 | } 259 | 260 | mData = HARMatCombine(mData, mJumpData[,-1,drop = FALSE]) 261 | 262 | 263 | vCoef = fastLMcoef(cbind(1,mData[-nrow(mData),-1]) , mData[-nrow(mData),1]) 264 | #leave the last row out of the estimation and pass it back to form the forecast 265 | return(list("coefficients" = vCoef, "mData" = mData)) 266 | 267 | } 268 | 269 | 270 | FASTCHARestimate = function(RM, BPV, periods, iT, h = 1){ 271 | mData = cbind(RM[(max(periods)+1):(iT)], HARDataCreationC(BPV, periods, h)[,-1]) 272 | vCoef = fastLMcoef(cbind(1,mData[-nrow(mData),-1]) , mData[-nrow(mData),1]) 273 | #leave the last row out of the estimation and pass it back to form the forecast 274 | return(list("coefficients" = vCoef, "mData" = mData)) 275 | } 276 | 277 | 278 | 279 | FASTCHARQestimate = function(RM, BPV, RQ, periods, periodsRQ, iT, h = 1){ 280 | mData = cbind(RM[(max(periods)+1):(iT)], HARDataCreationC(BPV, periods, h)[,-1]) 281 | if(h!=1 & length(periodsRQ) == 1){ 282 | mAuxData = matrix(1, nrow = length(RQ) - 2*h +1, ncol = length(periods)) 283 | mAuxData[,h == periods] = as.matrix(HARDataCreationC(RQ , c(h), h))[,-1] 284 | meanAux = mean(sqrt(RQ)) 285 | mAuxData[, h == periods] = sqrt(mAuxData[,h == periods]) - meanAux 286 | 287 | mData = HARMatCombine(mData, mAuxData[,h == periods, drop = FALSE]) 288 | mData[,-(1:(length(periods) +1))] = mData[,-(1:(length(periods) +1))] * 289 | mData[,c(FALSE, h==periods, rep(FALSE, length(periodsRQ)))] ##interaction term 290 | 291 | }else{ 292 | mAuxData = as.matrix(HARDataCreationC(RQ , periodsRQ, h)) 293 | meanAux = mean(sqrt(RQ)) 294 | mAuxData = sqrt(mAuxData) - meanAux 295 | 296 | mData = HARMatCombine(mData, mAuxData[,-1, drop = FALSE]) 297 | 298 | mData[,-(1:(length(periods) +1))] = mData[,-(1:(length(periods) +1))] * mData[,2:(length(periodsRQ)+1)] ##interaction term 299 | 300 | } 301 | vCoef = fastLMcoef(cbind(1,mData[-nrow(mData),-1]) , mData[-nrow(mData),1]) 302 | #leave the last row out of the estimation and pass it back to form the forecast 303 | return(list("coefficients" = vCoef, "mData" = mData)) 304 | 305 | } 306 | 307 | 308 | 309 | FASTTVHARestimate = function(RM, periods, h = 1){ 310 | 311 | mData = HARDataCreationC(RM , periods, h) 312 | mData = cbind(mData[,1], mData[,2] , abs(mData[,2] - mData[,ncol(mData)]) * mData[,2], mData[,3:ncol(mData)]) 313 | vCoef = fastLMcoef(cbind(1, mData[-nrow(mData),-1]) , mData[-nrow(mData),1]) 314 | #leave the last row out of the estimation and pass it back to form the forecast 315 | return(list("coefficients" = vCoef, "mData" = mData)) 316 | 317 | } 318 | 319 | HARinsanityFilter = function(vY , dL, dU , Replacement){ 320 | vIndex = (vY
dU) 321 | vY[vIndex] = Replacement 322 | return(vY) 323 | } 324 | 325 | -------------------------------------------------------------------------------- /R/HARForecast.R: -------------------------------------------------------------------------------- 1 | HARForecast = function(RM, BPV = NULL, RQ = NULL , periods = c(1,5,22) , 2 | periodsJ = NULL, periodsRQ = NULL, nRoll=10 , nAhead=1 , type = "HAR", windowType = "rolling", 3 | insanityFilter = TRUE, h = 1){ 4 | FCstart.time = Sys.time() 5 | ######Initialization section ###### 6 | iT = length(RM) 7 | iLags = length(periods) 8 | iLagsPlusOne = iLags+1 9 | iLagsMax = max(periods) 10 | vObservations = RM[(iLagsMax+1):(iT-nRoll)] 11 | vForecastComp = RM[(iT-nRoll+1):iT] 12 | vDates = as.Date((iLagsMax+1):(iT-nRoll), origin = "1970/01/01") 13 | vForecastDates = as.Date((iT-nRoll+1):iT, origin = "1970/01/01") 14 | vRollingSynonyms = c("rolling","Rolling", "fixed", "Fixed", "RW", "rw") 15 | vIncreasingSynonyms = c("increasing","Increasing", "IW", "iw", "expanding", "ew", "EW") 16 | lFit = list() 17 | if(!(windowType %in% c(vRollingSynonyms, vIncreasingSynonyms))){ 18 | warning(paste("windowType", windowType, "not in synonyms of windowtypes, thus it is set to rolling.")) 19 | windowType = "rolling" 20 | } 21 | 22 | if(is(RM,"xts")){ 23 | vDates = index(RM) 24 | vDates = vDates[(max(periods)+1):(iT-nRoll)] 25 | vForecastDates = index(vForecastComp) 26 | } 27 | if(h != 1){ 28 | vForecastComp = HARDataCreationC(RM, periods, h = h)[-(1:(iT - nRoll - iLagsMax-h+1)),1] 29 | 30 | 31 | } 32 | 33 | ######Initialization end ####### 34 | ######Checks section ####### 35 | if(nRoll > (length(RM) + iLagsMax)) { 36 | stop("The amount of rolling forecasts cannot be greater the length of the Realized measure vector 37 | plus the maximum lag.") 38 | } 39 | 40 | vImplementedTypes = c("HAR" , "HARJ" , "HARQ" , "HARQ-J", "CHAR", "CHARQ", "TV-HAR") 41 | 42 | if(!any(grepl(type, vImplementedTypes))){ 43 | cat("type argument not correctly specifiec or is not implemented, available types are:", 44 | paste(dQuote(vImplementedTypes))) 45 | return(NULL) 46 | } 47 | if(length(periodsRQ) > length(periods)){ 48 | stop("periodsRQ cannot be longer than periods") 49 | } 50 | if(h %% 1 != 0 | h < 1){ 51 | stop("h must be a positive integer") 52 | } 53 | if(type %in% c("HARQ", "HARQ-J", "CHARQ")){ 54 | if(h !=1 & length(periodsRQ) == 1){ 55 | if(!h %in% periods){ 56 | stop("h is not in periods, that is not allowed as of now when periodsRQ is of length 1") 57 | } 58 | } 59 | } 60 | if(nAhead > 1 && h!=1){ 61 | stop("More than 1 step ahead forecasts when h>1 have not been implemented, and currently I don't plan on doing it.\n 62 | Feel free to implement it yourself and send the code to me.") 63 | } 64 | ###### Checks end ####### 65 | 66 | ######Forecasting ####### 67 | ### type: "HAR" 68 | if(type == "HAR"){ 69 | mForecast = matrix(0 , nrow = nAhead , ncol = nRoll) 70 | if(nAhead == 1){ 71 | 72 | for (j in 1:nRoll) { 73 | if(windowType %in% vRollingSynonyms){ 74 | lFit = FASTHARestimate(RM[j:(iT-nRoll+j)], periods, h = h) 75 | }else{ 76 | lFit = FASTHARestimate(RM[1:(iT-nRoll+j)], periods, h = h) 77 | } 78 | mData = lFit$mData[,-1] 79 | vCoef = lFit$coefficients 80 | mForecast[1,j] = vCoef[1] + sum(vCoef[-1]*mData[nrow(mData),]) 81 | #Creates the j'th 1-step ahead forecast 82 | } # End loop 83 | }# End one-step ahead conditionals 84 | else{ 85 | for (j in 1:(nRoll)){ 86 | if(windowType %in% vRollingSynonyms){ 87 | vThisRoll = as.numeric(RM[j:(iT-nRoll+j)]) #pass as.numeric 88 | } 89 | if(windowType %in% vIncreasingSynonyms){ 90 | vThisRoll = as.numeric(RM[1:(iT-nRoll+j)]) #pass as.numeric 91 | } 92 | lFit = FASTHARestimate(vThisRoll , periods) 93 | mData = lFit$mData[,-1] 94 | vCoef = lFit$coefficients 95 | #Creates the j'th 1-step ahead forecast 96 | mForecast[1,j] = vCoef[1] + sum(vCoef[-1]*mData[nrow(mData),]) 97 | for (i in 2:(min((iLagsMax), nAhead))) { 98 | vForecastfoo = c(vThisRoll[(iT-nRoll-iLagsMax+i) : (iT-nRoll+1)] , mForecast[1:(i-1) , j]) 99 | #Gets the data necessary to form the forecast in one vector. 100 | vLastrowdata = HARDataCreationC(vForecastfoo[(length(vForecastfoo) - iLagsMax):length(vForecastfoo)], 101 | periods) 102 | #Creates the j'th i-step ahead forecast 103 | mForecast[i,j] = vCoef[1] + sum(vCoef[-1]*vLastrowdata[-1]) 104 | } #end first nested for-loop 105 | if(nAhead>iLagsMax){ 106 | for (i in (iLagsMax+1):(nAhead)) { 107 | vForecastfoo = mForecast[(i-iLagsMax):i , j] 108 | vLastrowdatafoo = HARDataCreationC(vForecastfoo , periods) 109 | #Gets the data necessary to form the forecast in one vector. 110 | mForecast[i,j] = vCoef[1] + sum(vCoef[-1]*vLastrowdatafoo[-1]) 111 | #Creates the j'th i-step ahead forecast 112 | } #End second nested for-loop 113 | } 114 | 115 | } #end for-loop 116 | } 117 | 118 | }# type: "HAR" end 119 | 120 | # type: "HARJ" end 121 | if(type == "HARJ"){ 122 | JumpComponent = pmax(RM - BPV , 0) 123 | if(is.null(periodsJ)){ # check if periodsJ is provided 124 | cat("\nJump Lags not provided, changed to match periods") 125 | periodsJ = periods 126 | } 127 | if(max(periods) < max(periodsJ)){ 128 | cat("\nHigher maximum value of jump lag vector than RV lag vector is unfortunately not 129 | implemented in forecasting yet. periodsJ is set to periods") 130 | periodsJ = periods 131 | } 132 | iMaxJumpLags = max(periodsJ) 133 | iJumpLags = length(periodsJ) 134 | iJumpLagsPlusOne = iJumpLags+1 135 | mForecast = matrix(0 , nrow = nAhead , ncol = nRoll) 136 | if(nAhead == 1){ 137 | for (j in 1:(nRoll)) { 138 | if(windowType %in% vRollingSynonyms){ 139 | lFit = FASTHARJestimate(RM[j:(iT-nRoll+j)], JumpComponent[j:(iT-nRoll+j)], 140 | periods , periodsJ, h = h) 141 | } 142 | if(windowType %in% vIncreasingSynonyms){ 143 | lFit = FASTHARJestimate(RM[1:(iT-nRoll+j)], JumpComponent[1:(iT-nRoll+j)], 144 | periods , periodsJ, h = h) 145 | } 146 | #Extracts the coefficients of the model 147 | mData = lFit$mData[,-1] 148 | vCoef = lFit$coefficients 149 | mForecast[1,j] = vCoef[1] + sum(vCoef[-1]*mData[dim(mData)[1], ]) 150 | if(insanityFilter){ 151 | if(windowType %in% vRollingSynonyms){ 152 | mForecast[,j] = HARinsanityFilter(mForecast[,j], 0, 153 | max(lFit$mData[, 1]), 154 | mean(lFit$mData[,1])) 155 | } 156 | if(windowType %in% vIncreasingSynonyms){ 157 | mForecast[,j] = HARinsanityFilter(mForecast[,j], 0, 158 | max(lFit$mData[,1]), 159 | mean(lFit$mData[,1])) 160 | } 161 | } # end insanityFilter conditional 162 | #Creates the j'th 1-step ahead forecast 163 | } # End loop 164 | } 165 | else{ 166 | mJumpForecast = matrix(0, nrow = nAhead, ncol = nRoll) 167 | for (j in 1:nRoll) { 168 | #Creates the j'th 1-step ahead forecast for both the realized measure and the jump component. 169 | if(windowType %in% vRollingSynonyms){ 170 | vThisRoll = as.numeric(RM[j:(iT-nRoll+j)]) #pass as.numeric 171 | vThisRollJump = as.numeric(JumpComponent[j:(iT-nRoll+j)]) 172 | } 173 | if(windowType %in% vIncreasingSynonyms){ 174 | vThisRoll = as.numeric(RM[1:(iT-nRoll+j)]) 175 | vThisRollJump = as.numeric(JumpComponent[1:(iT-nRoll+j)]) 176 | } 177 | lFit = FASTHARJestimate(vThisRoll, vThisRollJump , periods , periodsJ) 178 | mJumpFoo = HARDataCreationC(vThisRollJump , c(1)) 179 | dJumpY = JumpComponent[(iT-nRoll+j-1)] 180 | lJumpFit = fastLMcoef(cbind(1,mJumpFoo[,2]) , mJumpFoo[,1]) 181 | dAlpha = lJumpFit[1] 182 | dBeta = lJumpFit[2] 183 | dMu = dAlpha/(1-dBeta) 184 | mJumpForecast[1,j] = dMu + dBeta*(dJumpY - dMu) 185 | mData = lFit$mData[,-1] 186 | vCoef = lFit$coefficients 187 | mForecast[1,j] = vCoef[1] + sum(vCoef[-1]*mData[dim(mData)[1], ]) 188 | 189 | for (i in 2:(min((iLagsMax), nAhead))) { 190 | vForecastfoo = c(vThisRoll[(iT-nRoll-iLagsMax+i) : (iT-nRoll+1)] , mForecast[1:(i-1) , j]) 191 | vJumpForecastfoo = c(vThisRollJump[(iT-nRoll-iLagsMax+i) : (iT-nRoll+1)] , mJumpForecast[1:(i-1),j]) 192 | mJumpForecast[i,j] = dMu + (dBeta^i)*(dJumpY - dMu) 193 | vLastrowdata = HARDataCreationC(vForecastfoo[(length(vForecastfoo) - 194 | iLagsMax):length(vForecastfoo)] 195 | , periods) 196 | vLastrowJumpdata = HARDataCreationC(vJumpForecastfoo[(length(vJumpForecastfoo) - 197 | iMaxJumpLags):length(vJumpForecastfoo)], 198 | periodsJ) 199 | mForecast[i,j] = vCoef[1] + sum(vCoef[-1] * 200 | c(vLastrowdata[-1], 201 | vLastrowJumpdata[-1])) 202 | #Creates the j'th i-step ahead forecast 203 | 204 | } #end first nested for-loop 205 | if(nAhead>iLagsMax){ 206 | for (i in (iLagsMax+1):(nAhead)) { 207 | vForecastfoo = mForecast[(i-iLagsMax):i , j] ## Fix so the size stays the same. 208 | vJumpForecastfoo = mJumpForecast[(i-iLagsMax):i,j] 209 | mJumpForecast[i,j] = dMu + (dBeta^i)*(dJumpY - dMu) 210 | vLastrowdatafoo = HARDataCreationC(vForecastfoo , periods) 211 | vLastrowJumpdata = HARDataCreationC(vJumpForecastfoo[(length(vJumpForecastfoo) - 212 | iMaxJumpLags):length(vJumpForecastfoo)], 213 | periodsJ) 214 | mForecast[i,j] = vCoef[1] + sum(vCoef[-1]*c(vLastrowdata[-1], 215 | vLastrowJumpdata[-1])) 216 | #Creates the j'th i-step ahead forecast 217 | } #End second nested for-loop 218 | } 219 | if(insanityFilter){ 220 | mForecast[,j] = HARinsanityFilter(mForecast[,j] , 0 , max(vThisRoll) , sum(vThisRoll)/length(vThisRoll)) 221 | } # end insanityFilter conditional 222 | } #end for-loop 223 | } 224 | 225 | }#type: "HARJ" end 226 | 227 | if(type == "HARQ"){ 228 | if(is.null(RQ)){ 229 | stop("Auxiliary data must be proveded as the RQ input") 230 | } 231 | if(is.null(periodsRQ)){ 232 | periodsRQ = periods 233 | } 234 | if(max(periods) < max(periodsRQ)){ 235 | cat("\nHigher maximum value of auxiliary lag vector than RV lag vector is unfortunately not 236 | implemented in forecasting yet. periodsRQ is set to periods") 237 | periodsRQ = periods 238 | } 239 | iMaxAuxLags = max(periodsRQ) 240 | mForecast = matrix(0 , nrow = nAhead , ncol = nRoll) 241 | mAuxForecast = matrix(0, nrow = nAhead, ncol = nRoll) 242 | if(nAhead == 1){ 243 | for (j in 1:(nRoll)) { 244 | if(windowType %in% vRollingSynonyms){ 245 | lFit = FASTHARQestimate(RM[j:(iT-nRoll+j)], RQ[j:(iT-nRoll+j)], 246 | periods, periodsRQ, h = h) 247 | } 248 | if(windowType %in% vIncreasingSynonyms){ 249 | lFit = FASTHARQestimate(RM[1:(iT-nRoll+j)], RQ[1:(iT-nRoll+j)], 250 | periods, periodsRQ, h = h) 251 | 252 | } 253 | mData = lFit$mData[,-1] 254 | vCoef = lFit$coefficients 255 | mForecast[1,j] = vCoef[1] + sum(vCoef[-1]*mData[dim(mData)[1] ,]) 256 | if(insanityFilter){ 257 | if(windowType %in% vRollingSynonyms){ 258 | mForecast[,j] = HARinsanityFilter(mForecast[,j], 0, 259 | max(lFit$mData[,1]), 260 | mean(lFit$mData[,1])) 261 | } 262 | if(windowType %in% vIncreasingSynonyms){ 263 | mForecast[,j] = HARinsanityFilter(mForecast[,j], 0, 264 | max(lFit$mData[,1]), 265 | mean(lFit$mData[,1])) 266 | } 267 | } # end insanityFilter conditional 268 | #Creates the j'th 1-step ahead forecast 269 | } # End loop 270 | }# End one-step ahead conditionals 271 | else{ 272 | for (j in 1:(nRoll)) { 273 | if(windowType %in% vRollingSynonyms){ 274 | vThisRoll = as.numeric(RM[j:(iT-nRoll+j)]) 275 | vThisRollRQ = as.numeric(RQ[j:(iT-nRoll+j)]) 276 | } 277 | if(windowType %in% vIncreasingSynonyms){ 278 | vThisRoll = as.numeric(RM[1:(iT-nRoll+j)]) 279 | vThisRollRQ = as.numeric(RQ[1:(iT-nRoll+j)]) 280 | } 281 | lFit = FASTHARQestimate(vThisRoll, vThisRollRQ, periods, periodsRQ) 282 | mAuxFoo = HARDataCreationC(vThisRollRQ , c(1)) 283 | dAuxY = sqrt(RQ[(iT-nRoll+j-1)]) #remember square root 284 | lAuxFit = fastLMcoef(cbind(1,sqrt(mAuxFoo[,2])),sqrt(mAuxFoo[,1])) 285 | dAlpha = lAuxFit[1] 286 | dBeta = lAuxFit[2] 287 | dMu = dAlpha/(1 - dBeta) 288 | 289 | mAuxForecast[1,j]= dMu + dBeta * (dAuxY - dMu) 290 | mData = lFit$mData[,-1] 291 | vCoef = lFit$coefficients 292 | #Creates the j'th 1-step ahead forecast 293 | mForecast[1,j] = vCoef[1] + sum(vCoef[-1]*mData[dim(mData)[1] ,]) 294 | 295 | for (i in 2:(min((iLagsMax), nAhead))) { 296 | 297 | vForecastfoo = c(vThisRoll[(iT-nRoll-iLagsMax+i) : (iT-nRoll+1)] , mForecast[1:(i-1) , j]) 298 | vForecastAuxFoo = c(sqrt(vThisRollRQ[(iT-nRoll-iLagsMax+i) : (iT-nRoll+1)]), 299 | mAuxForecast[1:(i-1) , j]) 300 | #Gets the data necessary to form the forecast in one vector. 301 | vLastrowdata = HARDataCreationC(vForecastfoo[(length(vForecastfoo) - 302 | iLagsMax):length(vForecastfoo)] 303 | , periods) 304 | vLastrowAuxdata = HARDataCreationC(vForecastAuxFoo[(length(vForecastAuxFoo) - 305 | iMaxAuxLags) : length(vForecastAuxFoo)] 306 | , periodsRQ) 307 | #Creates the j'th i-step ahead forecast 308 | mAuxForecast[i,j] = dMu + (dBeta^i)*(dAuxY - dMu) 309 | mForecast[i,j] = vCoef[1] + sum(vCoef[-1]* c(vLastrowdata[-1] , vLastrowAuxdata[-1])) 310 | 311 | } #end first nested for-loop 312 | if(nAhead>iLagsMax){ 313 | for (i in (iLagsMax+1):(nAhead)) { 314 | vForecastfoo = mForecast[(i-iLagsMax):i , j] 315 | vForecastAuxFoo = mAuxForecast[(i-iLagsMax):i, j] 316 | #Gets the data necessary to form the forecast in one vector. 317 | vLastrowdata = HARDataCreationC(vForecastfoo[(length(vForecastfoo) - 318 | iLagsMax) : length(vForecastfoo)], 319 | periods) 320 | vLastrowAuxdata = HARDataCreationC(vForecastAuxFoo[(length(vForecastAuxFoo) - 321 | iMaxAuxLags) : length(vForecastAuxFoo)], 322 | periodsRQ) 323 | mAuxForecast[i,j] = dMu + (dBeta^i)*(dAuxY - dMu) 324 | 325 | #Gets the data necessary to form the forecast in one vector. 326 | 327 | mForecast[i,j] = vCoef[1] + sum(vCoef[-1]* c(vLastrowdata[-1] , vLastrowAuxdata[,-1])) 328 | 329 | #Creates the j'th i-step ahead forecast 330 | } #End second nested for-loop 331 | } 332 | if(insanityFilter){ 333 | mForecast[,j] = HARinsanityFilter(mForecast[,j] , 0 , max(vThisRoll) , sum(vThisRoll)/length(vThisRoll)) 334 | } # end insanityFilter conditional 335 | } #end for-loop 336 | } 337 | 338 | }#type: "HARQ" end 339 | 340 | if(type == "HARQ-J"){ 341 | JumpComponent = pmax(RM - BPV , 0) 342 | if(is.null(RQ)){ 343 | stop("Auxiliary data must be proveded as the RQ input") 344 | } 345 | if(is.null(periodsJ)){ # check if periodsJ is provided 346 | cat("\nJump Lags not provided, changed to match periods") 347 | periodsJ = periods 348 | } 349 | if(is.null(periodsRQ)){ 350 | periodsRQ = periods 351 | } 352 | if(max(periods) < max(periodsJ)){ 353 | cat("\nHigher maximum value of jump lag vector than RV lag vector is 354 | unfortunately not implemented in forecasting yet. periodsJ is set to periods") 355 | periodsJ = periods 356 | } 357 | if(max(periods) < max(periodsRQ)){ 358 | cat("\nHigher maximum value of auxiliary lag vector than RV lag vector is 359 | unfortunately not implemented in forecasting yet. periodsRQ is set to periods") 360 | periodsJ = periods 361 | } 362 | iMaxAuxLags = max(periodsRQ) 363 | iMaxJumpLags = max(periodsJ) 364 | mJumpForecast = matrix(0 , nrow = nAhead, ncol = nRoll ) 365 | mForecast = matrix(0 , nrow = nAhead , ncol = nRoll) 366 | mAuxForecast = matrix(0, nrow = nAhead, ncol = nRoll) 367 | if(nAhead == 1){ 368 | for (j in 1:(nRoll)) { 369 | if(windowType %in% vRollingSynonyms){ 370 | lFit = FASTHARQJestimate(RM[j:(iT-nRoll+j)], RQ[j:(iT-nRoll+j)], 371 | JumpComponent[j:(iT-nRoll+j)], periods, 372 | periodsRQ,periodsJ, h = h) 373 | } 374 | if(windowType %in% vIncreasingSynonyms){ 375 | lFit = FASTHARQJestimate(RM[1:(iT-nRoll+j)], RQ[1:(iT-nRoll+j)], 376 | JumpComponent[1:(iT-nRoll+j)], periods, 377 | periodsRQ,periodsJ, h = h) 378 | } 379 | mData = lFit$mData[,-1] 380 | vCoef = lFit$coefficients 381 | 382 | mForecast[1,j] = vCoef[1] + sum(vCoef[-1]*mData[dim(mData)[1] ,]) 383 | if(insanityFilter){ 384 | if(windowType %in% vRollingSynonyms){ 385 | mForecast[,j] = HARinsanityFilter(mForecast[,j], 0, 386 | max(lFit$mData[,1]), 387 | mean(lFit$mData[,1])) 388 | } 389 | if(windowType %in% vIncreasingSynonyms){ 390 | mForecast[,j] = HARinsanityFilter(mForecast[,j], 0, 391 | max(lFit$mData[,1]), 392 | mean(lFit$mData[,1])) 393 | } 394 | } # end insanityFilter conditional 395 | #Creates the j'th 1-step ahead forecast 396 | } # End loop 397 | }# End one-step ahead conditionals 398 | else{ 399 | for (j in 1:(nRoll)) { 400 | if(windowType %in% vRollingSynonyms){ 401 | vThisRoll = as.numeric(RM[j:(iT-nRoll+j)]) 402 | vThisRollRQ = as.numeric(RQ[j:(iT-nRoll+j)]) 403 | vThisRollJump = as.numeric(JumpComponent[j:(iT-nRoll+j)]) 404 | } else{ 405 | vThisRoll = as.numeric(RM[1:(iT-nRoll+j)]) 406 | vThisRollRQ = as.numeric(RQ[1:(iT-nRoll+j)]) 407 | vThisRollJump = as.numeric(JumpComponent[1:(iT-nRoll+j)]) 408 | } 409 | mJumpFoo = HARDataCreationC(vThisRollJump , c(1)) 410 | dJumpY = JumpComponent[(iT-nRoll+j-1)] 411 | lJumpFit = fastLMcoef(cbind(1,mJumpFoo[,2]) ,mJumpFoo[,1]) 412 | dJumpAlpha = lJumpFit[1] 413 | dJumpBeta = lJumpFit[2] 414 | dJumpMu = dJumpAlpha/(1-dJumpBeta) 415 | lFit = FASTHARQJestimate(vThisRoll, vThisRollRQ, vThisRollJump, 416 | periods, periodsRQ, periodsJ) 417 | mAuxFoo = HARDataCreationC(vThisRollRQ , c(1)) 418 | dAuxY = sqrt(RQ[(iT-nRoll+j-1)]) 419 | lAuxFit = fastLMcoef(cbind(1,sqrt(mAuxFoo[,2])), sqrt(mAuxFoo[,1])) 420 | dAuxAlpha = lAuxFit[1] 421 | dAuxBeta = lAuxFit[2] 422 | dAuxMu = dAuxAlpha/(1 - dAuxBeta) 423 | mJumpForecast[1,j] = dJumpMu + dJumpBeta*(dJumpY - dJumpMu) 424 | mAuxForecast[1,j] = dAuxMu + dAuxBeta * (dAuxY - dAuxMu) 425 | mData = lFit$mData[,-1] 426 | vCoef = lFit$coefficients 427 | #Creates the j'th 1-step ahead forecast 428 | mForecast[1,j] = vCoef[1] + sum(vCoef[-1]*mData[dim(mData)[1] ,]) 429 | 430 | for (i in 2:(min((iLagsMax), nAhead))) { 431 | 432 | vForecastfoo = c(vThisRoll[(iT-nRoll-iLagsMax+i) : (iT-nRoll+1)] , mForecast[1:(i-1) , j]) 433 | vForecastAuxFoo = c(sqrt(vThisRollRQ[(iT-nRoll-iLagsMax+i) : (iT-nRoll+1)]), 434 | mAuxForecast[1:(i-1) , j]) 435 | vJumpForecastfoo = c(vThisRollJump[(iT-nRoll-iLagsMax+i) : (iT-nRoll+1)], 436 | mJumpForecast[1:(i-1)],j) 437 | vLastrowJumpdata = HARDataCreationC(vJumpForecastfoo[(length(vJumpForecastfoo) - 438 | iMaxJumpLags) : length(vJumpForecastfoo)], 439 | periodsJ) 440 | #Gets the data necessary to form the forecast in one vector. 441 | vLastrowdata = HARDataCreationC(vForecastfoo[(length(vForecastfoo) - 442 | iLagsMax):length(vForecastfoo)] , periods) 443 | vLastrowAuxdata = HARDataCreationC(vForecastAuxFoo[(length(vForecastAuxFoo) - 444 | iMaxAuxLags):length(vForecastAuxFoo)], 445 | periodsRQ) 446 | #Creates the j'th i-step ahead forecast 447 | 448 | mAuxForecast[i,j] = dAuxMu + (dAuxBeta^i)*(dAuxY - dAuxMu) 449 | mJumpForecast[i,j]= dJumpMu + (dJumpBeta^i)*(dJumpY - dJumpMu) 450 | mForecast[i,j] = vCoef[1] + sum(vCoef[-1]* c(vLastrowdata[-1] , 451 | vLastrowAuxdata[-1] , 452 | vLastrowJumpdata[-1])) 453 | 454 | } #end first nested for-loop 455 | if(nAhead>iLagsMax){ 456 | for (i in (iLagsMax+1):(nAhead)) { 457 | vForecastfoo = mForecast[(i-iLagsMax):i , j] 458 | vForecastAuxFoo = mAuxForecast[(i-iLagsMax):i, j] 459 | vJumpForecastfoo = mJumpForecast[(i-iLagsMax):i, j] 460 | vLastrowJumpdata = HARDataCreationC(vJumpForecastfoo[(length(vJumpForecastfoo) 461 | - iMaxJumpLags) : length(vJumpForecastfoo)], 462 | periodsJ) 463 | #data preparation 464 | vLastrowdata = HARDataCreationC(vForecastfoo[(length(vForecastfoo) - 465 | iLagsMax) : length(vForecastfoo)] 466 | , periods) 467 | vLastrowAuxdata = HARDataCreationC(vForecastAuxFoo[(length(vForecastAuxFoo) - 468 | iMaxAuxLags) : length(vForecastAuxFoo)] , 469 | periodsRQ) 470 | 471 | 472 | #Creates the j'th i-step ahead forecast 473 | mJumpForecast[i,j]= dJumpMu + (dJumpBeta^i)*(dJumpY - dJumpMu) 474 | mAuxForecast[i,j] = dAuxMu + (dAuxBeta^i)*(dAuxY - dAuxMu) 475 | mForecast[i,j] = vCoef[1] + sum(vCoef[-1]* c(vLastrowdata[-1], 476 | vLastrowAuxdata[,-1], 477 | vLastrowJumpdata[-1])) 478 | 479 | } #End second nested for-loop 480 | } 481 | if(insanityFilter){ 482 | mForecast[,j] = HARinsanityFilter(mForecast[,j] , 0 , max(vThisRoll) , sum(vThisRoll)/length(vThisRoll)) 483 | } # end insanityFilter conditional 484 | } #end for-loop 485 | } 486 | 487 | 488 | 489 | }#type: "HARQ-J" end 490 | 491 | if(type == "CHAR"){ 492 | mForecast = matrix(0 , nrow = nAhead , ncol = nRoll) 493 | mBPVForecast = matrix(0, nrow = nAhead, ncol = nRoll) 494 | iN = iT-nRoll+1 #Used for fast CHAR estimation, need better name for it tho 495 | if(nAhead == 1){ 496 | for (j in 1:(nRoll)) { 497 | if(windowType %in% vRollingSynonyms){ 498 | lFit = FASTCHARestimate(RM[j:(iT-nRoll+j)], BPV[j:(iT-nRoll+j)], 499 | periods, iN, h = h) 500 | } 501 | if(windowType %in% vIncreasingSynonyms){ 502 | lFit = FASTCHARestimate(RM[1:(iT-nRoll+j)], BPV[1:(iT-nRoll+j)], 503 | periods, iN + j -1, h = h) 504 | } 505 | mData = lFit$mData[,-1] 506 | vCoef = lFit$coefficients 507 | mForecast[1,j] = vCoef[1] + sum(vCoef[-1]*mData[dim(mData)[1] ,]) 508 | if(insanityFilter){ 509 | if(windowType %in% vRollingSynonyms){ 510 | mForecast[,j] = HARinsanityFilter(mForecast[,j], 0, 511 | max(lFit$mData[,1]), 512 | mean(lFit$mData[,1])) 513 | } 514 | if(windowType %in% vIncreasingSynonyms){ 515 | mForecast[,j] = HARinsanityFilter(mForecast[,j], 0, 516 | max(lFit$mData[,1]), 517 | mean(lFit$mData[,1])) 518 | } 519 | } # end insanityFilter conditional 520 | #Creates the j'th 1-step ahead forecast 521 | } # End loop 522 | }# End one-step ahead conditionals 523 | else{ 524 | for (j in 1:(nRoll)) { 525 | if(windowType %in% vRollingSynonyms){ 526 | vThisRoll = as.numeric(RM[j:(iT-nRoll+j)]) 527 | vThisRollBPV = as.numeric(BPV[j:(iT-nRoll+j)]) 528 | } 529 | if(windowType %in% vIncreasingSynonyms){ 530 | vThisRoll = as.numeric(RM[1:(iT-nRoll+j)]) 531 | vThisRollBPV = as.numeric(BPV[1:(iT-nRoll+j)]) 532 | iN = iT-nRoll+j 533 | } 534 | lFit = FASTCHARestimate(vThisRoll, vThisRollBPV, periods, iN) 535 | mBPVFoo = HARDataCreationC(vThisRollBPV , c(1)) 536 | dBPVY = BPV[(iT-nRoll+j-1)] 537 | lBPVFit = fastLMcoef(cbind(1,mBPVFoo[,2]),mBPVFoo[,1]) 538 | dAlpha = lBPVFit[1] 539 | dBeta = lBPVFit[2] 540 | dMu = dAlpha/(1 - dBeta) 541 | mBPVForecast[1,j]= dMu + dBeta * (dBPVY - dMu) 542 | mData = lFit$mData[,-1] 543 | vCoef = lFit$coefficients 544 | #Creates the j'th 1-step ahead forecast 545 | mForecast[1,j] = vCoef[1] + sum(vCoef[-1]*mData[dim(mData)[1] ,]) 546 | 547 | for (i in 2:(min((iLagsMax), nAhead))) { 548 | 549 | vForecastBPVFoo = c(vThisRollBPV[(iT-nRoll-iLagsMax+i) : (iT-nRoll+1)], 550 | mBPVForecast[1:(i-1) , j]) 551 | #Gets the data necessary to form the forecast in one vector. 552 | vLastrowBPVdata = HARDataCreationC(vForecastBPVFoo[(length(vForecastBPVFoo) - 553 | iLagsMax) : length(vForecastBPVFoo)] 554 | , periods) 555 | #Creates the j'th i-step ahead forecast 556 | mBPVForecast[i,j] = dMu + (dBeta^i)*(dBPVY - dMu) 557 | mForecast[i,j] = vCoef[1] + sum(vCoef[-1]* c(vLastrowBPVdata[-1])) 558 | 559 | } #end first nested for-loop 560 | if(nAhead>iLagsMax){ 561 | for (i in (iLagsMax+1):(nAhead)) { 562 | vForecastBPVFoo = mBPVForecast[(i-iLagsMax):i, j] 563 | #Gets the data necessary to form the forecast in one vector. 564 | vLastrowBPVdata = HARDataCreationC(vForecastBPVFoo[(length(vForecastBPVFoo) - 565 | iLagsMax) : length(vForecastBPVFoo)], 566 | periods) 567 | mBPVForecast[i,j] = dMu + (dBeta^i)*(dBPVY - dMu) 568 | 569 | #Gets the data necessary to form the forecast in one vector. 570 | 571 | mForecast[i,j] = vCoef[1] + sum(vCoef[-1]* vLastrowBPVdata[,-1]) 572 | 573 | #Creates the j'th i-step ahead forecast 574 | } #End second nested for-loop 575 | } 576 | if(insanityFilter){ 577 | mForecast[,j] = HARinsanityFilter(mForecast[,j] , 0 , max(vThisRoll) , mean(vThisRoll)) 578 | } # end insanityFilter conditional 579 | } #end for-loop 580 | } 581 | 582 | 583 | }#type: "CHAR" end 584 | 585 | 586 | if(type == "CHARQ"){ 587 | mForecast = matrix(0 , nrow = nAhead , ncol = nRoll) 588 | mBPVForecast = matrix(0, nrow = nAhead, ncol = nRoll) 589 | mAuxForecast = matrix(0, nrow = nAhead, ncol = nRoll) 590 | iMaxAuxLags = max(periodsRQ) 591 | iN = iT-nRoll+1 #Used for fast CHAR estimation, need better name for it tho 592 | if(nAhead == 1){ 593 | for (j in 1:(nRoll)) { 594 | if(windowType %in% vRollingSynonyms){ 595 | lFit = FASTCHARQestimate(RM[j:(iT-nRoll+j)], BPV[j:(iT-nRoll+j)], RQ[j:(iT-nRoll+j)], 596 | periods, periodsRQ, iN, h = h) 597 | } 598 | if(windowType %in% vIncreasingSynonyms){ 599 | lFit = FASTCHARQestimate(RM[1:(iT-nRoll+j)], BPV[1:(iT-nRoll+j)], RQ[1:(iT-nRoll+j)], 600 | periods, periodsRQ, iN + j -1, h = h) 601 | } 602 | mData = lFit$mData[,-1] 603 | vCoef = lFit$coefficients 604 | mForecast[1,j] = vCoef[1] + sum(vCoef[-1]*mData[dim(mData)[1] ,]) 605 | if(insanityFilter){ 606 | if(windowType %in% vRollingSynonyms){ 607 | mForecast[,j] = HARinsanityFilter(mForecast[,j], 0, 608 | max(lFit$mData[,1]), 609 | mean(lFit$mData[,1])) 610 | } else { 611 | mForecast[,j] = HARinsanityFilter(mForecast[,j], 0, 612 | max(lFit$mData[,1]), 613 | mean(lFit$mData[,1])) 614 | } 615 | } # end insanityFilter conditional 616 | #Creates the j'th 1-step ahead forecast 617 | } # End loop 618 | }# End one-step ahead conditionals 619 | else{ 620 | for (j in 1:(nRoll)) { 621 | if(windowType %in% vRollingSynonyms){ 622 | vThisRollRQ = as.numeric(RQ[j:(iT-nRoll+j)]) 623 | vThisRoll = as.numeric(RM[j:(iT-nRoll+j)]) 624 | vThisRollBPV = as.numeric(BPV[j:(iT-nRoll+j)]) 625 | } 626 | if(windowType %in% vIncreasingSynonyms){ 627 | vThisRollRQ = as.numeric(RQ[1:(iT-nRoll+j)]) 628 | vThisRoll = as.numeric(RM[1:(iT-nRoll+j)]) 629 | vThisRollBPV = as.numeric(BPV[1:(iT-nRoll+j)]) 630 | iN = iT-nRoll+j 631 | } 632 | lFit = FASTCHARQestimate(vThisRoll, vThisRollBPV, vThisRollRQ, periods, periodsRQ,iN) 633 | ##BPV modeling 634 | mBPVFoo = HARDataCreationC(vThisRollRQ , c(1)) 635 | dBPVY = BPV[(iT-nRoll+j-1)] 636 | lBPVFit = fastLMcoef(cbind(1,mBPVFoo[,2]),mBPVFoo[,1]) 637 | dAlpha = lBPVFit[1] 638 | dBeta = lBPVFit[2] 639 | dMu = dAlpha/(1 - dBeta) 640 | mBPVForecast[1,j]= dMu + dBeta * (dBPVY - dMu) 641 | ##RQ modeling 642 | mAuxFoo = HARDataCreationC(vThisRollRQ , c(1)) 643 | dAuxY = sqrt(RQ[(iT-nRoll+j-1)]) #remember square root 644 | lAuxFit = fastLMcoef(cbind(1,sqrt(mAuxFoo[,2])),sqrt(mAuxFoo[,1])) 645 | dAlphaRQ = lAuxFit[1] 646 | dBetaRQ = lAuxFit[2] 647 | dMuRQ = dAlphaRQ/(1 - dBetaRQ) 648 | mAuxForecast[1,j]= dMuRQ + dBetaRQ * (dAuxY - dMuRQ) 649 | mData = lFit$mData[,-1] 650 | vCoef = lFit$coefficients 651 | #Creates the j'th 1-step ahead forecast 652 | mForecast[1,j] = vCoef[1] + sum(vCoef[-1]*mData[dim(mData)[1] ,]) 653 | 654 | for (i in 2:(min((iLagsMax), nAhead))) { 655 | 656 | 657 | vForecastBPVFoo = c(vThisRollRQ[(iT-nRoll-iLagsMax+i) : (iT-nRoll+1)], 658 | mBPVForecast[1:(i-1) , j]) 659 | vForecastAuxFoo = c(sqrt(vThisRollRQ[(iT-nRoll-iLagsMax+i) : (iT-nRoll+1)]), 660 | mAuxForecast[1:(i-1) , j]) 661 | #data preparation 662 | vLastrowBPVdata = HARDataCreationC(vForecastBPVFoo[(length(vForecastBPVFoo) - 663 | iLagsMax) : length(vForecastBPVFoo)] 664 | , periods) 665 | vLastrowAuxdata = HARDataCreationC(vForecastAuxFoo[(length(vForecastAuxFoo) - 666 | iMaxAuxLags):length(vForecastAuxFoo)], 667 | periodsRQ) 668 | #Creates the j'th i-step ahead forecasts 669 | mAuxForecast[i,j] = dMuRQ + (dBetaRQ^i)*(dAuxY - dMuRQ) 670 | mBPVForecast[i,j] = dMu + (dBeta^i)*(dBPVY - dMu) 671 | mForecast[i,j] = vCoef[1] + sum(vCoef[-1]* c(vLastrowBPVdata[-1], vLastrowAuxdata[,-1])) 672 | 673 | } #end first nested for-loop 674 | if(nAhead>iLagsMax){ 675 | for (i in (iLagsMax+1):(nAhead)) { 676 | vForecastAuxFoo = mAuxForecast[(i-iLagsMax):i, j] 677 | vForecastBPVFoo = mBPVForecast[(i-iLagsMax):i, j] 678 | #Gets the data necessary to form the forecast in one vector. 679 | vLastrowBPVdata = HARDataCreationC(vForecastBPVFoo[(length(vForecastBPVFoo) - 680 | iLagsMax) : length(vForecastBPVFoo)], 681 | periods) 682 | vLastrowAuxdata = HARDataCreationC(vForecastAuxFoo[(length(vForecastAuxFoo) - 683 | iMaxAuxLags) : length(vForecastAuxFoo)] , 684 | periodsRQ) 685 | mBPVForecast[i,j] = dMu + (dBeta^i)*(dBPVY - dMu) 686 | mAuxForecast[i,j] = dMuRQ + (dBetaRQ^i)*(dAuxY - dMuRQ) 687 | mForecast[i,j] = vCoef[1] + sum(vCoef[-1]* c(vLastrowBPVdata[-1], vLastrowAuxdata[,-1])) 688 | 689 | #Creates the j'th i-step ahead forecast 690 | } #End second nested for-loop 691 | } 692 | if(insanityFilter){ 693 | mForecast[,j] = HARinsanityFilter(mForecast[,j] , 0 , max(vThisRoll) , mean(vThisRoll)) 694 | } # end insanityFilter conditional 695 | } #end for-loop 696 | } 697 | 698 | 699 | 700 | }#type: "CHARQ" end 701 | 702 | ### type: "TV-HAR" 703 | if(type == "TV-HAR"){ 704 | mForecast = matrix(0 , nrow = nAhead , ncol = nRoll) 705 | if(nAhead == 1){ 706 | 707 | for (j in 1:nRoll) { 708 | if(windowType %in% vRollingSynonyms){ 709 | lFit = FASTTVHARestimate(RM[j:(iT-nRoll+j)] , periods, h = h) 710 | }else{ 711 | lFit = FASTTVHARestimate(RM[1:(iT-nRoll+j)] , periods, h = h) 712 | } 713 | mData = lFit$mData[,-1] 714 | vCoef = lFit$coefficients 715 | mForecast[1,j] = vCoef[1] + sum(vCoef[-1]*mData[nrow(mData),]) 716 | #Creates the j'th 1-step ahead forecast 717 | if(insanityFilter){ 718 | if(windowType %in% vRollingSynonyms){ 719 | mForecast[,j] = HARinsanityFilter(mForecast[,j], 0, 720 | max(lFit$mData[,1]), 721 | mean(lFit$mData[,1])) 722 | } else { 723 | mForecast[,j] = HARinsanityFilter(mForecast[,j], 0, 724 | max(lFit$mData[,1]), 725 | mean(lFit$mData[,1])) 726 | } 727 | } # end insanityFilter conditional 728 | } # End loop 729 | }# End one-step ahead conditionals 730 | else{ 731 | for (j in 1:(nRoll)){ 732 | if(windowType %in% vRollingSynonyms){ 733 | vThisRoll = as.numeric(RM[j:(iT-nRoll+j)]) #pass as.numeric 734 | } 735 | if(windowType %in% vIncreasingSynonyms){ 736 | vThisRoll = as.numeric(RM[1:(iT-nRoll+j)]) #pass as.numeric 737 | } 738 | lFit = FASTTVHARestimate(vThisRoll , periods) 739 | mData = lFit$mData[,-1] 740 | vCoef = lFit$coefficients 741 | #Creates the j'th 1-step ahead forecast 742 | mForecast[1,j] = vCoef[1] + sum(vCoef[-1] * mData[nrow(mData),]) 743 | 744 | 745 | for (i in 2:(min((iLagsMax), nAhead))) { 746 | vForecastfoo = c(vThisRoll[(iT-nRoll-iLagsMax+i) : (iT-nRoll+1)] , mForecast[1:(i-1) , j]) 747 | #Gets the data necessary to form the forecast in one vector. 748 | vLastrowdata = HARDataCreationC(vForecastfoo[(length(vForecastfoo) - iLagsMax):length(vForecastfoo)], 749 | periods) 750 | #Creates the j'th i-step ahead forecast 751 | mForecast[i,j] = vCoef[1] + sum(vCoef[-1]* c(vLastrowdata[2], 752 | abs(vLastrowdata[2]-vLastrowdata[iLagsPlusOne]), #difference 753 | vLastrowdata[3:iLagsPlusOne])) 754 | 755 | } #end first nested for-loop 756 | if(nAhead>iLagsMax){ 757 | for (i in (iLagsMax+1):(nAhead)) { 758 | vForecastfoo = mForecast[(i-iLagsMax):i , j] 759 | vLastrowdatafoo = HARDataCreationC(vForecastfoo , periods) 760 | #Gets the data necessary to form the forecast in one vector. 761 | mForecast[i,j] = vCoef[1] + sum(vCoef[-1]* c(vLastrowdata[2], 762 | abs(vLastrowdata[2]-vLastrowdata[iLagsPlusOne]), #difference 763 | vLastrowdata[3:iLagsPlusOne])) 764 | #Creates the j'th i-step ahead forecast 765 | } #End second nested for-loop 766 | } 767 | if(insanityFilter){ 768 | mForecast[,j] = HARinsanityFilter(mForecast[,j] , 0 , max(vThisRoll) , sum(vThisRoll)/length(vThisRoll)) 769 | } 770 | } #end for-loop 771 | } 772 | 773 | }# type: "TV-HAR" end 774 | FCElapsedTime = Sys.time() - FCstart.time 775 | HARForecast = new("HARForecast" , 776 | "model" = HAREstimate(RM[1:(iT-nRoll)], 777 | BPV = BPV[1:(iT-nRoll)], 778 | RQ = RQ[1:(iT-nRoll)], 779 | periods = periods, periodsRQ = periodsRQ, type = type, h = h), 780 | "forecast" = mForecast, 781 | "info" = list("elapsedTime" = FCElapsedTime , "rolls" = nRoll, 782 | "horizon" = nAhead , "type" = type, "windowType" = windowType), 783 | "data" = list("forecastDates" = vForecastDates, 784 | "observations" = xts(vObservations, vDates), 785 | "forecastComparison" = xts(vForecastComp, vForecastDates))) 786 | colnames(HARForecast@forecast) = paste0("roll", 1:nRoll) 787 | rownames(HARForecast@forecast) = paste0("step", 1:nAhead) 788 | 789 | return(HARForecast) 790 | 791 | } --------------------------------------------------------------------------------