57 views

Uploaded by JasonClark

EWAEWC Pair Trade Kalman Filter

EWAEWC Pair Trade Kalman Filter

© All Rights Reserved

- Vehicular Technologies Increasing Connectivity
- Algo Trading
- Laterally Loaded Piles in CLAY
- Fokker Planck1
- ASYMPTOTIC OPTIMALITY IN BAYESIAN CHANGE-POINT DETECTION PROBLEMS UNDER GLOBAL FALSE ALARM PROBABILITY CONSTRAINT
- Math Application for Me
- Mm326 System Dynamics Hw4 Solution
- 8-Differencing
- space time FEM
- Kalman Introduction
- NAFEMS Books.xlsx
- Time Series Book
- Random Vibration
- Etabs for Users
- Paper-3 Reducing Support Vector Machine Complexity by Implementing Kalman Filter
- linabp
- The Riccati equation method with variable expansion coefficients. IV. Solving the Fitzhugh-Nagumo equation.
- Investigating the Long Run Relationship Between Crude Oil and Food Commodity Prices
- A MATLAB Simulink Library for Transient Flow Simulation of Gas Networks
- S0273-0979-00-00868-5.pdf

You are on page 1of 4

g: Winning Strategies and Their Rationale. It's been posted here previously but

that used constants for the linear regression coefficients.

In this case, a Kalman filter is used to dynamically update the linear regressio

n coefficients between the EWA and EWC ETFs. It performs well up to 2009 but aft

er that the performance degrades.

import numpy as np

import pytz

def initialize(context):

context.ewa = sid(14516)

context.ewc = sid(14517)

context.delta = 0.0001

context.Vw = context.delta / (1 - context.delta) * np.eye(2)

context.Ve = 0.001

context.beta = np.zeros(2)

context.P = np.zeros((2, 2))

context.R = None

context.pos = None

context.day = None

set_slippage(slippage.FixedSlippage(spread=0))

set_commission(commission.PerShare(cost=0))

def handle_data(context, data):

exchange_time = get_datetime().astimezone(pytz.timezone('US/Eastern'))

# update Kalman filter and exectue a trade during the last 5 mins of trading

each day

if exchange_time.hour == 15 and exchange_time.minute >= 55:

# only execute this once per day

if context.day is not None and context.day == exchange_time.day:

return

context.day = exchange_time.day

x = np.asarray([data[context.ewa].price, 1.0]).reshape((1, 2))

y = data[context.ewc].price

# update Kalman

if context.R is

context.R =

else:

context.R =

not None:

context.P + context.Vw

np.zeros((2, 2))

yhat = x.dot(context.beta)

Q = x.dot(context.R).dot(x.T) + context.Ve

sqrt_Q = np.sqrt(Q)

e = y - yhat

K = context.R.dot(x.T) / Q

context.P = context.R - K * x.dot(context.R)

record(beta=context.beta[0], alpha=context.beta[1])

if e < 5:

record(spread=float(e), Q_upper=float(sqrt_Q), Q_lower=float(-sqrt_Q

))

if context.pos is not None:

if context.pos == 'long' and e > -sqrt_Q:

#log.info('closing long')

order_target(context.ewa, 0)

order_target(context.ewc, 0)

context.pos = None

elif context.pos == 'short' and e < sqrt_Q:

#log.info('closing short')

order_target(context.ewa, 0)

order_target(context.ewc, 0)

context.pos = None

if context.pos is None:

if e < -sqrt_Q:

#log.info('opening long')

order(context.ewc, 1000)

order(context.ewa, -1000 * context.beta[0])

context.pos = 'long'

elif e > sqrt_Q:

#log.info('opening short')

order(context.ewc, -1000)

order(context.ewa, 1000 * context.beta[0])

context.pos = 'short'

dimensions of the observation matrix for the Kalman filter (variable x in the a

lgo). This backtest does a regression between SPY and the sector ETF's XLE, XLF

and XLI.

mport numpy as np

import pytz

def initialize(context):

context.y = sid(8554)

context.x = [sid(19655), sid(19656), sid(19657)]

context.n_dim_state = len(context.x) + 1

context.delta = 0.0001

context.Vw = context.delta / (1 - context.delta) * np.eye(context.n_dim_stat

e)

context.Ve = 0.001

context.beta = np.zeros(context.n_dim_state)

context.P = np.zeros((context.n_dim_state, context.n_dim_state))

context.R = None

context.pos = None

context.day = None

set_slippage(slippage.FixedSlippage(spread=0))

set_commission(commission.PerShare(cost=0))

def handle_data(context, data):

exchange_time = get_datetime().astimezone(pytz.timezone('US/Eastern'))

# update Kalman filter and exectue a trade during the last 5 mins of trading

each day

if exchange_time.hour == 15 and exchange_time.minute >= 55:

# only execute this once per day

if context.day is not None and context.day == exchange_time.day:

return

context.day = exchange_time.day

x = np.hstack([[data[sec].price for sec in context.x], 1.0]).reshape((1,

context.n_dim_state))

y = data[context.y].price

# update Kalman

if context.R is

context.R =

else:

context.R =

not None:

context.P + context.Vw

np.zeros((context.n_dim_state, context.n_dim_state))

yhat = x.dot(context.beta)

Q = x.dot(context.R).dot(x.T) + context.Ve

sqrt_Q = np.sqrt(Q)

e = y - yhat

K = context.R.dot(x.T) / Q

context.beta = context.beta + K.flatten() * e

context.P = context.R - K * x.dot(context.R)

record(beta1=context.beta[0], beta2=context.beta[1], beta3=context.beta[

2], alpha=context.beta[-1])

#if e < 5:

#

record(spread=float(e), Q_upper=float(sqrt_Q), Q_lower=float(-sqrt_

Q))

if context.pos is not None:

if context.pos == 'long' and e > -sqrt_Q:

#log.info('closing long')

order_target(context.y, 0)

for sec in context.x:

order_target(sec, 0)

context.pos = None

elif context.pos == 'short' and e < sqrt_Q:

#log.info('closing short')

order_target(context.y, 0)

for sec in context.x:

order_target(sec, 0)

context.pos = None

if context.pos is None:

if e < -sqrt_Q:

#log.info('opening long')

order(context.y, 1000)

for i in xrange(len(context.x)):

order(context.x[i], -1000 * context.beta[i])

context.pos = 'long'

elif e > sqrt_Q:

#log.info('opening short')

order(context.y, -1000)

for i in xrange(len(context.x)):

order(context.x[i], 1000 * context.beta[i])

context.pos = 'short'

@Eric and @Jason, there is reasoning behind using a Kalman filter for this appli

cation!

First, let's look at what we are trying to achieve. We want to construct a stati

onary time-series (spread) from two individually non-stationary time-series (EWA

and EWC). Let's assume there exists a parameter (beta or cointegration coeffici

ent) such that the residual from the linear combination of the non-stationary ti

me-series is stationary and we can use the resulting stationary series to genera

te trading signals. In a perfect world, beta would be constant and our job would

be done.

Our problem now is that beta is not constant and changes gradually (assuming the

series stay cointegrated) over time. To use a Kalman filter, we need to formula

te an observation and transition equation. The observation equation is the linea

r combination of the non-stationary time-series plus Gaussian white noise. This

is really just a linear regression of EWA and EWC. The transition equation assum

es that beta is equal the previous beta plus Gaussian white noise. This is a ran

dom walk.

Using more complex non-linear models probably won't improve things, as Ernie Cha

n said on non-linear models "experiences showed me that nonlinear models have mo

stly been unmitigated disasters in terms of trading profits" and "One is almost

certain to overfit a nonlinear model to non-recurring noise".

Using the current setup of the algo, it trades frequently, almost every day, and

the profit from each trade is not sufficient to cover transaction costs. It tra

des frequently because the Kalman filter responds quickly to changes in the EWA/

EWC spread. Reducing the sensitivity of the Kalman filter will decrease trading

frequency and only trade larger deviations in the spread, which will increase th

e expected payoff. To answer your question, it only makes sense to use this stra

tegy, or any other strategy, when the expected payoff of a trade is greater than

transaction costs.

- Vehicular Technologies Increasing ConnectivityUploaded byJosé Ramírez
- Algo TradingUploaded bynikilmarrisetty
- Laterally Loaded Piles in CLAYUploaded bydr
- Fokker Planck1Uploaded bynormancboy
- ASYMPTOTIC OPTIMALITY IN BAYESIAN CHANGE-POINT DETECTION PROBLEMS UNDER GLOBAL FALSE ALARM PROBABILITY CONSTRAINTUploaded bybayareaking
- Math Application for MeUploaded byDetec Tive Roy Tizon
- Mm326 System Dynamics Hw4 SolutionUploaded byOğulcan Aytaç
- 8-DifferencingUploaded byjustinlondon
- space time FEMUploaded bySadiq Sarfaraz
- Kalman IntroductionUploaded byBui Tuan Viet Long
- NAFEMS Books.xlsxUploaded byds_srinivas
- Time Series BookUploaded byUsman Khalid
- Random VibrationUploaded byLouc Ing
- Etabs for UsersUploaded byHaymanAHMED
- Paper-3 Reducing Support Vector Machine Complexity by Implementing Kalman FilterUploaded byRachel Wheeler
- linabpUploaded bymemguoyan
- The Riccati equation method with variable expansion coefficients. IV. Solving the Fitzhugh-Nagumo equation.Uploaded byMakos_Antoniou
- Investigating the Long Run Relationship Between Crude Oil and Food Commodity PricesUploaded byCapita1
- A MATLAB Simulink Library for Transient Flow Simulation of Gas NetworksUploaded byAhmadi Ahmad
- S0273-0979-00-00868-5.pdfUploaded byShu Shujaat Lin
- DOC-20160422-WA0021Uploaded byLucas Bezerra
- Case Study _Kalman Filter Design and SimulationUploaded byrktiwary256034
- 04311853Uploaded bynasir
- Nonstat DetectorUploaded bytruongvinhlan19895148
- lindberg1996.pdfUploaded byMolinaEstefany
- wp10258 - IMFUploaded byvarunhome
- Philip Cardiff OFW09 P 0014Uploaded bySimon Regő
- Frequency Domain Analysis InUploaded byIAN.SEMUT
- 4Uploaded byJessica Ross
- MS-8 june 2013Uploaded bymahi

- Ma0232 Probability Random ProcessUploaded byRajkumar Kondappan
- Wikipedia-WikiProject_Mathematics_List_of_mathematics_articles_(S).pdfUploaded bymars
- GS (2).docUploaded byEdvin Musi
- Arimax ArimaUploaded byTeresaMadurai
- How Foreign Direct Investment and Urbanization Affect the Environment of IndonesiaUploaded byMaharanny
- lectr14Uploaded byHira Masood
- An Empirical Analysis of Stock Market Performance AndEconomic Growth Evidence From India (Paramati&Gupta 2011)Uploaded byShardulWaikar
- Time SeriesUploaded byWyara Vanesa Moura
- ec2-4Uploaded byMasudul Islam
- lec3-08Uploaded byalanpicard2303
- rp spiral.pdfUploaded byno one
- Notes MainimpUploaded bydondan123
- Implementation of Garch ModelsUploaded bySayantan Paul
- Time Series QuestionsUploaded byakriti_08
- PfaffvdvsdUploaded byprabinseth
- Regional Sea Level Reconstruction in the Pacific OceanUploaded bysitizulaika275
- Applied Time Series AnalysisUploaded byJelena Martinović
- d07027.pdfUploaded byRabia Almamalook
- Lecture 9 the Lag OperatorUploaded byz_k_j_v
- Linear time variantUploaded byindameantime
- b.techece Iiyear.r10studentsUploaded byJagadeesh Kumar
- Using Google Trend Data in Forecasting Number of Dengue Fever Cases With ARIMAX Method Case Study- Surabaya, IndonesiaUploaded byArdi Susanto
- S349 08.pptUploaded byrabiadz
- Kjsce Te SyllabusUploaded byharsh
- Survey of Stochsatic ModelsUploaded byhkocan
- 1-s2.0-S0301421509008489-mainUploaded byRazleen Rashidi
- Time Series Analysis of Monthly Rainfall data for the Gadaref rainfall station, Sudan, by Sarima MethodsUploaded byAmin Mojiri
- Time Averages and ErgodicityUploaded byShubham
- Jeff Gill-Essential Mathematics for Political and Social Research (Analytical Methods for Social Research) (2006)Uploaded byMarcello Sena
- mpc3Uploaded bySurya Budi Widagdo