-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathkalman-filter-pairs-trading.html
670 lines (507 loc) · 35.1 KB
/
kalman-filter-pairs-trading.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
<link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
<link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
<link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
<link rel="mask-icon" href="/images/logo.svg" color="#222">
<meta name="google-site-verification" content="bokhEjod5-cme1ZueY6aAPHORfnXv9hSoljSfg2Vp_Q">
<link rel="stylesheet" href="/css/main.css">
<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
<script id="hexo-configurations">
var NexT = window.NexT || {};
var CONFIG = {"hostname":"letianzj.github.io","root":"/","scheme":"Muse","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
</script>
<meta name="description" content="This post shows how to apply Kalman Filter in pairs trading. It updates the cointegration relationship using Kalman Filter, and then utilize this relationship in a mean-reversion strategy to backtest">
<meta property="og:type" content="article">
<meta property="og:title" content="Kalman Filter and Pairs Trading">
<meta property="og:url" content="https://letianzj.github.io/kalman-filter-pairs-trading.html">
<meta property="og:site_name" content="Quantitative Trading and Systematic Investing">
<meta property="og:description" content="This post shows how to apply Kalman Filter in pairs trading. It updates the cointegration relationship using Kalman Filter, and then utilize this relationship in a mean-reversion strategy to backtest">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="https://letianzj.github.io/time_varying_scatterplot.png">
<meta property="og:image" content="https://letianzj.github.io/kalman-filter-pairs-trading/time_varying_scatterplot.png">
<meta property="og:image" content="https://letianzj.github.io/time_varying_parameters.png">
<meta property="og:image" content="https://letianzj.github.io/kalman-filter-pairs-trading/time_varying_parameters.png">
<meta property="og:image" content="https://letianzj.github.io/time_varying_regression.png">
<meta property="og:image" content="https://letianzj.github.io/kalman-filter-pairs-trading/time_varying_regression.png">
<meta property="og:image" content="https://letianzj.github.io/backtest_results.png">
<meta property="og:image" content="https://letianzj.github.io/kalman-filter-pairs-trading/backtest_results.png">
<meta property="article:published_time" content="2018-03-30T23:25:00.000Z">
<meta property="article:modified_time" content="2020-09-04T20:57:20.037Z">
<meta property="article:author" content="Letian Wang">
<meta property="article:tag" content="Kalman Filter">
<meta property="article:tag" content="Machine Learning">
<meta property="article:tag" content="Algorithmic Trading">
<meta property="article:tag" content="Quantitative Trading">
<meta property="article:tag" content="Pairs Trading">
<meta property="article:tag" content="State Space Model">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://letianzj.github.io/time_varying_scatterplot.png">
<link rel="canonical" href="https://letianzj.github.io/kalman-filter-pairs-trading.html">
<script id="page-configurations">
// https://hexo.io/docs/variables.html
CONFIG.page = {
sidebar: "",
isHome : false,
isPost : true,
lang : 'en'
};
</script>
<title>Kalman Filter and Pairs Trading | Quantitative Trading and Systematic Investing</title>
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-109341958-2"></script>
<script>
if (CONFIG.hostname === location.hostname) {
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-109341958-2');
}
</script>
<noscript>
<style>
.use-motion .brand,
.use-motion .menu-item,
.sidebar-inner,
.use-motion .post-block,
.use-motion .pagination,
.use-motion .comments,
.use-motion .post-header,
.use-motion .post-body,
.use-motion .collection-header { opacity: initial; }
.use-motion .site-title,
.use-motion .site-subtitle {
opacity: initial;
top: initial;
}
.use-motion .logo-line-before i { left: initial; }
.use-motion .logo-line-after i { right: initial; }
</style>
</noscript>
</head>
<body itemscope itemtype="http://schema.org/WebPage">
<div class="container use-motion">
<div class="headband"></div>
<header class="header" itemscope itemtype="http://schema.org/WPHeader">
<div class="header-inner"><div class="site-brand-container">
<div class="site-nav-toggle">
<div class="toggle" aria-label="Toggle navigation bar">
<span class="toggle-line toggle-line-first"></span>
<span class="toggle-line toggle-line-middle"></span>
<span class="toggle-line toggle-line-last"></span>
</div>
</div>
<div class="site-meta">
<a href="/" class="brand" rel="start">
<span class="logo-line-before"><i></i></span>
<h1 class="site-title">Quantitative Trading and Systematic Investing</h1>
<span class="logo-line-after"><i></i></span>
</a>
<p class="site-subtitle" itemprop="description">Letian Wang Blog on Quant Trading and Portfolio Management</p>
</div>
<div class="site-nav-right">
<div class="toggle popup-trigger">
</div>
</div>
</div>
<nav class="site-nav">
<ul id="menu" class="main-menu menu">
<li class="menu-item menu-item-home">
<a href="/" rel="section"><i class="fa fa-home fa-fw"></i>Home</a>
</li>
<li class="menu-item menu-item-archives">
<a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>Archives</a>
</li>
<li class="menu-item menu-item-sitemap">
<a href="/sitemap.xml" rel="section"><i class="fa fa-sitemap fa-fw"></i>Sitemap</a>
</li>
</ul>
</nav>
</div>
</header>
<div class="back-to-top">
<i class="fa fa-arrow-up"></i>
<span>0%</span>
</div>
<main class="main">
<div class="main-inner">
<div class="content-wrap">
<div class="content post posts-expand">
<article itemscope itemtype="http://schema.org/Article" class="post-block" lang="en">
<link itemprop="mainEntityOfPage" href="https://letianzj.github.io/kalman-filter-pairs-trading.html">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="image" content="/images/avatar.jpg">
<meta itemprop="name" content="Letian Wang">
<meta itemprop="description" content="Letian Wang blog to discuss quantitative trading strategies, portfolio management, risk premia, risk management, systematic trading, and machine learning, deep learning applications in Finance.">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="Quantitative Trading and Systematic Investing">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
Kalman Filter and Pairs Trading
</h1>
<div class="post-meta">
<span class="post-meta-item">
<span class="post-meta-item-icon">
<i class="far fa-calendar"></i>
</span>
<span class="post-meta-item-text">Posted on</span>
<time title="Created: 2018-03-30 19:25:00" itemprop="dateCreated datePublished" datetime="2018-03-30T19:25:00-04:00">2018-03-30</time>
</span>
<span class="post-meta-item">
<span class="post-meta-item-icon">
<i class="far fa-calendar-check"></i>
</span>
<span class="post-meta-item-text">Edited on</span>
<time title="Modified: 2020-09-04 16:57:20" itemprop="dateModified" datetime="2020-09-04T16:57:20-04:00">2020-09-04</time>
</span>
<span class="post-meta-item">
<span class="post-meta-item-icon">
<i class="far fa-folder"></i>
</span>
<span class="post-meta-item-text">In</span>
<span itemprop="about" itemscope itemtype="http://schema.org/Thing">
<a href="/categories/Systematic-Investment/" itemprop="url" rel="index"><span itemprop="name">Systematic Investment</span></a>
</span>
,
<span itemprop="about" itemscope itemtype="http://schema.org/Thing">
<a href="/categories/Systematic-Investment/Quantitative-Trading/" itemprop="url" rel="index"><span itemprop="name">Quantitative Trading</span></a>
</span>
</span>
<span class="post-meta-item">
<span class="post-meta-item-icon">
<i class="far fa-comment"></i>
</span>
<span class="post-meta-item-text">Disqus: </span>
<a title="disqus" href="/kalman-filter-pairs-trading.html#disqus_thread" itemprop="discussionUrl">
<span class="post-comments-count disqus-comment-count" data-disqus-identifier="kalman-filter-pairs-trading.html" itemprop="commentCount"></span>
</a>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<p>This post shows how to apply Kalman Filter in pairs trading. It updates the cointegration relationship using Kalman Filter, and then utilize this relationship in a mean-reversion strategy to backtest the pairs trading performance.</p>
<h2 id="introduction">Introduction</h2>
<p>In <a href="/kalman-filter-linear-regression.html" title="previous post">previous post</a> we have seen Kalman Filter and its ability to online train a linear regression model. In <a href="/cointegration-pairs-trading.html" title="last post">last post</a> we have also seen the idea of cointegration and pairs trading. As pointed out at the end of last post, one way to avoid <a href="https://www.investopedia.com/terms/l/lookaheadbias.asp" target="_blank" rel="noopener">look-ahead bias</a> and gain <a href="https://en.wikipedia.org/wiki/Walk_forward_optimization" target="_blank" rel="noopener">walk forward analysis</a> is through Bayesian online training mechanism such as Kalman Filter. Today we'll apply this idea to pairs trading.</p>
<p>As usual, the backtest codes in this post is located <a href="https://github.com/letianzj/QuantResearch/tree/master/backtest" target="_blank" rel="noopener">here on Github</a>.</p>
<a id="more"></a>
<h2 id="pairs-trading-via-kalman-filter">Pairs Trading via Kalman Filter</h2>
<p>The idea is simple. Because we can obtain pairs trading hedge coefifcient through linear regression, and linear regression can be solved by Kalman Filter as in <a href="/kalman-filter-linear-regression.html" title="this post">this post</a>, therefore we can link the pairs through Kalman Filter. In this post we are going to use <a href="https://github.com/pykalman/pykalman" target="_blank" rel="noopener">PyKalman package</a>, so the only thing you need to do is to understand the concept and then express the problem in Bayesian format. Let's inherit the notations from previous post (refer to as Prev).</p>
<p>The state variables are still the intercept <span class="math inline">\(a_k\)</span> and the slope <span class="math inline">\(b_k\)</span> as in Prev<span class="math inline">\((2.1)\)</span>. But this time let's observe one <span class="math inline">\(y_t\)</span> a time. So Prev<span class="math inline">\((2.2)\)</span> is re-written as</p>
<p><span class="math display">\[
y_t=[1,x_t]\begin{bmatrix} a_t \\\\ b_t \end{bmatrix}+v_t
\tag{2.1}
\]</span></p>
<p>If we consider the case EWA as indepedent variable <span class="math inline">\(x\)</span> and EWC as depedent variable <span class="math inline">\(y\)</span>, then the setting corresponds to</p>
<p><span class="math display">\[
\begin{array}{lcl}
G_t &=&I \\\\
\theta_t&=&\begin{bmatrix} a_t \\\\ b_t \end{bmatrix} \\\\
F_t&=&[1,x_t]
\end{array}
\tag{2.2}
\]</span></p>
<p>in Prev<span class="math inline">\((A.1)\)</span> and Prev<span class="math inline">\((A.2)\)</span>. Notice that the observation matrix <span class="math inline">\(F_t\)</span> changes everytime with new EWA price <span class="math inline">\(x_t\)</span>.</p>
<p>The following code explorer the relationship betwen EWA and EWC as a scatterplot colored by time.</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">cm = plt.get_cmap(<span class="string">'jet'</span>)</span><br><span class="line">colors = np.linspace(<span class="number">0.1</span>, <span class="number">1</span>, data.shape[<span class="number">0</span>])</span><br><span class="line">sc = plt.scatter(data[sym_a], data[sym_b], s=<span class="number">10</span>, c=colors, cmap=cm, edgecolors=<span class="string">'k'</span>, alpha=<span class="number">0.7</span>)</span><br><span class="line">cb = plt.colorbar(sc)</span><br><span class="line">cb.ax.set_yticklabels(str(p.date()) <span class="keyword">for</span> p <span class="keyword">in</span> data[::data.shape[<span class="number">0</span>]//<span class="number">9</span>].index)</span><br><span class="line">plt.xlabel(<span class="string">'EWA'</span>)</span><br><span class="line">plt.ylabel(<span class="string">'EWC'</span>)</span><br><span class="line">plt.show()</span><br></pre></td></tr></table></figure>
<!--<img src="time_varying_scatterplot.png" align="center" width="80%" height="80%">-->
<img src="/kalman-filter-pairs-trading/time_varying_scatterplot.png" class="" title="Time Varying Scatterplot">
<p>From the scatterplot we can tell that their relationship changes between year 2010 and 2018. Therefore, the hedge ratio changes over time and our strategy needs to adapt to it. Otherwise using a static hedge ratio from linear regression would result in over- or under- hedge.</p>
<p>That is when Kalman Filter comes in to help. This time instead of do it manually, let's model Kalman filter with the help of pykalman package.</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># observation matrix F is 2-dimensional, containing sym_a price and 1</span></span><br><span class="line"><span class="comment"># there are data.shape[0] observations</span></span><br><span class="line">obs_mat_F = np.transpose(np.vstack([data[sym_a].values, np.ones(data.shape[<span class="number">0</span>])])).reshape(<span class="number">-1</span>, <span class="number">1</span>, <span class="number">2</span>)</span><br><span class="line"></span><br><span class="line">kf = KalmanFilter(n_dim_obs=<span class="number">1</span>, <span class="comment"># y is 1-dimensional</span></span><br><span class="line"> n_dim_state=<span class="number">2</span>, <span class="comment"># states (alpha, beta) is 2-dimensinal</span></span><br><span class="line"> initial_state_mean=np.ones(<span class="number">2</span>), <span class="comment"># initial value of intercept and slope theta0|0</span></span><br><span class="line"> initial_state_covariance=np.ones((<span class="number">2</span>, <span class="number">2</span>)), <span class="comment"># initial cov matrix between intercept and slope P0|0</span></span><br><span class="line"> transition_matrices=np.eye(<span class="number">2</span>), <span class="comment"># G, constant</span></span><br><span class="line"> observation_matrices=obs_mat_F, <span class="comment"># F, depends on x</span></span><br><span class="line"> observation_covariance=<span class="number">1</span>, <span class="comment"># v_t, constant</span></span><br><span class="line"> transition_covariance= np.eye(<span class="number">2</span>)) <span class="comment"># w_t, constant</span></span><br><span class="line"></span><br><span class="line">state_means, state_covs = kf.filter(data[sym_b]) <span class="comment"># observes sym_b price</span></span><br><span class="line">beta_kf = pd.DataFrame({<span class="string">'Slope'</span>: state_means[:, <span class="number">0</span>], <span class="string">'Intercept'</span>: state_means[:, <span class="number">1</span>]}, index=data.index)</span><br><span class="line">beta_kf.plot(subplots=<span class="literal">True</span>)</span><br><span class="line">plt.show()</span><br></pre></td></tr></table></figure>
<p>The code above is well commented. First fill in every input parameters based on your model design, and then just call kf.filter function to perform Kalman Filter. Note that the results are sensitive to your inputs such as your belief on <strong>observation_covariance</strong> and <strong>transition_covariance</strong> because they don't get adjusted over time.</p>
<!--<img src="time_varying_parameters.png" align="center" width="80%" height="80%">-->
<img src="/kalman-filter-pairs-trading/time_varying_parameters.png" class="" title="Time Varying Parameters">
<p>From the figure above it seems slope between EWA and EWC is pretty stable around <span class="math inline">\(0.85\)</span>.</p>
<p>We can see how the regression line evolves over time, and relative to the line in black, which is the OLS line fitted to the whole dataset.</p>
<!--<img src="time_varying_regression.png" align="center" width="80%" height="80%">-->
<img src="/kalman-filter-pairs-trading/time_varying_regression.png" class="" title="Time Varying Regression">
<p>Last but not least, above codes work correctly but if we want to use Kalman filter in practce we have to take a different approach. That is, we want it to be updated step by step. Fortunately PyKalman also prvoides a function called <strong>kf.filter_update</strong> that serves this purpose. The code is a bit too long to fit here so I relegate it on <a href="https://github.com/letianzj/QuantResearch/blob/master/notebooks/pairs_trading_kalman_filter.py" target="_blank" rel="noopener">github</a>. You are encouraged to run it to see the equivalence but the latter allows for model updates every day upon new EWA and EWC prices, which will in turn be used in the next section.</p>
<h2 id="pairs-trading-backtest">Pairs Trading Backtest</h2>
<p>It is time to backtest the EWA-EWC pairs trading on the <a href="https://en.wikipedia.org/wiki/Bollinger_Bands" target="_blank" rel="noopener">Bollinger-bands strategy</a> via Kalman Filter updates. The strategy is the same as <a href="/cointegration-pairs-trading.html" title="last post">last post</a>. This allows us to compare the results with simple linear regression.</p>
<p>There is one thing needs to be pointed out in order to better understand the code, that is, <strong>the measurement error given in Pre<span class="math inline">\((A.5)\)</span> is actually the spread at time k</strong>. To see this, notice that the first item on the right-hand side, <span class="math inline">\(y_k\)</span>, is the EWC price, and the second item,</p>
<p><span class="math display">\[
F_k\hat{\theta}_{k|k-1}=a_k+b_k*x_k
\tag{3.1}
\]</span></p>
<p>is the hedge side of EWA.</p>
<p>By the same logic, <strong>Pre<span class="math inline">\((A.6)\)</span> is the variance of spread</strong>. In addition, Pre<span class="math inline">\((A.2)\)</span> assumes the spread/eror term is normally distributed with zero mean and variance of Pre<span class="math inline">\((A.6)\)</span>. Therefore Pre<span class="math inline">\((A.5)\)</span> and Pre<span class="math inline">\((A.6)\)</span> provide the moving average and moving standard deviation (as sqaure root of variance) for Bollinger bands.</p>
<p>Unfortunately PyKalman package doesn't return them directly so we have to calculate them manually in the strategy. Here is the trading logic (also see [1]). Full code can be found <a href="https://github.com/letianzj/QuantResearch/tree/master/backtest" target="_blank" rel="noopener">here on github</a>.</p>
<ol type="1">
<li>On each day, observe EWA price <span class="math inline">\(x_t\)</span> and EWC price <span class="math inline">\(y_t\)</span></li>
<li>Calculate Pre<span class="math inline">\(A.5\)</span> and Pre<span class="math inline">\(A.6\)</span> as current spread and its variance</li>
<li>Let Bollinger band be <span class="math inline">\(\hat{y}_{k}\pm\delta\sqrt{S_k}\)</span></li>
</ol>
<p>The backtest result is shown as follows. It seems the strategy was good until year 2017.</p>
<!--<img src="backtest_results.png" align="center" width="80%" height="80%">-->
<img src="/kalman-filter-pairs-trading/backtest_results.png" class="" title="Backtest Results">
<p><strong>Reference</strong> * [1] Chan, Ernie. Algorithmic trading: winning strategies and their rationale. Vol. 625. John Wiley & Sons, 2013.</p>
<ul>
<li><p>[2] Haohan Wang, 2015. <a href="https://medium.com/@haohanwang/kalman-filters-and-pairs-trading-1-5d191032234" target="_blank" rel="noopener">Kalman Filters and Pairs Trading 1</a></p></li>
<li><p>[3] Haohan Wang, 2015. <a href="https://medium.com/@haohanwang/kalman-filters-and-pairs-trading-2-aa1f05ad9ff5" target="_blank" rel="noopener">Kalman Filters and Pairs Trading 2</a></p></li>
<li><p>[4] Halls-Moore, M. (2014). <a href="https://www.quantstart.com/articles/Backtesting-An-Intraday-Mean-Reversion-Pairs-Strategy-Between-SPY-And-IWM" target="_blank" rel="noopener">Backtesting An Intraday Mean Reversion Pairs Strategy Between SPY And IWM</a></p></li>
<li><p>[5] Halls-Moore, M. (2016). <a href="https://www.quantstart.com/articles/Dynamic-Hedge-Ratio-Between-ETF-Pairs-Using-the-Kalman-Filter" target="_blank" rel="noopener">Dynamic Hedge Ratio Between ETF Pairs Using the Kalman Filter</a></p></li>
<li><p>[6] Quantopian, David Edwards. <a href="https://www.quantopian.com/lectures/example-kalman-filter-pairs-trade" target="_blank" rel="noopener">Example: Kalman Filter Pairs Trade</a></p></li>
</ul>
<p><strong>DISCLAIMER: This post is for the purpose of research and backtest only. The author doesn't promise any future profits and doesn't take responsibility for any trading losses.</strong></p>
</div>
<div>
<ul class="post-copyright">
<li class="post-copyright-author">
<strong>Post author: </strong>Letian Wang
</li>
<li class="post-copyright-link">
<strong>Post link: </strong>
<a href="https://letianzj.github.io/kalman-filter-pairs-trading.html" title="Kalman Filter and Pairs Trading">https://letianzj.github.io/kalman-filter-pairs-trading.html</a>
</li>
<li class="post-copyright-license">
<strong>Copyright Notice: </strong>All articles in this blog are licensed under <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> unless stating additionally.
</li>
</ul>
</div>
<footer class="post-footer">
<div class="post-tags">
<a href="/tags/Systematic-Investment/" rel="tag"># Systematic Investment</a>
<a href="/tags/Quantitative-Trading/" rel="tag"># Quantitative Trading</a>
</div>
<div class="post-nav">
<div class="post-nav-item">
<a href="/cointegration-pairs-trading.html" rel="prev" title="Cointegration and Pairs Trading">
<i class="fa fa-chevron-left"></i> Cointegration and Pairs Trading
</a></div>
<div class="post-nav-item">
<a href="/hidden-markov-chain.html" rel="next" title="Hidden Markov Chain and Stock Market Regimes">
Hidden Markov Chain and Stock Market Regimes <i class="fa fa-chevron-right"></i>
</a></div>
</div>
</footer>
</article>
</div>
<div class="comments">
<div id="disqus_thread">
<noscript>Please enable JavaScript to view the comments powered by Disqus.</noscript>
</div>
</div>
<script>
window.addEventListener('tabs:register', () => {
let { activeClass } = CONFIG.comments;
if (CONFIG.comments.storage) {
activeClass = localStorage.getItem('comments_active') || activeClass;
}
if (activeClass) {
let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
if (activeTab) {
activeTab.click();
}
}
});
if (CONFIG.comments.storage) {
window.addEventListener('tabs:click', event => {
if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
let commentClass = event.target.classList[1];
localStorage.setItem('comments_active', commentClass);
});
}
</script>
</div>
<div class="toggle sidebar-toggle">
<span class="toggle-line toggle-line-first"></span>
<span class="toggle-line toggle-line-middle"></span>
<span class="toggle-line toggle-line-last"></span>
</div>
<aside class="sidebar">
<div class="sidebar-inner">
<ul class="sidebar-nav motion-element">
<li class="sidebar-nav-toc">
Table of Contents
</li>
<li class="sidebar-nav-overview">
Overview
</li>
</ul>
<!--noindex-->
<div class="post-toc-wrap sidebar-panel">
<div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#introduction"><span class="nav-number">1.</span> <span class="nav-text">Introduction</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#pairs-trading-via-kalman-filter"><span class="nav-number">2.</span> <span class="nav-text">Pairs Trading via Kalman Filter</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#pairs-trading-backtest"><span class="nav-number">3.</span> <span class="nav-text">Pairs Trading Backtest</span></a></li></ol></div>
</div>
<!--/noindex-->
<div class="site-overview-wrap sidebar-panel">
<div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
<img class="site-author-image" itemprop="image" alt="Letian Wang"
src="/images/avatar.jpg">
<p class="site-author-name" itemprop="name">Letian Wang</p>
<div class="site-description" itemprop="description">Letian Wang blog to discuss quantitative trading strategies, portfolio management, risk premia, risk management, systematic trading, and machine learning, deep learning applications in Finance.</div>
</div>
<div class="site-state-wrap motion-element">
<nav class="site-state">
<div class="site-state-item site-state-posts">
<a href="/archives/">
<span class="site-state-item-count">24</span>
<span class="site-state-item-name">posts</span>
</a>
</div>
<div class="site-state-item site-state-categories">
<span class="site-state-item-count">24</span>
<span class="site-state-item-name">categories</span>
</div>
<div class="site-state-item site-state-tags">
<span class="site-state-item-count">20</span>
<span class="site-state-item-name">tags</span>
</div>
</nav>
</div>
<div class="links-of-author motion-element">
<span class="links-of-author-item">
<a href="https://github.com/letianzj" title="GitHub → https://github.com/letianzj" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
</span>
<span class="links-of-author-item">
<a href="mailto:letian.zj@gmail.com" title="E-Mail → mailto:letian.zj@gmail.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
</span>
<span class="links-of-author-item">
<a href="https://twitter.com/letian781" title="Twitter → https://twitter.com/letian781" rel="noopener" target="_blank"><i class="fab fa-twitter fa-fw"></i>Twitter</a>
</span>
<span class="links-of-author-item">
<a href="https://youtu.be/CrsrTxqiXNY" title="YouTube → https://youtu.be/CrsrTxqiXNY" rel="noopener" target="_blank"><i class="fab fa-youtube fa-fw"></i>YouTube</a>
</span>
<span class="links-of-author-item">
<a href="https://www.linkedin.com/in/letian-wang-phd-cfa-frm/" title="Linkedin → https://www.linkedin.com/in/letian-wang-phd-cfa-frm/" rel="noopener" target="_blank"><i class="fab fa-linkedin fa-fw"></i>Linkedin</a>
</span>
</div>
</div>
</div>
</aside>
<div id="sidebar-dimmer"></div>
</div>
</main>
<footer class="footer">
<div class="footer-inner">
<div class="copyright">
©
<span itemprop="copyrightYear">2020</span>
<span class="with-love">
<i class="fa fa-heart"></i>
</span>
<span class="author" itemprop="copyrightHolder">Letian Wang</span>
</div>
<div class="powered-by">Powered by <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://muse.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a>
</div>
</div>
</footer>
</div>
<script src="/lib/anime.min.js"></script>
<script src="/lib/velocity/velocity.min.js"></script>
<script src="/lib/velocity/velocity.ui.min.js"></script>
<script src="/js/utils.js"></script>
<script src="/js/motion.js"></script>
<script src="/js/schemes/muse.js"></script>
<script src="/js/next-boot.js"></script>
<script>
(function(){
var canonicalURL, curProtocol;
//Get the <link> tag
var x=document.getElementsByTagName("link");
//Find the last canonical URL
if(x.length > 0){
for (i=0;i<x.length;i++){
if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
canonicalURL=x[i].href;
}
}
}
//Get protocol
if (!canonicalURL){
curProtocol = window.location.protocol.split(':')[0];
}
else{
curProtocol = canonicalURL.split(':')[0];
}
//Get current URL if the canonical URL does not exist
if (!canonicalURL) canonicalURL = window.location.href;
//Assign script content. Replace current URL with the canonical URL
!function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
</script>
<script>
if (typeof MathJax === 'undefined') {
window.MathJax = {
loader: {
source: {
'[tex]/amsCd': '[tex]/amscd',
'[tex]/AMScd': '[tex]/amscd'
}
},
tex: {
inlineMath: {'[+]': [['$', '$']]},
tags: 'ams'
},
options: {
renderActions: {
findScript: [10, doc => {
document.querySelectorAll('script[type^="math/tex"]').forEach(node => {
const display = !!node.type.match(/; *mode=display/);
const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display);
const text = document.createTextNode('');
node.parentNode.replaceChild(text, node);
math.start = {node: text, delim: '', n: 0};
math.end = {node: text, delim: '', n: 0};
doc.math.push(math);
});
}, '', false],
insertedScript: [200, () => {
document.querySelectorAll('mjx-container').forEach(node => {
let target = node.parentNode;
if (target.nodeName.toLowerCase() === 'li') {
target.parentNode.classList.add('has-jax');
}
});
}, '', false]
}
}
};
(function () {
var script = document.createElement('script');
script.src = '//cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js';
script.defer = true;
document.head.appendChild(script);
})();
} else {
MathJax.startup.document.state(0);
MathJax.texReset();
MathJax.typeset();
}
</script>
<script>
function loadCount() {
var d = document, s = d.createElement('script');
s.src = 'https://https-letianzj-github-io.disqus.com/count.js';
s.id = 'dsq-count-scr';
(d.head || d.body).appendChild(s);
}
// defer loading until the whole page loading is completed
window.addEventListener('load', loadCount, false);
</script>
<script>
var disqus_config = function() {
this.page.url = "https://letianzj.github.io/kalman-filter-pairs-trading.html";
this.page.identifier = "kalman-filter-pairs-trading.html";
this.page.title = "Kalman Filter and Pairs Trading";
};
NexT.utils.loadComments(document.querySelector('#disqus_thread'), () => {
if (window.DISQUS) {
DISQUS.reset({
reload: true,
config: disqus_config
});
} else {
var d = document, s = d.createElement('script');
s.src = 'https://https-letianzj-github-io.disqus.com/embed.js';
s.setAttribute('data-timestamp', '' + +new Date());
(d.head || d.body).appendChild(s);
}
});
</script>
</body>
</html>