BlueHorseshoe,
Your code here-above is supposed to calculate what?
The "optimal" ratio between the two price series?
Something different?
Kalman filter is a methodology to calculate "adaptative" things. There is not one unique formula. It depends on what we try to do.
Let's A and B be the 2 instruments.
In pairs trading, typically:
- cointegration is checked (Dickey-Fuller or other) on the long term (typically > 1 year).
- hedge ratio (let's call it gamma) is calculated on the in-sample data by linear regression
- then, on out-of-sample data, we enter "long A short B with appropriate position sizing" each time the spread A-gamma*B departs too much from its mean.
For this "basic" approach, Kalman filter is not really useful.
It may become useful if you want to calculate a shorter-term gamma, in order to have a more "dynamic" and short-term spread.
Then, we may consider these 2 equations
{ B[t] (observed) = gamma[t] (to be assessed by KF) * A[t] (observed) + noise (unknown)
{ gamma[t] = gamma[t-1] + noise (unknown)
We have the 2 typical equations (state equation and measurement equation) on which we can the KF methodology.
There is a research paper on intraday pairs trading which implements the above KF approach (as well as other methodologies) to assess a short-term gamma:
Dunis and al
Statistical Arbitrage and High-Frequency Data with an Application to Eurostoxx 50 Equities
March 2010
http://www.ljmu.ac.uk/Images_Everyone/Jozef_1st(1).pdf
What is above is only my understanding so... may be wrong!
Nicolas
Nicolas