trying to code my first python class. should I be naming the updateState() method handle_add() instead? I got confused by the function decorators (https://github.com/quantopian/zipline/blob/master/zipline/transforms/utils.py), started googling those, but its a bit late so I'll check it out tomorrow.
Any tips on how to fit this before I run it on out of sample data? I'm not too familiar with the python modules.
Notation (sort of) follows shumway and stoffers book "Time Series Analysis and Its Applications: With R Examples."
import numpy as np
from zipline.transforms.utils import EventWindow
class Kalman(EventWindow):
def __init__(self, mu0, Sigma0, PHIfit, Qfit, Rfit):
#initial state guesses are mu0, Sigma0
#note we are not assuming Bayesian priors...just fixed values
self.X = mu0
self.P = Sigma0
#things that should be from a fit are PHI, Q, and R
self.PHI = PHIfit
self.Q = Qfit
self.R = Rfit
#some convenience functions
def predictState(prevX):
return(PHI*prevX)
def predictStateCov(prevP):
return(PHI*prevP*transpose(PHI) + Q)
def predictObserv(prevX):
return(A*predictState(prevX))
def predictObservCov(prevP):
return( (A * predictStateCov(predP) *transpose(A)) + R)
#this is the guy that gets called every minute
def updateState(observedY, X, P):
predP = predictStateCov(P)
GAIN = predP*transpose(A)* ( (A*predP*transpose(A)) + R).getI()
innov = observedY - predictObserv(X)
I = np.eye(self.X.shape[0])
self.X = predX + GAIN*innov
self.P = (I - (GAIN*A))*predP
def initialize(context):
context.stock = sid(26578)