forked from souzatharsis/open-quant-live-book
-
Notifications
You must be signed in to change notification settings - Fork 0
/
open-quant-live-book.tex
3170 lines (2565 loc) · 131 KB
/
open-quant-live-book.tex
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
\PassOptionsToPackage{unicode=true}{hyperref} % options for packages loaded elsewhere
\PassOptionsToPackage{hyphens}{url}
\PassOptionsToPackage{dvipsnames,svgnames*,x11names*}{xcolor}
%
\documentclass[]{book}
\usepackage{lmodern}
\usepackage{amssymb,amsmath}
\usepackage{ifxetex,ifluatex}
\usepackage{fixltx2e} % provides \textsubscript
\ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{textcomp} % provides euro and other symbols
\else % if luatex or xelatex
\usepackage{unicode-math}
\defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase}
\fi
% use upquote if available, for straight quotes in verbatim environments
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
% use microtype if available
\IfFileExists{microtype.sty}{%
\usepackage[]{microtype}
\UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
}{}
\IfFileExists{parskip.sty}{%
\usepackage{parskip}
}{% else
\setlength{\parindent}{0pt}
\setlength{\parskip}{6pt plus 2pt minus 1pt}
}
\usepackage{xcolor}
\usepackage{hyperref}
\hypersetup{
pdftitle={The Open Quant Live Book},
pdfauthor={OpenQuants.com},
colorlinks=true,
linkcolor=Maroon,
filecolor=Maroon,
citecolor=Blue,
urlcolor=Blue,
breaklinks=true}
\urlstyle{same} % don't use monospace font for urls
\usepackage{geometry}
\geometry{paperwidth=6in, paperheight=9in}
\usepackage{color}
\usepackage{fancyvrb}
\newcommand{\VerbBar}{|}
\newcommand{\VERB}{\Verb[commandchars=\\\{\}]}
\DefineVerbatimEnvironment{Highlighting}{Verbatim}{commandchars=\\\{\}}
% Add ',fontsize=\small' for more characters per line
\usepackage{framed}
\definecolor{shadecolor}{RGB}{248,248,248}
\newenvironment{Shaded}{\begin{snugshade}}{\end{snugshade}}
\newcommand{\KeywordTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{\textbf{#1}}}
\newcommand{\DataTypeTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{#1}}
\newcommand{\DecValTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}}
\newcommand{\BaseNTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}}
\newcommand{\FloatTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}}
\newcommand{\ConstantTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}}
\newcommand{\CharTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}
\newcommand{\SpecialCharTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}}
\newcommand{\StringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}
\newcommand{\VerbatimStringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}
\newcommand{\SpecialStringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}
\newcommand{\ImportTok}[1]{#1}
\newcommand{\CommentTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textit{#1}}}
\newcommand{\DocumentationTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\AnnotationTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\CommentVarTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\OtherTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{#1}}
\newcommand{\FunctionTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}}
\newcommand{\VariableTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{#1}}
\newcommand{\ControlFlowTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{\textbf{#1}}}
\newcommand{\OperatorTok}[1]{\textcolor[rgb]{0.81,0.36,0.00}{\textbf{#1}}}
\newcommand{\BuiltInTok}[1]{#1}
\newcommand{\ExtensionTok}[1]{#1}
\newcommand{\PreprocessorTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textit{#1}}}
\newcommand{\AttributeTok}[1]{\textcolor[rgb]{0.77,0.63,0.00}{#1}}
\newcommand{\RegionMarkerTok}[1]{#1}
\newcommand{\InformationTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\WarningTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textbf{\textit{#1}}}}
\newcommand{\AlertTok}[1]{\textcolor[rgb]{0.94,0.16,0.16}{#1}}
\newcommand{\ErrorTok}[1]{\textcolor[rgb]{0.64,0.00,0.00}{\textbf{#1}}}
\newcommand{\NormalTok}[1]{#1}
\usepackage{longtable,booktabs}
% Fix footnotes in tables (requires footnote package)
\IfFileExists{footnote.sty}{\usepackage{footnote}\makesavenoteenv{longtable}}{}
\usepackage{graphicx,grffile}
\makeatletter
\def\maxwidth{\ifdim\Gin@nat@width>\linewidth\linewidth\else\Gin@nat@width\fi}
\def\maxheight{\ifdim\Gin@nat@height>\textheight\textheight\else\Gin@nat@height\fi}
\makeatother
% Scale images if necessary, so that they will not overflow the page
% margins by default, and it is still possible to overwrite the defaults
% using explicit options in \includegraphics[width, height, ...]{}
\setkeys{Gin}{width=\maxwidth,height=\maxheight,keepaspectratio}
% Make links footnotes instead of hotlinks:
\DeclareRobustCommand{\href}[2]{#2\footnote{\url{#1}}}
\setlength{\emergencystretch}{3em} % prevent overfull lines
\providecommand{\tightlist}{%
\setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
\setcounter{secnumdepth}{5}
% Redefines (sub)paragraphs to behave more like sections
\ifx\paragraph\undefined\else
\let\oldparagraph\paragraph
\renewcommand{\paragraph}[1]{\oldparagraph{#1}\mbox{}}
\fi
\ifx\subparagraph\undefined\else
\let\oldsubparagraph\subparagraph
\renewcommand{\subparagraph}[1]{\oldsubparagraph{#1}\mbox{}}
\fi
% set default figure placement to htbp
\makeatletter
\def\fps@figure{htbp}
\makeatother
\usepackage{booktabs}
\usepackage{amsthm}
\usepackage{pdfpages}
\usepackage{graphicx}
\usepackage{mathtools}
\usepackage{xcolor}
\usepackage[]{natbib}
\bibliographystyle{apalike}
\title{The Open Quant Live Book}
\author{OpenQuants.com}
\date{2019-12-15}
\usepackage{amsthm}
\newtheorem{theorem}{Theorem}[chapter]
\newtheorem{lemma}{Lemma}[chapter]
\newtheorem{corollary}{Corollary}[chapter]
\newtheorem{proposition}{Proposition}[chapter]
\newtheorem{conjecture}{Conjecture}[chapter]
\theoremstyle{definition}
\newtheorem{definition}{Definition}[chapter]
\theoremstyle{definition}
\newtheorem{example}{Example}[chapter]
\theoremstyle{definition}
\newtheorem{exercise}{Exercise}[chapter]
\theoremstyle{remark}
\newtheorem*{remark}{Remark}
\newtheorem*{solution}{Solution}
\let\BeginKnitrBlock\begin \let\EndKnitrBlock\end
\begin{document}
\includepdf{./fig/cover1.pdf}
\maketitle
{
\hypersetup{linkcolor=}
\setcounter{tocdepth}{2}
\tableofcontents
}
\newcommand{\independent}{\perp\!\!\!\!\perp}
\DeclarePairedDelimiter\ceil{\lceil}{\rceil}
\DeclarePairedDelimiter\floor{\lfloor}{\rfloor}
\chapter*{Preface}\label{preface}
\subsection*{Description}\label{description}
The book aims to be an Open Source introductory reference of the most
important aspects of financial data analysis, algo trading, portfolio
selection, econophysics and machine learning in finance with an emphasis
in reproducibility and openness not to be found in most other typical
Wall Street-like references.
\subsection*{Contribute}\label{contribute}
The Book is Open and we welcome co-authors. Feel free to
\href{https://www.openquants.com/contact}{reach out} or simply create a
pull request with your contribution! See project structure, guidelines
and how to contribute
\href{https://github.com/souzatharsis/open-quant-live-book/blob/master/CONTRIBUTING.md}{here}.
\subsection*{Working Contents}\label{working-contents}
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\tightlist
\item
The Basics
\end{enumerate}
\begin{itemize}
\tightlist
\item
I/O
\item
Stylized Facts
\end{itemize}
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\setcounter{enumi}{1}
\tightlist
\item
Algo Trading
\end{enumerate}
\begin{itemize}
\tightlist
\item
Investment Process
\item
Backtesting
\item
Factor Investing
\item
Limit Order
\end{itemize}
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\setcounter{enumi}{2}
\tightlist
\item
Portfolio Optimization
\end{enumerate}
\begin{itemize}
\tightlist
\item
Convex Optimization
\item
Risk Parity Portfolios
\end{itemize}
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\setcounter{enumi}{3}
\tightlist
\item
Machine Learning
\end{enumerate}
\begin{itemize}
\tightlist
\item
Intro
\item
Agent-Based Models
\item
Binary Classifiers
\item
AutoML
\item
Hierarchical Risk Parity
\end{itemize}
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\setcounter{enumi}{4}
\tightlist
\item
Econophysics
\end{enumerate}
\begin{itemize}
\tightlist
\item
Entropy, Efficiency and Bubbles
\item
Nonparametric Statistical Causality: An Information-Theoretical
Approach
\item
Financial Networks
\end{itemize}
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\setcounter{enumi}{5}
\tightlist
\item
Alternative Data
\end{enumerate}
\begin{itemize}
\tightlist
\item
The Market, The Players, The Rules
\item
Case Studies
\end{itemize}
\subsection*{Book's information}\label{books-information}
First published at: \href{https://openquants.com/}{openquants.com}.
Licensed under
\href{https://creativecommons.org/licenses/by-nc-sa/4.0/}{Attribution-NonCommercial-ShareAlike
4.0 International}.
\begin{center}\includegraphics[width=0.15\linewidth]{fig/by-nc-sa} \end{center}
\BeginKnitrBlock{flushright}
Copyright (c) 2019. OpenQuants.com, New York, NY.
\EndKnitrBlock{flushright} \BeginKnitrBlock{flushright}
\href{http://patreon.com/openquants}{\includegraphics{https://github.com/souzatharsis/open-quant-live-book/blob/master/fig/patreon.png}}
\EndKnitrBlock{flushright}
\part{The Basics}\label{part-the-basics}
\chapter{I/O}\label{io}
In this Chapter, we will introduce basic functions to read text, excel
and JSON files as well as large files.
We will also show how to obtain free financial and economic data
including the following:
\begin{itemize}
\tightlist
\item
End-of-day and real-time pricing;
\item
Company financials;
\item
Macroeconomic data.
\end{itemize}
Data sources utilized in this Chapter include the following:
\begin{itemize}
\tightlist
\item
U.S. Securities and Exchange Commission;
\item
Quandl;
\item
IEX;
\item
Alpha Vantage.
\end{itemize}
\section{Importing Data}\label{importing-data}
\subsection{Text Files}\label{text-files}
The most basic and commonly used option to import data from text files
in R is the use of the function \texttt{read.table} from the
\textbf{r-base}. We can use this function to read text files with
extensions such as \texttt{.txt} and \texttt{.csv}.
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{dat.table <-}\StringTok{ }\KeywordTok{read.table}\NormalTok{(}\DataTypeTok{file =} \StringTok{"<name of your file>.txt"}\NormalTok{)}
\NormalTok{dat.csv <-}\StringTok{ }\KeywordTok{read.csv}\NormalTok{(}\DataTypeTok{file =} \StringTok{"<name of your file>.csv"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
The package \textbf{readr} provides functions for reading text data into
R that are much faster that the functions from the \textbf{r-base}. The
\texttt{read\_table} function from the package \textbf{readr} provides a
near-replacement for the \texttt{read.table} function.
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{library}\NormalTok{(readr)}
\NormalTok{dat.table <-}\StringTok{ }\NormalTok{readr}\OperatorTok{::}\KeywordTok{read_table2}\NormalTok{(}\DataTypeTok{file =} \StringTok{"<name of your file>.txt"}\NormalTok{)}
\NormalTok{dat.csv <-}\StringTok{ }\NormalTok{readr}\OperatorTok{::}\KeywordTok{read_csv}\NormalTok{(}\DataTypeTok{file =} \StringTok{"<name of your file>.csv"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
Another option to save data is to write it in \texttt{rds} format. Data
stored in \texttt{rds} format has the advantage to keep the original
data struture and type of the object saved. Also, \texttt{.rds} files
are compressed and consume less space than files saved in \texttt{.csv}
format. A data.frame object can be saved in \texttt{rds} format and then
loaded back as follows:
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{write_rds}\NormalTok{(dat.frame, }\DataTypeTok{path =} \StringTok{"<name of your file>.rds"}\NormalTok{)}
\NormalTok{dat.frame <-}\StringTok{ }\KeywordTok{read_rds}\NormalTok{(}\DataTypeTok{path =} \StringTok{"<name of your file>.rds"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\subsection{Excel Files}\label{excel-files}
The package \texttt{readxl} has an ease to use interface to functions
that load excel documents in R. The functions \texttt{read\_xls} and
\texttt{read\_xlsx} can be used to read excel files as follows:
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{library}\NormalTok{(readxl)}
\NormalTok{readxl}\OperatorTok{::}\KeywordTok{read_xls}\NormalTok{(}\DataTypeTok{path =} \StringTok{"<name of your file>.xls"}\NormalTok{)}
\NormalTok{readxl}\OperatorTok{::}\KeywordTok{read_xlsx}\NormalTok{(}\DataTypeTok{path =} \StringTok{"<name of your file>.xlsx"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
The function \texttt{read\_excel()} automatically detects the extension
of the input file as follows:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{readxl}\OperatorTok{::}\KeywordTok{read_excel}\NormalTok{(}\StringTok{"<name and extension of your file>"}\NormalTok{, }\DataTypeTok{sheet =} \StringTok{"<sheet name or index>"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
In the \texttt{read\_excel} function, the \texttt{sheet} argument can
receive either the target sheet name or index number, where sheet
indexing starts at 1.
The \texttt{readxl} has been oberving increased use compared to other
comparable packages such as \textbf{gdata} and the \textbf{xlsx} due to
its relative ease of use and performance. Also, the \texttt{readxl} do
not have depency with external code libraries while the packages
\textbf{gdata} and \textbf{xlsx} depend on \texttt{ActiveState\ PERL}
and the \texttt{Java\ JDK}, respectively.
\subsection{JSON Files}\label{json-files}
JSON files are particularly used for transmitting data in web
applications but also frequently used as a standard data interchange
format.
The \texttt{jsonline} package can be used to parse files in JSON format
as follows:
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{library}\NormalTok{(jsonlite)}
\NormalTok{result_json <-}\StringTok{ }\KeywordTok{read_json}\NormalTok{(}\StringTok{"<json file>"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\subsection{Large Files}\label{large-files}
Fast data manipulation in a short and flexible syntax.
\section{Data Sources}\label{data-sources}
In this section, we will show how to obtain financial and economic data
from public sources.
\subsection{Alpha Vantage}\label{alpha-vantage}
Alpha Vantage offers free access to pricing data including:
\begin{itemize}
\tightlist
\item
Stock Time Series Data;
\item
Physical and Digital/Crypto Currencies (e.g., Bitcoin);
\item
Technical Indicators and
\item
Sector Performances.
\end{itemize}
The data are available in JSON and CSV formats via REST APIs. The
\textbf{quantmod} and the \textbf{alphavantager} R packages offer a
lightweight R interface to the Alpha Vantage API. Daily stock prices can
be obtained with the \texttt{quantmod::getSymbols} function as follows:
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{getSymbols}\NormalTok{(}\DataTypeTok{Symbols =} \StringTok{"AAPL"}\NormalTok{, }\DataTypeTok{src =} \StringTok{"av"}\NormalTok{, }\DataTypeTok{output.size =} \StringTok{"full"}\NormalTok{, }
\DataTypeTok{adjusted =} \OtherTok{TRUE}\NormalTok{, }\DataTypeTok{api.key =} \StringTok{"your API key"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
The output data is stored in an object with the same name as the
corresponding symbol, in this example \texttt{AAPL}. The output data
looks like the following
\begin{tabular}{rrrrrr}
\toprule
AAPL.Open & AAPL.High & AAPL.Low & AAPL.Close & AAPL.Volume & AAPL.Adjusted\\
\midrule
102.4 & 102.5 & 98.9 & 99.0 & 4731800 & 3.08\\
98.4 & 99.8 & 94.8 & 94.9 & 3891700 & 2.95\\
93.2 & 97.2 & 91.1 & 97.0 & 5562300 & 3.01\\
98.0 & 98.4 & 94.0 & 98.3 & 4141300 & 3.05\\
100.9 & 102.0 & 98.5 & 100.0 & 4419700 & 3.11\\
\addlinespace
99.6 & 99.6 & 96.6 & 98.0 & 2535600 & 3.04\\
\bottomrule
\end{tabular}
\begin{center}\includegraphics{open-quant-live-book_files/figure-latex/unnamed-chunk-16-1} \end{center}
We called the \texttt{quantmod::getSymbols} function with the following
arguments:
\begin{itemize}
\tightlist
\item
\texttt{Symbols=\textquotesingle{}AAPL\textquotesingle{}} defines a
character vector specifying the names of each symbol to be loaded,
here specified by the symbol of the company Apple Inc.;
\item
\texttt{src="av"} specifies the sourcing method, here defined with the
value corresponding to Alpha Vantage;
\item
\texttt{output.size="full"}specified length of the time series
returned. The strings \texttt{compact} and \texttt{full} are accepted
with the following specifications: \texttt{compact} returns only the
latest 100 data points; \texttt{full} returns the full-length time
series of up to 20 years of historical data;
\item
\texttt{adjusted=TRUE} defines a boolean variable to include a column
of closing prices adjusted for dividends and splits;
\item
\texttt{api.key} specifies your Alpha Vantage API key.
\end{itemize}
\subsection{IEX}\label{iex}
The IEX Group operates the Investors Exchange (IEX), a stock exchange
for U.S. equities that is built for investors and companies. IEX offers
U.S. reference and market data including end-of-day and intraday pricing
data. IEX offers an API with ``a set of services designed for developers
and engineers. It can be used to build high-quality apps and services''.
Data sourced from the IEX API is freely available for commercial subject
to \href{https://iextrading.com/api-exhibit-a/}{conditions} and the use
of their API is subject to additional
\href{https://iextrading.com/api-terms/}{terms of use}.
IEX lists the following github project as an unofficial API for R:
\url{https://github.com/imanuelcostigan/iex}. We will provide examples
on how to obtain intraday pricing data using this package. First, we
will use the \textbf{devtools} to install the package directly from its
github repository as follows:
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{library}\NormalTok{(devtools)}
\KeywordTok{install_github}\NormalTok{(}\StringTok{"imanuelcostigan/iex"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
The \textbf{iex} package provides 4 set of functions as follows:
\begin{itemize}
\tightlist
\item
\texttt{last}: Provides IEX near real time last sale price, size and
time. Last is ideal for developers that need a lightweight stock
quote. \href{https://iextrading.com/developer/docs/\#last}{IEX API
real time API documentation}.
\item
\texttt{market}: Provides exchange trade volume data in near real
time. \href{https://iextrading.com/developer/\#market-market}{IEX
market API documentation}.
\item
\texttt{stats}: A set of functions that return trading statistics.
\href{https://iextrading.com/developer/\#stats}{IEX stats API
documentation}.
\item
\texttt{tops}: Provides IEX's aggregated bid and offer position in
near real time for all securities on IEX's displayed limit order book.
\href{https://iextrading.com/developer/\#tops-tops}{IEX API TOPS
documentation}.
\end{itemize}
For instance, the \texttt{last} function has the following arguments:
\begin{itemize}
\tightlist
\item
\texttt{symbols}: A vector of tickers (case insensitive). Special
characters will be escaped. A list of eligible symbols is
\href{https://iextrading.com/trading/eligible-symbols/}{published
daily} by the IEX. When set to \texttt{NULL} (default) returns values
for all symbols.
\item
\texttt{fields}: A vector of fields names to return (case sensitive).
When set to \texttt{NULL} (default) returns values for all fields.
\item
\texttt{version}: The API version number, which is used to define the
API URL.
\end{itemize}
We can obtain intraday stock price data with the \texttt{last} function
as follows:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{dat <-}\StringTok{ }\NormalTok{iex}\OperatorTok{::}\KeywordTok{last}\NormalTok{(}\DataTypeTok{symbols =} \KeywordTok{c}\NormalTok{(}\StringTok{"AAPL"}\NormalTok{), }\DataTypeTok{fields =} \KeywordTok{c}\NormalTok{(}\StringTok{"symbol"}\NormalTok{, }
\StringTok{"price"}\NormalTok{, }\StringTok{"size"}\NormalTok{))}
\end{Highlighting}
\end{Shaded}
The function returns an S3 object of class \texttt{iex\_api} which has
three accessible fields: \texttt{path} , \texttt{response} and
\texttt{content}.
\begin{itemize}
\tightlist
\item
The \texttt{path} contains the corresponding IEX API path:
\end{itemize}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{dat}\OperatorTok{$}\NormalTok{path}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [1] "tops/last"
\end{verbatim}
\begin{itemize}
\tightlist
\item
The \texttt{response} contains the unparsed IEX API response:
\end{itemize}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{dat}\OperatorTok{$}\NormalTok{response}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## Response [https://api.iextrading.com/1.0/tops/last?symbols=AAPL&filter=symbol%2Cprice%2Csize]
## Date: 2019-12-16 03:01
## Status: 200
## Content-Type: application/json; charset=utf-8
## Size: 44 B
\end{verbatim}
\begin{itemize}
\tightlist
\item
The \texttt{content} contains the parsed content from the API's
response:
\end{itemize}
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{dat}\OperatorTok{$}\NormalTok{content}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## [[1]]
## [[1]]$symbol
## [1] "AAPL"
##
## [[1]]$price
## [1] 275
##
## [[1]]$size
## [1] 52
\end{verbatim}
According to the developer, this package causes R to pause 0.2 seconds
after executing an API call to avoid the user being throttled by the IEX
API (which enforces a 5 request per second limit). Documentation about
the other set of functions can be obtained at
\url{https://github.com/imanuelcostigan/iex/tree/master/man}.
\subsection{Quandl}\label{quandl}
\href{https://www.quandl.com}{\textbf{Quandl}} is likely the largest
financial and alternative data aggregator/provider today. They leverage
relationships with third-party providers to be a one-stop-shop for
alternative data and traditional fundamental, pricing and estimates
datasets.
Quandl offer an API which usage is free for registered users. You can
obtain an API key
\href{https://www.quandl.com/sign-up-modal?defaultModal=showSignUp}{here}.
After signing up, just append your API key to your call like this:
\begin{verbatim}
https://www.quandl.com/api/v3/datasets/WIKI/FB/data.csv?api_key=YOURAPIKEYHERE
\end{verbatim}
At Quandl, every dataset is identified by ``Quandl code'', which is a
unique id. In the above example, you downloaded a dataset with the
Quandl code ``WIKI/FB''.
Every Quandl code has 2 parts: the database code (``WIKI'') which
specifies where the data comes from, and the dataset code (``FB'') which
identifies the specific time series you want.
You can find Quandl codes using their
\href{https://www.quandl.com/search}{data browser}. Additional API
documentation can be found \href{https://docs.quandl.com/}{here}.
Quandl is also available via an R interface \citep{R-Quandl}. For
instance, we can obtain Crude Oil Futures prices from 01/01/2010 to
01/01/2019 as follows:
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{library}\NormalTok{(Quandl)}
\KeywordTok{Quandl.api_key}\NormalTok{(config}\OperatorTok{::}\KeywordTok{get}\NormalTok{()}\OperatorTok{$}\NormalTok{quandl.key)}
\NormalTok{from.dat <-}\StringTok{ }\KeywordTok{as.Date}\NormalTok{(}\StringTok{"01/01/2010"}\NormalTok{, }\DataTypeTok{format =} \StringTok{"%d/%m/%Y"}\NormalTok{)}
\NormalTok{to.dat <-}\StringTok{ }\KeywordTok{as.Date}\NormalTok{(}\StringTok{"01/01/2019"}\NormalTok{, }\DataTypeTok{format =} \StringTok{"%d/%m/%Y"}\NormalTok{)}
\NormalTok{crude.oil.futures <-}\StringTok{ }\KeywordTok{Quandl}\NormalTok{(}\StringTok{"CHRIS/CME_CL1"}\NormalTok{, }\DataTypeTok{start_date =}\NormalTok{ from.dat, }
\DataTypeTok{end_date =}\NormalTok{ to.dat, }\DataTypeTok{type =} \StringTok{"xts"}\NormalTok{)}
\KeywordTok{plot}\NormalTok{(crude.oil.futures}\OperatorTok{$}\NormalTok{Last)}
\end{Highlighting}
\end{Shaded}
\begin{center}\includegraphics{open-quant-live-book_files/figure-latex/unnamed-chunk-22-1} \end{center}
In the example above we specified the following Database/Dataset:
\begin{itemize}
\tightlist
\item
Database: ``CHRIS''. Continuous contracts for all 600 futures on
Quandl. Built on top of raw data from CME, ICE, LIFFE etc. Curated by
the Quandl community. 50 years history.
\item
Dataset: ``CME\_CL1''. Historical futures prices of Crude Oil Futures,
Continuous Contract \#1. Non-adjusted price based on spot-month
continuous contract calculations. Raw data from CME.
\end{itemize}
\subsection{SEC}\label{sec}
Official filings are freely available from the U.S. Securities and
Exchange Commission's EDGAR database. The package \texttt{finreportr}
provides an interface in R to facilitate financial analysis from SEC's
10K and 10K/A filings.
We can obtain company basic information with the function the
\texttt{CompanyInfo} function by passing the ticker symbol of the target
company as follows:
\begin{Shaded}
\begin{Highlighting}[]
\KeywordTok{library}\NormalTok{(}\StringTok{"finreportr"}\NormalTok{)}
\NormalTok{AAPL.Info <-}\StringTok{ }\KeywordTok{CompanyInfo}\NormalTok{(}\StringTok{"AAPL"}\NormalTok{)}
\KeywordTok{print}\NormalTok{(AAPL.Info)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
## company CIK SIC state state.inc FY.end
## 1 Apple Inc. 0000320193 3571 CA CA 0928
## street.address city.state
## 1 ONE APPLE PARK WAY CUPERTINO CA 95014
\end{verbatim}
As a result, we obtain the following information:
\begin{itemize}
\tightlist
\item
Company name: Apple Inc.;
\item
SEC Central Index Key (CIK): 0000320193;
\item
Standard Industrial Classification (SIC): 3571, which is the industry
code for Electronic Computers;
\item
Address: ONE APPLE PARK WAY, CUPERTINO CA 95014;
\item
Most recent period of report end is 0928.
\end{itemize}
The list of company annual reports with corresponding filing dates can
be obtained with the function \emph{AnnualReports} as follows:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{AAPL.reports <-}\StringTok{ }\KeywordTok{AnnualReports}\NormalTok{(}\StringTok{"AAPL"}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\begin{table}[t]
\caption{\label{tab:unnamed-chunk-25}Sample Annual Reports}
\centering
\begin{tabular}{lll}
\toprule
filing.name & filing.date & accession.no\\
\midrule
10-K & 2019-10-31 & 0000320193-19-000119\\
10-K & 2018-11-05 & 0000320193-18-000145\\
10-K & 2017-11-03 & 0000320193-17-000070\\
10-K & 2016-10-26 & 0001628280-16-020309\\
10-K & 2015-10-28 & 0001193125-15-356351\\
\addlinespace
10-K & 2014-10-27 & 0001193125-14-383437\\
\bottomrule
\end{tabular}
\end{table}
The accession number is a unique identifier that the SEC creates for
each filing.
Company financials are organized into 3 segments: Income Statement,
Balance Sheet and Cash Flow.
\textbf{Income Statement}
Financials from the Income Statement segment can be obtained with the
\emph{GetIncome} function as follows:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{AAPL.IS <-}\StringTok{ }\KeywordTok{GetIncome}\NormalTok{(}\StringTok{"AAPL"}\NormalTok{, }\DecValTok{2017}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\begin{table}[t]
\caption{\label{tab:unnamed-chunk-28}Sample Income Statement Financials}
\centering
\begin{tabular}{lllll}
\toprule
Metric & Units & Amount & startDate & endDate\\
\midrule
Revenue, Net & usd & 233715000000 & 2014-09-28 & 2015-09-26\\
Revenue, Net & usd & 75872000000 & 2015-09-27 & 2015-12-26\\
Revenue, Net & usd & 50557000000 & 2015-12-27 & 2016-03-26\\
Revenue, Net & usd & 42358000000 & 2016-03-27 & 2016-06-25\\
Revenue, Net & usd & 46852000000 & 2016-06-26 & 2016-09-24\\
\addlinespace
Revenue, Net & usd & 215639000000 & 2015-09-27 & 2016-09-24\\
\bottomrule
\end{tabular}
\end{table}
The Income Statement function returns data for the following metrics:
\begin{table}[t]
\caption{\label{tab:unnamed-chunk-29}Income Statement Metrics}
\centering
\begin{tabular}{l}
\toprule
Metrics\\
\midrule
Revenue, Net\\
Cost of Goods and Services Sold\\
Gross Profit\\
Research and Development Expense\\
Selling, General and Administrative Expense\\
\addlinespace
Operating Expenses\\
Operating Income (Loss)\\
Nonoperating Income (Expense)\\
Income (Loss) from Continuing Operations before Income Taxes, Noncontrolling Interest\\
Income Tax Expense (Benefit)\\
\addlinespace
Net Income (Loss) Attributable to Parent\\
Earnings Per Share, Basic\\
Earnings Per Share, Diluted\\
Weighted Average Number of Shares Outstanding, Basic\\
Weighted Average Number of Shares Outstanding, Diluted\\
\addlinespace
Common Stock, Dividends, Per Share, Declared\\
\bottomrule
\end{tabular}
\end{table}
\textbf{Balance Sheet}
Financials from the Balance Sheet segment can be obtained with the
\emph{GetBalanceSheet} function as follows:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{AAPL.BS <-}\StringTok{ }\KeywordTok{GetBalanceSheet}\NormalTok{(}\StringTok{"AAPL"}\NormalTok{, }\DecValTok{2017}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\begin{table}[t]
\caption{\label{tab:unnamed-chunk-32}Sample Balance Sheet Financials}
\centering
\begin{tabular}{lllll}
\toprule
Metric & Units & Amount & startDate & endDate\\
\midrule
Cash and Cash Equivalents, at Carrying Value & usd & 13844000000 & NA & 2014-09-27\\
Cash and Cash Equivalents, at Carrying Value & usd & 21120000000 & NA & 2015-09-26\\
Cash and Cash Equivalents, at Carrying Value & usd & 20484000000 & NA & 2016-09-24\\
Cash and Cash Equivalents, at Carrying Value & usd & 20289000000 & NA & 2017-09-30\\
Available-for-sale Securities, Current & usd & 46671000000 & NA & 2016-09-24\\
\addlinespace
Available-for-sale Securities, Current & usd & 53892000000 & NA & 2017-09-30\\
\bottomrule
\end{tabular}
\end{table}
The Balance Sheet function returns data for the following metrics:
\begin{table}[t]
\caption{\label{tab:unnamed-chunk-33}Balance Sheet Metrics}
\centering
\begin{tabular}{l}
\toprule
Metrics\\
\midrule
Cash and Cash Equivalents, at Carrying Value\\
Available-for-sale Securities, Current\\
Accounts Receivable, Net, Current\\
Inventory, Net\\
Nontrade Receivables, Current\\
\addlinespace
Other Assets, Current\\
Assets, Current\\
Available-for-sale Securities, Noncurrent\\
Property, Plant and Equipment, Net\\
Goodwill\\
\addlinespace
Intangible Assets, Net (Excluding Goodwill)\\
Other Assets, Noncurrent\\
Assets\\
Accounts Payable, Current\\
Accrued Liabilities, Current\\
\addlinespace
Deferred Revenue, Current\\
Commercial Paper\\
Long-term Debt, Current Maturities\\
Liabilities, Current\\
Deferred Revenue, Noncurrent\\
\addlinespace
Long-term Debt, Excluding Current Maturities\\
Other Liabilities, Noncurrent\\
Liabilities\\
Commitments and Contingencies\\
Common Stocks, Including Additional Paid in Capital\\
\addlinespace
Retained Earnings (Accumulated Deficit)\\
Accumulated Other Comprehensive Income (Loss), Net of Tax\\
Stockholders' Equity Attributable to Parent\\
Liabilities and Equity\\
\bottomrule
\end{tabular}
\end{table}
\textbf{Cash Flow}
Financials from the Cash Flow segment can be obtained with the
\emph{GetCashFlow} function as follows:
\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{AAPL.CF <-}\StringTok{ }\KeywordTok{GetCashFlow}\NormalTok{(}\StringTok{"AAPL"}\NormalTok{, }\DecValTok{2017}\NormalTok{)}
\end{Highlighting}
\end{Shaded}
\begin{table}[t]
\caption{\label{tab:unnamed-chunk-36}Sample Cash Flow Financials}
\centering
\begin{tabular}{lllll}
\toprule
Metric & Units & Amount & startDate & endDate\\
\midrule
Cash and Cash Equivalents, at Carrying Value & usd & 13844000000 & NA & 2014-09-27\\
Cash and Cash Equivalents, at Carrying Value & usd & 21120000000 & NA & 2015-09-26\\
Cash and Cash Equivalents, at Carrying Value & usd & 20484000000 & NA & 2016-09-24\\
Cash and Cash Equivalents, at Carrying Value & usd & 20289000000 & NA & 2017-09-30\\
Net Income (Loss) Attributable to Parent & usd & 53394000000 & 2014-09-28 & 2015-09-26\\
\addlinespace
Net Income (Loss) Attributable to Parent & usd & 18361000000 & 2015-09-27 & 2015-12-26\\
\bottomrule
\end{tabular}
\end{table}
The Cash Flow function returns data for the following metrics:
\begin{table}[t]
\caption{\label{tab:unnamed-chunk-37}Cash Flow Metrics}
\centering
\begin{tabular}{l}
\toprule
Metrics\\
\midrule
Cash and Cash Equivalents, at Carrying Value\\
Net Income (Loss) Attributable to Parent\\
Depreciation, Amortization and Accretion, Net\\
Share-based Compensation\\
Deferred Income Tax Expense (Benefit)\\
\addlinespace
Other Noncash Income (Expense)\\