-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathmarkets_trading.Rnw
5733 lines (5263 loc) · 225 KB
/
markets_trading.Rnw
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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
% Define knitr options
% !Rnw weave=knitr
% Set global chunk options
<<knitr_setup,include=FALSE,cache=FALSE>>=
library(knitr)
opts_chunk$set(prompt=TRUE, eval=FALSE, tidy=FALSE, strip.white=FALSE, comment=NA, highlight=FALSE, message=FALSE, warning=FALSE, size="tiny", fig.width=6, fig.height=5)
options(width=80, dev="pdf")
options(digits=3)
thm <- knit_theme$get("acid")
knit_theme$set(thm)
@
% Define document options
\documentclass[9pt]{beamer}
\DeclareMathSizes{8pt}{6pt}{6pt}{5pt}
\mode<presentation>
\usetheme{AnnArbor}
% \usecolortheme{whale}
% Uncover everything in a step-wise fashion
% \beamerdefaultoverlayspecification{<+->}
% \usepackage{caption}
% tikz package for plotting and tables
\usepackage{tikz}
\usetikzlibrary{positioning}
\usepackage{array}
\usepackage{multirow}
% mathtools package for math symbols
\usepackage{mathtools}
% bbm package for unitary vector or matrix symbol
\usepackage{bbm}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{amsfonts}
\usepackage[latin1]{inputenc}
\usepackage{hyperref}
\usepackage{fancybox}
\usepackage{url}
\usepackage[backend=bibtex,style=alphabetic]{biblatex} % bibstyle=numeric
\usepackage{listings}
\usepackage{xcolor}
\definecolor{cmd_background}{rgb}{0.2, 0.2, 0.0}
\definecolor{vba_background}{rgb}{0.0, 0.0, 0.9}
% \colorlet{cmd_background_light}{cmd_background!20!black}
% \bibliographystyle{amsalpha} % doesn't work
% \addbibresource{FRE_lectures.bib}
% \addbibresource[location=remote]{http://www.citeulike.org/user/jerzyp}
\renewcommand\bibfont{\footnotesize}
\renewcommand{\pgfuseimage}[1]{\scalebox{0.75}{\includegraphics{#1}}} % scale bib icons
\setbeamertemplate{bibliography item}[text] % set bib icons
% \setbeamertemplate{bibliography item}{} % remove bib icons
% \usepackage{enumerate}
% \let\emph\textbf
% \let\alert\textbf
% Define colors for hyperlinks
\definecolor{links}{HTML}{2A1B81}
\hypersetup{colorlinks=true,linkcolor=,urlcolor=links}
% Make url text scriptsize
\renewcommand\UrlFont{\scriptsize}
% Make institute text italic and small
\setbeamerfont{institute}{size=\small,shape=\itshape}
\setbeamerfont{date}{size=\small}
\setbeamerfont{block title}{size=\normalsize} % shape=\itshape
\setbeamerfont{block body}{size=\footnotesize}
% Title page setup
\title[Markets and Trading]{Markets and Trading}
\subtitle{FRE6871 \& FRE7241, Fall 2024}
\institute[NYU Tandon]{NYU Tandon School of Engineering}
\titlegraphic{\includegraphics[scale=0.2]{image/tandon_long_color.png}}
\author[Jerzy Pawlowski]{Jerzy Pawlowski \emph{\href{mailto:jp3900@nyu.edu}{jp3900@nyu.edu}}}
\date{\today}
%%%%%%%%%%%%%%%
\begin{document}
%%%%%%%%%%%%%%%
\maketitle
%%%%%%%%%%%%%%%
\section{Bonds and Interest Rates}
%%%%%%%%%%%%%%%
\subsection{Downloading Treasury Bond Rates from \protect\emph{FRED}}
\begin{frame}[fragile,t]{\subsecname}
\vspace{-1em}
\begin{block}{}
\begin{columns}[T]
\column{0.5\textwidth}
The constant maturity Treasury rates are yields of hypothetical fixed-maturity bonds, interpolated from the market yields of actual Treasury bonds.
\vskip1ex
The \emph{FRED} database contains current and historical constant maturity Treasury rates, \\
\hskip1em\url{https://fred.stlouisfed.org/series/DGS5}
\vskip1ex
\texttt{quantmod::getSymbols()} creates objects in the specified \emph{environment} from the input strings (names).
\vskip1ex
It then assigns the data to those objects, without returning them as a function value, as a \emph{side effect}.
<<echo=TRUE,eval=FALSE>>=
# Symbols for constant maturity Treasury rates
symbolv <- c("DGS1", "DGS2", "DGS5", "DGS10", "DGS20", "DGS30")
# Create new environment for time series
ratesenv <- new.env()
# Download time series for symbolv into ratesenv
quantmod::getSymbols(symbolv, env=ratesenv, src="FRED")
# Remove NA values in ratesenv
sapply(ratesenv, function(x) sum(is.na(x)))
sapply(ls(ratesenv), function(namev) {
assign(x=namev, value=na.omit(get(namev, ratesenv)),
envir=ratesenv)
}) # end sapply
sapply(ratesenv, function(x) sum(is.na(x)))
# Get class of all objects in ratesenv
sapply(ratesenv, class)
# Get class of all objects in R workspace
sapply(ls(), function(namev) class(get(namev)))
# Save the time series environment into a binary .RData file
save(ratesenv, file="/Users/jerzy/Develop/lecture_slides/data/rates_data.RData")
@
\column{0.5\textwidth}
\includegraphics[width=0.45\paperwidth]{figure/treas_10y_rate.png}
<<echo=TRUE,eval=FALSE>>=
# Get class of time series object DGS10
class(get(x="DGS10", envir=ratesenv))
# Another way
class(ratesenv$DGS10)
# Get first 6 rows of time series
head(ratesenv$DGS10)
# Plot dygraphs of 10-year Treasury rate
dygraphs::dygraph(ratesenv$DGS10, main="10-year Treasury Rate") %>%
dyOptions(colors="blue", strokeWidth=2)
# Plot 10-year constant maturity Treasury rate
x11(width=6, height=5)
par(mar=c(2, 2, 0, 0), oma=c(0, 0, 0, 0))
chart_Series(ratesenv$DGS10["1990/"], name="10-year Treasury Rate")
@
\end{columns}
\end{block}
\end{frame}
%%%%%%%%%%%%%%%
\subsection{Treasury Yield Curve}
\begin{frame}[fragile,t]{\subsecname}
\vspace{-1em}
\begin{block}{}
\begin{columns}[T]
\column{0.5\textwidth}
The \emph{yield curve} is a vector of interest rates at different maturities, on a given date.
\vskip1ex
The \emph{yield curve} shape changes depending on the economic conditions: in recessions rates drop and the curve flattens, while in expansions rates rise and the curve steepens.
<<echo=TRUE,eval=FALSE>>=
# Load constant maturity Treasury rates
load(file="/Users/jerzy/Develop/lecture_slides/data/rates_data.RData")
# Get most recent yield curve
ycnow <- eapply(ratesenv, xts::last)
class(ycnow)
ycnow <- do.call(cbind, ycnow)
# Check if 2020-03-25 is not a holiday
date2020 <- as.Date("2020-03-25")
weekdays(date2020)
# Get yield curve from 2020-03-25
yc2020 <- eapply(ratesenv, function(x) x[date2020])
yc2020 <- do.call(cbind, yc2020)
# Combine the yield curves
ycurves <- c(yc2020, ycnow)
# Rename columns and rows, sort columns, and transpose into matrix
colnames(ycurves) <- substr(colnames(ycurves), start=4, stop=11)
ycurves <- ycurves[, order(as.numeric(colnames(ycurves)))]
colnames(ycurves) <- paste0(colnames(ycurves), "yr")
ycurves <- t(ycurves)
colnames(ycurves) <- substr(colnames(ycurves), start=1, stop=4)
@
\column{0.5\textwidth}
\vspace{-1em}
\includegraphics[width=0.45\paperwidth]{figure/yield_curve.png}
<<echo=(-(1:2)),eval=FALSE>>=
x11(width=6, height=5)
par(mar=c(3, 3, 2, 0), oma=c(0, 0, 0, 0), mgp=c(2, 1, 0))
# Plot using matplot()
colorv <- c("blue", "red")
matplot(ycurves, main="Yield Curves in 2020 and 2023", xaxt="n", lwd=3, lty=1,
type="l", xlab="maturity", ylab="yield", col=colorv)
# Add x-axis
axis(1, seq_along(rownames(ycurves)), rownames(ycurves))
# Add legend
legend("topleft", legend=colnames(ycurves), y.intersp=0.1,
bty="n", col=colorv, lty=1, lwd=6, inset=0.05, cex=1.0)
@
\end{columns}
\end{block}
\end{frame}
%%%%%%%%%%%%%%%
\subsection{Treasury Yield Curve Over Time}
\begin{frame}[fragile,t]{\subsecname}
\vspace{-1em}
\begin{block}{}
\begin{columns}[T]
\column{0.5\textwidth}
The \emph{yield curve} has changed shape dramatically depending on the economic conditions: in recessions rates drop and the curve flattens, while in expansions rates rise and the curve steepens.
<<echo=(-(1:2)),eval=FALSE>>=
x11(width=6, height=5)
par(mar=c(3, 3, 2, 0), oma=c(0, 0, 0, 0), mgp=c(2, 1, 0))
# Load constant maturity Treasury rates
load(file="/Users/jerzy/Develop/lecture_slides/data/rates_data.RData")
# Get end-of-year dates since 2006
datev <- xts::endpoints(ratesenv$DGS1["2006/"], on="years")
datev <- zoo::index(ratesenv$DGS1["2006/"][datev])
# Create time series of end-of-year rates
ycurves <- eapply(ratesenv, function(ratev) ratev[datev])
ycurves <- rutils::do_call(cbind, ycurves)
# Rename columns and rows, sort columns, and transpose into matrix
colnames(ycurves) <- substr(colnames(ycurves), start=4, stop=11)
ycurves <- ycurves[, order(as.numeric(colnames(ycurves)))]
colnames(ycurves) <- paste0(colnames(ycurves), "yr")
ycurves <- t(ycurves)
colnames(ycurves) <- substr(colnames(ycurves), start=1, stop=4)
# Plot matrix using plot.zoo()
colorv <- colorRampPalette(c("red", "blue"))(NCOL(ycurves))
plot.zoo(ycurves, main="Yield Curve Since 2006", lwd=3, xaxt="n",
plot.type="single", xlab="maturity", ylab="yield", col=colorv)
# Add x-axis
axis(1, seq_along(rownames(ycurves)), rownames(ycurves))
# Add legend
legend("topleft", legend=colnames(ycurves), y.intersp=0.1,
bty="n", col=colorv, lty=1, lwd=4, inset=0.05, cex=0.8)
@
\column{0.5\textwidth}
\vspace{-1em}
\includegraphics[width=0.45\paperwidth]{figure/yield_curve_time.png}
<<echo=TRUE,eval=FALSE>>=
# Alternative plot using matplot()
matplot(ycurves, main="Yield curve since 2006", xaxt="n", lwd=3, lty=1,
type="l", xlab="maturity", ylab="yield", col=colorv)
# Add x-axis
axis(1, seq_along(rownames(ycurves)), rownames(ycurves))
# Add legend
legend("topleft", legend=colnames(ycurves), y.intersp=0.1,
bty="n", col=colorv, lty=1, lwd=4, inset=0.05, cex=0.8)
@
\end{columns}
\end{block}
\end{frame}
%%%%%%%%%%%%%%%
\subsection{Covariance Matrix of Interest Rates}
\begin{frame}[fragile,t]{\subsecname}
\vspace{-1em}
\begin{block}{}
\begin{columns}[T]
\column{0.5\textwidth}
The covariance matrix $\mathbb{C}$, of the interest rate matrix $\mathbf{r}$ is given by:
\begin{displaymath}
\mathbb{C} = \frac{(\mathbf{r} - \bar{\mathbf{r}})^T (\mathbf{r} - \bar{\mathbf{r}})} {n-1}
\end{displaymath}
<<echo=TRUE,eval=FALSE>>=
# Extract rates from ratesenv
symbolv <- c("DGS1", "DGS2", "DGS5", "DGS10", "DGS20")
ratem <- mget(symbolv, envir=ratesenv)
ratem <- rutils::do_call(cbind, ratem)
ratem <- zoo::na.locf(ratem, na.rm=FALSE)
ratem <- zoo::na.locf(ratem, fromLast=TRUE)
# Calculate daily percentage rates changes
retp <- rutils::diffit(log(ratem))
# Center (de-mean) the returns
retp <- lapply(retp, function(x) {x - mean(x)})
retp <- rutils::do_call(cbind, retp)
sapply(retp, mean)
# Covariance and Correlation matrices of Treasury rates
covmat <- cov(retp)
cormat <- cor(retp)
# Reorder correlation matrix based on clusters
library(corrplot)
ordern <- corrMatOrder(cormat, order="hclust",
hclust.method="complete")
cormat <- cormat[ordern, ordern]
@
\column{0.5\textwidth}
\vspace{-1em}
\includegraphics[width=0.4\paperwidth]{figure/yield_cor.png}
<<echo=TRUE,eval=FALSE>>=
# Plot the correlation matrix
x11(width=6, height=6)
colorv <- colorRampPalette(c("red", "white", "blue"))
corrplot(cormat, title=NA, tl.col="black",
method="square", col=colorv(NCOL(cormat)), tl.cex=0.8,
cl.offset=0.75, cl.cex=0.7, cl.align.text="l", cl.ratio=0.25)
title("Correlation of Treasury Rates", line=1)
# Draw rectangles on the correlation matrix plot
corrRect.hclust(cormat, k=NROW(cormat) %/% 2,
method="complete", col="red")
@
\end{columns}
\end{block}
\end{frame}
%%%%%%%%%%%%%%%
\subsection{Principal Component Vectors}
\begin{frame}[fragile,t]{\subsecname}
\vspace{-1em}
\begin{block}{}
\begin{columns}[T]
\column{0.5\textwidth}
\emph{Principal components} are linear combinations of the \texttt{k} return vectors $\mathbf{r}_i$:
\begin{displaymath}
\mathbf{pc}_j = \sum_{i=1}^k {w_{ij} \, \mathbf{r}_i}
\end{displaymath}
Where $\mathbf{w}_j$ is a vector of weights (loadings) of the \emph{principal component} \texttt{j}, with $\mathbf{w}_j^T \mathbf{w}_j = 1$.
\vskip1ex
The weights $\mathbf{w}_j$ are chosen to maximize the variance of the \emph{principal components}, under the condition that they are orthogonal:
\begin{align*}
\mathbf{w}_j = {\operatorname{\arg \, \max}} \, \left\{ \mathbf{pc}_j^T \, \mathbf{pc}_j \right\} \\
\mathbf{pc}_i^T \, \mathbf{pc}_j = 0 \> (i \neq j)
\end{align*}
\vspace{-1em}
<<echo=TRUE,eval=FALSE>>=
# Create initial vector of portfolio weights
nweights <- NROW(symbolv)
weightv <- rep(1/sqrt(nweights), nweights)
names(weightv) <- symbolv
# Objective function equal to minus portfolio variance
objfun <- function(weightv, retp) {
retp <- retp %*% weightv
-1e7*var(retp) + 1e7*(1 - sum(weightv*weightv))^2
} # end objfun
# Objective function for equal weight portfolio
objfun(weightv, retp)
# Compare speed of vector multiplication methods
library(microbenchmark)
summary(microbenchmark(
transp=t(retp) %*% retp,
sumv=sum(retp*retp),
times=10))[, c(1, 4, 5)]
@
\column{0.5\textwidth}
\includegraphics[width=0.35\paperwidth]{figure/pca_rates_load1.png}
<<echo=TRUE,eval=FALSE>>=
# Find weights with maximum variance
optiml <- optim(par=weightv,
fn=objfun,
retp=retp,
method="L-BFGS-B",
upper=rep(5.0, nweights),
lower=rep(-5.0, nweights))
# Optimal weights and maximum variance
weights1 <- optiml$par
objfun(weights1, retp)
# Plot first principal component loadings
x11(width=6, height=5)
par(mar=c(3, 3, 2, 1), oma=c(0, 0, 0, 0), mgp=c(2, 1, 0))
barplot(weights1, names.arg=names(weights1),
xlab="", ylab="", main="First Principal Component Loadings")
@
\end{columns}
\end{block}
\end{frame}
%%%%%%%%%%%%%%%
\subsection{Higher Order Principal Components}
\begin{frame}[fragile,t]{\subsecname}
\vspace{-1em}
\begin{block}{}
\begin{columns}[T]
\column{0.5\textwidth}
The \emph{second principal component} can be calculated by maximizing its variance, under the constraint that it must be orthogonal to the \emph{first principal component}.
\vskip1ex
Similarly, higher order \emph{principal components} can be calculated by maximizing their variances, under the constraint that they must be orthogonal to all the previous \emph{principal components}.
\vskip1ex
The number of principal components is equal to the dimension of the covariance matrix.
<<echo=TRUE,eval=FALSE>>=
# pc1 weights and returns
pc1 <- drop(retp %*% weights1)
# Redefine objective function
objfun <- function(weightv, retp) {
retp <- retp %*% weightv
-1e7*var(retp) + 1e7*(1 - sum(weightv^2))^2 +
1e7*sum(weights1*weightv)^2
} # end objfun
# Find second principal component weights
optiml <- optim(par=weightv,
fn=objfun,
retp=retp,
method="L-BFGS-B",
upper=rep(5.0, nweights),
lower=rep(-5.0, nweights))
@
\column{0.5\textwidth}
\vspace{-1em}
\includegraphics[width=0.35\paperwidth]{figure/pca_rates_load2.png}
<<echo=TRUE,eval=FALSE>>=
# pc2 weights and returns
weights2 <- optiml$par
pc2 <- drop(retp %*% weights2)
sum(pc1*pc2)
# Plot second principal component loadings
barplot(weights2, names.arg=names(weights2),
xlab="", ylab="", main="Second Principal Component Loadings")
@
\end{columns}
\end{block}
\end{frame}
%%%%%%%%%%%%%%%
\subsection{Eigenvalues of the Covariance Matrix}
\begin{frame}[fragile,t]{\subsecname}
\vspace{-1em}
\begin{block}{}
\begin{columns}[T]
\column{0.5\textwidth}
The portfolio variance: $\mathbf{w}^T \mathbb{C} \, \mathbf{w}$ can be maximized under the \emph{quadratic} weights constraint $\mathbf{w}^T \mathbf{w} = 1$, by maximizing the \emph{Lagrangian} $\mathcal{L}$:
\begin{displaymath}
\mathcal{L} = \mathbf{w}^T \mathbb{C} \, \mathbf{w} \, - \, \lambda \, (\mathbf{w}^T \mathbf{w} - 1)
\end{displaymath}
Where $\lambda$ is a \emph{Lagrange multiplier}.
\vskip1ex
The maximum variance portfolio weights can be found by differentiating $\mathcal{L}$ with respect to $\mathbf{w}$ and setting it to zero:
\begin{displaymath}
\mathbb{C} \, \mathbf{w} = \lambda \, \mathbf{w}
\end{displaymath}
The above is the \emph{eigenvalue} equation of the covariance matrix $\mathbb{C}$, with the optimal weights $\mathbf{w}$ forming an \emph{eigenvector}, and $\lambda$ is the \emph{eigenvalue} corresponding to the \emph{eigenvector} $\mathbf{w}$.
\vskip1ex
The \emph{eigenvalues} are the variances of the \emph{eigenvectors}, and their sum is equal to the sum of the return variances:
\begin{displaymath}
\sum_{i=1}^k \lambda_i = \frac{1}{1-k} \sum_{i=1}^k {\mathbf{r}_i^T \mathbf{r}_i}
\end{displaymath}
\column{0.5\textwidth}
\vspace{-1em}
\includegraphics[width=0.35\paperwidth]{figure/pca_rates_eigenvalues.png}
<<echo=TRUE,eval=FALSE>>=
eigend <- eigen(covmat)
eigend$vectors
# Compare with optimization
all.equal(sum(diag(covmat)), sum(eigend$values))
all.equal(abs(eigend$vectors[, 1]), abs(weights1), check.attributes=FALSE)
all.equal(abs(eigend$vectors[, 2]), abs(weights2), check.attributes=FALSE)
all.equal(eigend$values[1], var(pc1), check.attributes=FALSE)
all.equal(eigend$values[2], var(pc2), check.attributes=FALSE)
# Eigenvalue equations are satisfied approximately
(covmat %*% weights1) / weights1 / var(pc1)
(covmat %*% weights2) / weights2 / var(pc2)
# Plot eigenvalues
barplot(eigend$values, names.arg=paste0("PC", 1:nweights),
las=3, xlab="", ylab="", main="Principal Component Variances")
@
\end{columns}
\end{block}
\end{frame}
%%%%%%%%%%%%%%%
\subsection{\protect\emph{Principal Component Analysis} Versus \protect\emph{Eigen Decomposition}}
\begin{frame}[fragile,t]{\subsecname}
\vspace{-1em}
\begin{block}{}
\begin{columns}[T]
\column{0.5\textwidth}
\emph{Principal Component Analysis} (\emph{PCA}) is equivalent to the \emph{eigen decomposition} of either the correlation or the covariance matrix.
\vskip1ex
If the input time series \emph{are} scaled, then \emph{PCA} is equivalent to the eigen decomposition of the \emph{correlation matrix}.
\vskip1ex
If the input time series \emph{are not} scaled, then \emph{PCA} is equivalent to the eigen decomposition of the \emph{covariance matrix}.
\vskip1ex
Scaling the input time series improves the accuracy of the \emph{PCA dimension reduction}, allowing a smaller number of \emph{principal components} to more accurately capture the data contained in the input time series.
\vskip1ex
The function \texttt{prcomp()} performs \emph{Principal Component Analysis} on a matrix of data (with the time series as columns), and returns the results as a list of class \texttt{prcomp}.
\vskip1ex
The \texttt{prcomp()} argument \texttt{scale=TRUE} specifies that the input time series should be scaled by their standard deviations.
\column{0.5\textwidth}
\vspace{-1em}
<<echo=TRUE,eval=FALSE>>=
# Eigen decomposition of correlation matrix
eigend <- eigen(cormat)
# Perform PCA with scaling
pcad <- prcomp(retp, scale=TRUE)
# Compare outputs
all.equal(eigend$values, pcad$sdev^2)
all.equal(abs(eigend$vectors), abs(pcad$rotation),
check.attributes=FALSE)
# Eigen decomposition of covariance matrix
eigend <- eigen(covmat)
# Perform PCA without scaling
pcad <- prcomp(retp, scale=FALSE)
# Compare outputs
all.equal(eigend$values, pcad$sdev^2)
all.equal(abs(eigend$vectors), abs(pcad$rotation),
check.attributes=FALSE)
@
\end{columns}
\end{block}
\end{frame}
%%%%%%%%%%%%%%%
\subsection{Principal Component Analysis of the Yield Curve}
\begin{frame}[fragile,t]{\subsecname}
\vspace{-1em}
\begin{block}{}
\begin{columns}[T]
\column{0.5\textwidth}
\emph{Principal Component Analysis} (\emph{PCA}) is a \emph{dimension reduction} technique, that explains the returns of a large number of correlated time series as linear combinations of a smaller number of principal component time series.
\vskip1ex
The input time series are often scaled by their standard deviations, to improve the accuracy of \emph{PCA dimension reduction}, so that more information is retained by the first few \emph{principal component} time series.
\vskip1ex
If the input time series are not scaled, then \emph{PCA} analysis is equivalent to the \emph{eigen decomposition} of the covariance matrix, and if they are scaled, then \emph{PCA} analysis is equivalent to the \emph{eigen decomposition} of the correlation matrix.
\vskip1ex
The function \texttt{prcomp()} performs \emph{Principal Component Analysis} on a matrix of data (with the time series as columns), and returns the results as a list of class \texttt{prcomp}.
\vskip1ex
The \texttt{prcomp()} argument \texttt{scale=TRUE} specifies that the input time series should be scaled by their standard deviations.
\column{0.5\textwidth}
\vspace{-1em}
\includegraphics[width=0.35\paperwidth]{figure/pca_rates_scree.png}\\
A \emph{scree plot} is a bar plot of the volatilities of the \emph{principal components}.
<<echo=TRUE,eval=FALSE>>=
# Perform principal component analysis PCA
pcad <- prcomp(retp, scale=TRUE)
# Plot standard deviations
barplot(pcad$sdev, names.arg=colnames(pcad$rotation),
las=3, xlab="", ylab="",
main="Scree Plot: Volatilities of Principal Components
of Treasury rates")
@
\end{columns}
\end{block}
\end{frame}
%%%%%%%%%%%%%%%
\subsection{Yield Curve Principal Component Loadings (Weights)}
\begin{frame}[fragile,t]{\subsecname}
\vspace{-1em}
\begin{block}{}
\begin{columns}[T]
\column{0.5\textwidth}
\emph{Principal component} loadings are the weights of portfolios which have mutually orthogonal returns.
\vskip1ex
The \emph{principal component} portfolios represent the different orthogonal modes of the data variance.
\vskip1ex
The first \emph{principal component} of the \emph{yield curve} is the correlated movement of all rates up and down.
\vskip1ex
The second \emph{principal component} is \emph{yield curve} steepening and flattening.
\vskip1ex
The third \emph{principal component} is the \emph{yield curve} butterfly movement.
<<echo=(-(1:1)),eval=FALSE>>=
x11(width=6, height=7)
# Calculate principal component loadings (weights)
pcad$rotation
# Plot loading barplots in multiple panels
par(mfrow=c(3,2))
par(mar=c(3.5, 2, 2, 1), oma=c(0, 0, 0, 0))
for (ordern in 1:NCOL(pcad$rotation)) {
barplot(pcad$rotation[, ordern], las=3, xlab="", ylab="", main="")
title(paste0("PC", ordern), line=-2.0, col.main="red")
} # end for
@
\column{0.5\textwidth}
\includegraphics[width=0.45\paperwidth]{figure/pca_rates_loadings.png}
\end{columns}
\end{block}
\end{frame}
%%%%%%%%%%%%%%%
\subsection{Yield Curve Principal Component Time Series}
\begin{frame}[fragile,t]{\subsecname}
\vspace{-1em}
\begin{block}{}
\begin{columns}[T]
\column{0.5\textwidth}
The time series of the \emph{principal components} can be calculated by multiplying the loadings (weights) times the original data.
\vskip1ex
The \emph{principal component} time series have mutually orthogonal returns.
\vskip1ex
Higher order \emph{principal components} are gradually less volatile.
<<echo=TRUE,eval=FALSE>>=
# Standardize (center and scale) the returns
retp <- lapply(retp, function(x) {(x - mean(x))/sd(x)})
retp <- rutils::do_call(cbind, retp)
sapply(retp, mean)
sapply(retp, sd)
# Calculate principal component time series
retpcac <- retp %*% pcad$rotation
all.equal(pcad$x, retpcac, check.attributes=FALSE)
# Calculate products of principal component time series
round(t(retpcac) %*% retpcac, 2)
# Coerce to xts time series
retpcac <- xts(retpcac, order.by=zoo::index(retp))
retpcac <- cumsum(retpcac)
# Plot principal component time series in multiple panels
par(mfrow=c(3,2))
par(mar=c(2, 2, 0, 1), oma=c(0, 0, 0, 0))
rangev <- range(retpcac)
for (ordern in 1:NCOL(retpcac)) {
plot.zoo(retpcac[, ordern], ylim=rangev, xlab="", ylab="")
title(paste0("PC", ordern), line=-1, col.main="red")
} # end for
@
\column{0.5\textwidth}
\includegraphics[width=0.45\paperwidth]{figure/pca_rates_series.png}
\end{columns}
\end{block}
\end{frame}
%%%%%%%%%%%%%%%
\subsection{Inverting Principal Component Analysis}
\begin{frame}[fragile,t]{\subsecname}
\vspace{-1em}
\begin{block}{}
\begin{columns}[T]
\column{0.5\textwidth}
The original time series can be calculated \emph{exactly} from the time series of all the \emph{principal components}, by inverting the loadings matrix.
\vskip1ex
The function \texttt{solve()} solves systems of linear equations, and also inverts square matrices.
\column{0.5\textwidth}
\vspace{-1em}
<<echo=TRUE,eval=FALSE>>=
# Invert all the principal component time series
retpca <- retp %*% pcad$rotation
solved <- retpca %*% solve(pcad$rotation)
all.equal(coredata(retp), solved)
@
\end{columns}
\end{block}
\end{frame}
%%%%%%%%%%%%%%%
\subsection{\protect\emph{Dimension Reduction} Using Principal Component Analysis}
\begin{frame}[fragile,t]{\subsecname}
\vspace{-1em}
\begin{block}{}
\begin{columns}[T]
\column{0.5\textwidth}
The original time series can be calculated \emph{approximately} from just the first few \emph{principal components}, which demonstrates that \emph{PCA} is a form of \emph{dimension reduction}.
\vskip1ex
A popular rule of thumb is to use the \emph{principal components} with the largest variances, which sum up to \texttt{80\%} of the total variance of returns.
\vskip1ex
The \emph{Kaiser-Guttman} rule uses only \emph{principal components} with variance greater than $1$.
<<echo=TRUE,eval=FALSE>>=
# Invert first 3 principal component time series
solved <- retpca[, 1:3] %*% solve(pcad$rotation)[1:3, ]
solved <- xts::xts(solved, zoo::index(retp))
solved <- cumsum(solved)
retc <- cumsum(retp)
# Plot the solved returns
par(mfrow=c(3,2))
par(mar=c(2, 2, 0, 1), oma=c(0, 0, 0, 0))
for (symbol in symbolv) {
plot.zoo(cbind(retc[, symbol], solved[, symbol]),
plot.type="single", col=c("black", "blue"), xlab="", ylab="")
legend(x="topleft", bty="n", y.intersp=0.1,
legend=paste0(symboln, c("", " solved")),
title=NULL, inset=0.0, cex=1.0, lwd=6,
lty=1, col=c("black", "blue"))
} # end for
@
\column{0.5\textwidth}
\includegraphics[width=0.45\paperwidth]{figure/pca_rates_series_solved.png}
\end{columns}
\end{block}
\end{frame}
%%%%%%%%%%%%%%%
\subsection{Calibrating Yield Curve Using Package \protect\emph{RQuantLib}}
\begin{frame}[fragile,t]{\subsecname}
\vspace{-1em}
\begin{block}{}
\begin{columns}[T]
\column{0.5\textwidth}
The package
\href{https://cran.r-project.org/web/packages/RQuantLib/index.html}{\emph{RQuantLib}}
is an interface to the
\href{http://quantlib.org/index.shtml}{\emph{QuantLib}}
open source \texttt{C/C++} library for quantitative finance, mostly designed for pricing fixed-income instruments and options.
\vskip1ex
The function \texttt{DiscountCurve()} calibrates a \emph{zero coupon yield curve} from \emph{money market} rates, \emph{Eurodollar} futures, and \emph{swap} rates.
\vskip1ex
The function \texttt{DiscountCurve()} interpolates the \emph{zero coupon} rates into a vector of dates specified by the \texttt{times} argument.
\column{0.5\textwidth}
\vspace{-1em}
<<echo=(-(1:1)),eval=FALSE>>=
library(quantmod) # Load quantmod
library(RQuantLib) # Load RQuantLib
# Specify curve parameters
curvep <- list(tradeDate=as.Date("2018-01-17"),
settleDate=as.Date("2018-01-19"),
dt=0.25,
interpWhat="discount",
interpHow="loglinear")
# Specify market data: prices of FI instruments
pricev <- list(d3m=0.0363,
fut1=96.2875,
fut2=96.7875,
fut3=96.9875,
fut4=96.6875,
s5y=0.0443,
s10y=0.05165,
s15y=0.055175)
# Specify dates for calculating the zero rates
datev <- seq(0, 10, 0.25)
# Specify the evaluation (as of) date
setEvaluationDate(as.Date("2018-01-17"))
# Calculate the zero rates
ratev <- DiscountCurve(params=curvep, tsQuotes=pricev, times=datev)
# Plot the zero rates
x11()
plot(x=ratev$zerorates, t="l", main="zerorates")
@
\end{columns}
\end{block}
\end{frame}
%%%%%%%%%%%%%%%
\section{Financial and Commodity Futures}
%%%%%%%%%%%%%%%
\subsection{Financial and Commodity Futures Contracts}
\begin{frame}[fragile,t]{\subsecname}
\vspace{-1em}
\begin{block}{}
\begin{columns}[T]
\column{0.5\textwidth}
The underlying assets delivered in \emph{commodity futures} contracts are commodities, such as grains (corn, wheat), or raw materials and metals (oil, aluminum).
\vskip1ex
The underlying assets delivered in \emph{financial futures} contracts are financial assets, such as stocks, bonds, and currencies.
\vskip1ex
Many futures contracts use cash settlement instead of physical delivery of the asset.
\vskip1ex
Futures contracts on different underlying assets can have quarterly, monthly, or even weekly expiration dates.
\vskip1ex
The front month futures contract is the contract with the closest expiration date to the current date.
\vskip1ex
Symbols of futures contracts are obtained by combining the contract code with the month code and the year.
\vskip1ex
For example, \emph{ESM9} is the symbol for the \emph{S\&P500} index E-mini futures expiring in June 2019.
\column{0.5\textwidth}
\vspace{-1em}
\begin{table}[htb]
\begin{minipage}{0.48\textwidth}
% \centering
<<echo=FALSE,eval=TRUE,results='asis'>>=
# Futures contracts codes
futures <- rbind(c("S&P500 index", "ES"),
c("10yr Treasury", "ZN"),
c("VIX index", "VX"),
c("Gold", "GC"),
c("Oil", "CL"),
c("Euro FX", "EC"),
c("Swiss franc", "SF"),
c("Japanese Yen", "JY"))
colnames(futures) <- c("Futures contract", "Code")
print(xtable::xtable(futures), comment=FALSE, size="scriptsize", include.rownames=FALSE, latex.environments="flushleft")
@
% \captionof{table}{The first table}
\end{minipage}
\begin{minipage}{0.48\textwidth}
% \centering
<<echo=FALSE,eval=TRUE,results='asis'>>=
# Monthly futures contract codes
codes <- cbind(c("January", "February", "September", "April", "May", "June", "July", "August", "September", "October", "November", "December"),
c("F", "G", "H", "J", "K", "M", "N", "Q", "U", "V", "X", "Z"))
colnames(codes) <- c("Month", "Code")
print(xtable::xtable(codes), comment=FALSE, size="scriptsize", include.rownames=FALSE, latex.environments="flushright")
@
% \captionof{table}{The second table}
\end{minipage}
\end{table}
\vspace{-1em}
Interactive Brokers provides more information about futures contracts:\\
\hskip1em\href{https://www.interactivebrokers.com/en/index.php?f=463}{IB Contract and Symbol Database}\\
\hskip1em\href{https://www.interactivebrokers.com/en/index.php?f=1563&p=fut}{IB Traded Products}
\vskip1ex
List of
\href{https://www.purefinancialacademy.com/futures-markets}{Popular Futures Contracts}.
\end{columns}
\end{block}
\end{frame}
%%%%%%%%%%%%%%%
\subsection{\protect\emph{E-mini} Futures Contracts}
\begin{frame}[fragile,t]{\subsecname}
\vspace{-1em}
\begin{block}{}
\begin{columns}[T]
\column{0.5\textwidth}
\emph{E-mini} futures are contracts with smaller notionals and tick values, which are more suitable for retail investors.
\vskip1ex
For example, the
\href{https://www.cmegroup.com/trading/energy/crude-oil/emini-crude-oil.html}{\emph{QM} E-mini oil future}
notional is \texttt{500} barrels, while the standard
\href{https://www.cmegroup.com/trading/energy/crude-oil/light-sweet-crude_quotes_globex.html}{\emph{CL} oil future} notional is \texttt{1,000} barrels.
\vskip1ex
The tick value is the change in the dollar value of the futures contract due to a one tick change in the underlying price.
\vskip1ex
For example, the tick value of the \emph{ES} E-mini \emph{S\&P500} future is \texttt{\$12.50}, and one tick is \texttt{0.25}.
\vskip1ex
So if the \emph{S\&P500} index changes by one tick (\texttt{0.25}), then the value of a single \emph{ES} E-mini contract changes by \texttt{\$12.50}, while the standard \emph{SP} contract value changes by \texttt{\$62.5}.
\vskip1ex
The
\href{https://www.cmegroup.com/trading/equity-index/us-index/e-mini-sandp500.html}{\emph{ES} E-mini \emph{S\&P500} futures} trade almost continuously 24 hours per day, from 6:00 PM Eastern Time (ET) on Sunday night to 5:00 PM Friday night (with a trading halt between 4:15 and 4:30 PM ET each day).
\column{0.5\textwidth}
\vspace{-1em}
\begin{table}[htb]
<<echo=FALSE,eval=TRUE,results='asis'>>=
# Futures contracts codes
futures <- rbind(c("S&P500 index", "SP", "ES"),
c("10yr Treasury", "ZN", "ZN"),
c("VIX index", "VX", "delisted"),
c("Gold", "GC", "YG"),
c("Oil", "CL", "QM"),
c("Euro FX", "EC", "E7"),
c("Swiss franc", "SF", "MSF"),
c("Japanese Yen", "JY", "J7"))
colnames(futures) <- c("Futures contract", "Standard", "E-mini")
print(xtable::xtable(futures), comment=FALSE, size="scriptsize", include.rownames=FALSE, latex.environments="flushleft")
@
\end{table}
\end{columns}
\end{block}
\end{frame}
%%%%%%%%%%%%%%%
\subsection{Plotting \protect\emph{S\&P500} Futures Data}
\begin{frame}[fragile,t]{\subsecname}
\vspace{-1em}
\begin{block}{}
\begin{columns}[T]
\column{0.5\textwidth}
The function \texttt{data.table::fread()} reads \texttt{.csv} files over five times faster than the function \texttt{read.csv()}!
\vskip1ex
The function \texttt{as.POSIXct.numeric()} coerces a \texttt{numeric} value representing the \emph{moment of time} into a \texttt{POSIXct} \emph{date-time}, equal to the \emph{clock time} in the local \emph{time zone}.
<<echo=TRUE,eval=FALSE>>=
# Load data for S&P Emini futures June 2019 contract
dirn <- "/Users/jerzy/Develop/data/ib_data"
filen <- file.path(dirn, "ESohlc.csv")
# Read a data table from CSV file
pricev <- data.table::fread(filen)
class(pricev)
# Coerce first column from string to date-time
unlist(sapply(pricev, class))
tail(pricev)
prices$Index <- as.POSIXct(prices$Index,
tz="America/New_York", origin="1970-01-01")
# Coerce prices into xts series
pricev <- data.table::as.xts.data.table(pricev)
class(pricev)
tail(pricev)
colnames(pricev)[1:5] <- c("Open", "High", "Low", "Close", "Volume")
tail(pricev)
@
\column{0.5\textwidth}
\vspace{-1em}
\includegraphics[width=0.45\paperwidth]{figure/sp500_futures.png}
<<echo=TRUE,eval=FALSE>>=
# Plot OHLC data in x11 window
x11(width=5, height=4) # Open x11 for plotting
par(mar=c(5, 5, 2, 1), oma=c(0, 0, 0, 0))
chart_Series(x=pricev, TA="add_Vo()",
name="S&P500 futures")
# Plot dygraph
dygraphs::dygraph(pricev[, 1:4], main="OHLC prices") %>%
dyCandlestick()
@
\end{columns}
\end{block}
\end{frame}
%%%%%%%%%%%%%%%
\subsection{Consecutive Contract Futures Volumes}
\begin{frame}[fragile,t]{\subsecname}
\vspace{-1em}
\begin{block}{}
\begin{columns}[T]
\column{0.5\textwidth}
The trading volumes of a futures contract drop significantly shortly before its expiration, and the successive contract volumes increase.
\vskip1ex
The contract with the highest trading volume is usually considered the most liquid contract.
<<echo=TRUE,eval=FALSE>>=
# Load ESU8 data
dirn <- "/Users/jerzy/Develop/data/ib_data"
filen <- file.path(dirn, "ESU8.csv")
ESU8 <- data.table::fread(filen)
# Coerce ESU8 into xts series
ESU8$V1 <- as.Date(as.POSIXct.numeric(ESU8$V1,
tz="America/New_York", origin="1970-01-01"))
ESU8 <- data.table::as.xts.data.table(ESU8)
colnames(ESU8)[1:5] <- c("Open", "High", "Low", "Close", "Volume")
# Load ESM8 data
filen <- file.path(dirn, "ESM8.csv")
ESM8 <- data.table::fread(filen)
# Coerce ESM8 into xts series
ESM8$V1 <- as.Date(as.POSIXct.numeric(ESM8$V1,
tz="America/New_York", origin="1970-01-01"))
ESM8 <- data.table::as.xts.data.table(ESM8)
colnames(ESM8)[1:5] <- c("Open", "High", "Low", "Close", "Volume")
@
\column{0.5\textwidth}
\vspace{-1em}
\includegraphics[width=0.45\paperwidth]{figure/sp500_futures_volumes.png}
<<echo=(-(1:1)),eval=FALSE>>=
x11(width=6, height=5) # Open x11 for plotting
# Plot last month of ESU8 and ESM8 volume data
endd <- end(ESM8)
startd <- (endd - 30)
volumm <- cbind(Vo(ESU8), Vo(ESM8))[paste0(startd, "/", endd)]
colnames(volumm) <- c("ESU8", "ESM8")
colorv <- c("blue", "green")
plot(volumm, col=colorv, lwd=3, major.ticks="days",
format.labels="%b-%d", observation.based=TRUE,
main="Volumes of ESU8 and ESM8 futures")
legend("topleft", legend=colnames(volumm), col=colorv, y.intersp=0.1,
title=NULL, bty="n", lty=1, lwd=6, inset=0.1, cex=0.7)
@
\end{columns}
\end{block}
\end{frame}
%%%%%%%%%%%%%%%
\subsection{Chaining Together Futures Prices}
\begin{frame}[fragile,t]{\subsecname}
\vspace{-1em}
\begin{block}{}
\begin{columns}[T]
\column{0.5\textwidth}
Chaining futures means splicing together prices from several consecutive futures contracts.
\vskip1ex
A continuous futures contract is a time series of prices obtained by chaining together prices from consecutive futures contracts.
\vskip1ex
The price of the continuous contract is equal to the most liquid contract times a scaling factor.
\vskip1ex
When the next contract becomes more liquid, then the continuous contract price is rolled over to that contract.
\vskip1ex
Futures contracts with different maturities (expiration datev) trade at different prices because of the futures curve, which causes price jumps between consecutive futures contracts.
\vskip1ex
The old contract price is multiplied by a scaling factor after that contract is rolled, to remove price jumps.
\vskip1ex
So the continuous contract prices are not equal to the past futures prices.
\vskip1ex
Interactive Brokers provides information about Continuous Contract Futures market data:\\
\hskip1em\href{https://www.interactivebrokers.com/en/software/tws/usersguidebook/technicalanalytics/continuous.htm}{Continuous Contract Futures Data}
\column{0.5\textwidth}
\vspace{-1em}
\includegraphics[width=0.45\paperwidth]{figure/sp500_futures_chained.png}
<<echo=TRUE,eval=FALSE>>=
# Find date when ESU8 volume exceeds ESM8
exceeds <- (volumm[, "ESU8"] > volumm[, "ESM8"])
indeks <- match(TRUE, exceeds)
# indeks <- min(which(exceeds))
# Scale the ESM8 prices
indeks <- zoo::index(exceeds[indeks])
ratio <- as.numeric(Cl(ESU8[indeks])/Cl(ESM8[indeks]))
ESM8[, 1:4] <- ratio*ESM8[, 1:4]
# Calculate continuous contract prices
chaind <- rbind(ESM8[zoo::index(ESM8) < indeks],
ESU8[zoo::index(ESU8) >= indeks])
# Or
# chaind <- rbind(ESM8[paste0("/", indeks-1)],
# ESU8[paste0(indeks, "/")])
# Plot continuous contract prices
chart_Series(x=chaind["2018"], TA="add_Vo()",
name="S&P500 chained futures")