[R] Kalman filter for a time series
Spencer Graves
spencer.graves at effectivedefense.org
Sun Jul 30 14:10:38 CEST 2017
On 2017-07-29 11:26 PM, Staff wrote:
> I found an example at
> http://www.bearcave.com/finance/random_r_hacks/kalman_smooth.html
That example is signed by "Ian Kaplan". There's a box at the
bottom of the page for you to email him.
> shown
> below. But it seems the structSSM function has been removed from KFAS
> library
or it never was part of KFAS. I don't know.
> so it won't run. Does anyone know how to fix the code so that it
> runs?
Have you tried the vignette with KFAS?
Hope this helps.
Spencer Graves
>
> library(KFAS)
> library(tseries)
> library(timeSeries)
> library(zoo)
> library(quantmod)
>
> getDailyPrices = function( tickerSym, startDate, endDate )
> {
> prices = get.hist.quote( instrument = tickerSym, start = startDate,
> end = endDate,
> quote="AdjClose", provider="yahoo",
> compression="d", quiet=T)
>
> prices.ts = ts(prices)
> return( prices.ts )
> }
>
> kalmanFilter = function( x )
> {
> t = x
> if (class(t) != "ts") {
> t = ts(t)
> }
> ssModel = structSSM( y = t, distribution="Gaussian")
> ssFit = fitSSM(inits=c(0.5*log(var(t)), 0.5*log(var(t))), model = ssModel )
> kfs = KFS( ssFit$model, smoothing="state", nsim=length(t))
> vals = kfs$a
> lastVal = vals[ length(vals)]
> return(lastVal)
> }
>
> Start = "2011-01-01"
> End = "2012-12-31"
> SandP = "^GSPC"
>
> windowWidth = 20
> tsLength = 100
>
> SAndP.ts = getDailyPrices( SandP, Start, End )
> SAndP.ts = SAndP.ts[1:tsLength]
> SAndP.smoothed = rollapply( data=SAndP.ts, width=windowWidth, FUN=kalmanFilter)
>
> par(mfrow=c(1,1))
> prices = coredata( SAndP.ts[windowWidth:length(SAndP.ts)])
> plot(prices, col="blue", type="l")
> lines(coredata(SAndP.smoothed), col="magenta")
> par(mfrow=c(1,1))
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list