-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathFeature-RandomWalkModel-Data.jl
More file actions
2537 lines (1962 loc) · 95.9 KB
/
Copy pathFeature-RandomWalkModel-Data.jl
File metadata and controls
2537 lines (1962 loc) · 95.9 KB
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
### A Pluto.jl notebook ###
# v0.17.4
using Markdown
using InteractiveUtils
# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).
macro bind(def, element)
quote
local iv = try Base.loaded_modules[Base.PkgId(Base.UUID("6e696c72-6542-2067-7265-42206c756150"), "AbstractPlutoDingetjes")].Bonds.initial_value catch; b -> missing; end
local el = $(esc(element))
global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)
el
end
end
# ╔═╡ 2bb52ee4-1c6f-46b6-b105-86827ada0f75
md"""
# Random Walks and The Efficient Market Hypothesis
"""
# ╔═╡ 2f499c95-38cf-4856-b199-6c9aac44237a
md"""
### Introduction
[A Random Walk Down Wall Street](https://en.wikipedia.org/wiki/A_Random_Walk_Down_Wall_Street) written by [Princeton University Professor Burton Malkiel](https://dof.princeton.edu/about/clerk-faculty/emeritus/burton-gordon-malkiel) popularized the [efficient market hypothesis (EMH)](https://en.wikipedia.org/wiki/Efficient-market_hypothesis), which posits that stock prices fully reflect all available information and expectations. The efficient market hypothesis was developed by [University of Chicago Professor Eugene Fama](https://en.wikipedia.org/wiki/Eugene_Fama):
* [Fama, E. F. (1970). Efficient Capital Markets: A Review of Theory and Empirical Work. The Journal of Finance, 25(2), 383–417. https://doi.org/10.2307/2325486](https://www.jstor.org/stable/2325486)
who was later awarded the [Noble Prize in Economics](https://www.nobelprize.org/prizes/economic-sciences/2013/press-release/) along with [Robert J. Shiller](http://www.econ.yale.edu/~shiller/) from Yale and [Lars Peter Hansen](https://en.wikipedia.org/wiki/Lars_Peter_Hansen) also from the University of Chicago, for their empirical analysis of asset prices.
Our interest in the efficient market hypothesis follows from its relationship with [random walks](https://en.wikipedia.org/wiki/Random_walk), and in particular, the potential of predicting the price of a stock 𝒯 days into the future (at least in a probabilistic sense) using a random walk approach, an idea first applied to stock prices by [Louis Bachelier](https://en.wikipedia.org/wiki/Louis_Bachelier) in 1900. Fluctuations in prices are explained by the changes in the instantaneous demand and supply of any given stock, causing a random walk in prices. Let's explore random walk models in more detail.
"""
# ╔═╡ 89b5c4d0-68cb-499f-bf99-216e38b40ca0
# ╔═╡ 489464b4-3139-466c-80c7-84449dcec698
# ╔═╡ b4f60458-0299-4246-b2ad-dc3f1db6382b
# ╔═╡ 34bf07e8-5c47-4aa8-aa2c-161709c158be
md"""
### Materials and Methods
##### Disclaimer
This notebook (and all codes discussed within) is offered solely for training and informational purposes. No offer or solicitation to buy or sell securities or securities derivative products of any kind, or any type of investment or trading advice or strategy, is made, given, or in any manner endorsed by Pooksoft.
Trading involves risk. Carefully review your financial situation before investing in securities, futures contracts, options, or commodity interests. Past performance, whether actual or indicated by historical tests of strategies, is no guarantee of future performance or success. Trading is generally not appropriate for someone with limited resources, investment or trading experience, or a low-risk tolerance. Only risk capital that will not be needed for living expenses.
You are fully responsible for any investment or trading decisions you make, and such decisions should be based solely on your evaluation of your financial circumstances, investment or trading objectives, risk tolerance, and liquidity needs.
"""
# ╔═╡ 65a0683e-3124-4844-ad0a-cccdc9192d05
# ╔═╡ e603c785-b697-48e3-92be-e9213e72215b
# ╔═╡ badff812-6b68-4f6d-b495-3f344873d45c
# ╔═╡ 6a4164c2-bb11-437a-bc7d-a12e363d3e84
# ╔═╡ c81486cb-f78e-4eec-a1cd-1ea113428bd6
# ╔═╡ 880b1174-0925-4e8c-b9f6-f6e295412824
md"""
##### Random Walk Models (RWMs)
[Random walk models](https://en.wikipedia.org/wiki/Random_walk) are tools for computing the time evolution of the prices of risky assets, for example, the price of a stock with the ticker symbol `XYZ`. Let the price of `XYZ` at time $j$ be given by $P_{j}$ (units: USD/share). Then during the next time period (index $j+1$) the `XYZ` share price will be given by:
$$P_{j+1} = P_{j}\exp\left(\mu_{j\rightarrow{j+1}}\Delta{t}\right)$$
where $\Delta{t}$ denotes the length of time between periods $j$ and $j+1$ (units: time) and $\mu_{j\rightarrow{j+1}}$ denotes the growth rate (in the financial world called the [return](https://www.investopedia.com/terms/a/absolutereturn.asp)) between time period(s) $j$ and $j+1$ (units: time$^{-1}$). The growth rate $\mu_{j\rightarrow{j+1}}$ is different for different tickers, and is not constant between time period $j\rightarrow{j+1}$. Dividing both sides by $P_{j}$ and taking the [natural log](https://en.wikipedia.org/wiki/Natural_logarithm) gives the expression:
$$p_{j+1} = p_{j} + \mu_{j\rightarrow{j+1}}\Delta{t}$$
where $p_{\star}$ denotes the log of the price at time $\star$ (units: dimensionless). This expression is a basic [random walk model](https://en.wikipedia.org/wiki/Random_walk). The challenge to using this model is how to estimate the return
$\mu_{j\rightarrow{j+1}}$ because the values for $\mu_{j\rightarrow{j+1}}$ are [random variables](https://en.wikipedia.org/wiki/Stochastic_process) which are [distributed](https://en.wikipedia.org/wiki/Probability_distribution) in some unknown way. However, if we had a value for $\mu_{j\rightarrow{j+1}}$ (or at least a model to estimate a value for it, denoted as $\hat{\mu}_{j\rightarrow{j+1}}$), we could
simulate the price of `XYZ` during the next time period $j+1$ given knowledge of the price now (time period $j$). For example, given a value for the close price of `XYZ` on Monday, we could estimate a value for the close price of `XYZ` on Tuesday if we had a model for the daily return.
"""
# ╔═╡ 4c2bbb6b-f287-43c4-9e24-f44fb4c87e36
# ╔═╡ 00120ff5-e9ed-4e71-8208-cf8efd2eac6a
# ╔═╡ e3ba3cf8-2f94-4276-98ed-6fedcfaadd43
# ╔═╡ a64f7082-b834-4400-880a-032cb9aafe4c
# ╔═╡ a1b50b95-bf7d-4f2a-817d-9edb3418aeb3
md"""
##### Estimating models for the return from historical data
Suppose values for the return were governed by some [probability distribution](https://en.wikipedia.org/wiki/Probability_distribution) $\mathcal{D}\left(\bar{m},\sigma\right)$ where $\bar{m}$
denotes the [mean value](https://en.wikipedia.org/wiki/Mean) and $\sigma$ denotes the [standard deviation](https://en.wikipedia.org/wiki/Standard_deviation) of the growth rate $\mu_{j\rightarrow{j+1}}$. Of course, we do not know the actual values for
$\left(\bar{m},\sigma\right)$, nor do we know the form of $\mathcal{D}\left(\bar{m},\sigma\right)$, but we can estimate them from historial price data.
An even better way to learn $\mathcal{D}\left(\bar{m},\sigma\right)$ would be to estimate the form of the distribution from the data itself using a technique such as [Kernel Density Estimation](https://en.wikipedia.org/wiki/Kernel_density_estimation) or KDE.
"""
# ╔═╡ 1852d4c5-e73d-4038-a565-b8fb6ff63502
# ╔═╡ 1c9f096f-7dce-4d0c-8a71-6fbe682e514d
# ╔═╡ eb4a5874-c13c-4915-96b9-0c47eaa7f50c
# ╔═╡ 66bfd748-3b40-42df-86fa-e55019dba856
# ╔═╡ cf11b553-13e5-488d-bf1c-16de5911d658
# ╔═╡ 2353a285-71de-43b2-a60f-5a3274ff9e6b
md"""
##### My Julia Setup
In the following code block, we set up project paths and import external packages that we use to download and analyze historical price history for a variety of ticker symbols. In addition, we load a local copy of the [Serenity library](https://github.com/Pooksoft/Serenity).
"""
# ╔═╡ 43d75d79-b710-4dc5-9478-dd2b08616be9
# ╔═╡ ebc5ed32-1fe3-4854-a326-7a068e14164b
# ╔═╡ 1b25e7d1-909f-4fdc-9700-5d131251e1b5
# ╔═╡ 9943d000-83d0-413d-a231-0295fb19df71
md"""
### Results and Discussion
"""
# ╔═╡ f66a480b-3f0c-4ebf-a8b8-e0f91dff851d
md"""
##### Download historical price data from the [Polygon.io](https://www.polygon.io) financial data warehouse
In this study, we model two years of daily adjusted close price data from `2019-12-26` to `2021-12-23` (N = 504) for a variety of ticker symbols (𝒫 = 40). We used methods in the [Serenity library](https://github.com/Pooksoft/Serenity) and the routine `aggregates_api_endpoint` defined in this notebook to download historical pricing data from the [Polygon.io](https://www.polygon.io) financial data warehouse using a free tier application programming interface key.
The `aggregates_api_endpoint` takes a list of ticker symbols that we want to model as an input argument.
This method checks to see if we have price data already saved locally for each ticker.
* If yes, then we load the saved file as a [DataFrame](https://dataframes.juliadata.org/stable/) and store it in the `price_data_dictionary` data structure which is of type [Dict](https://docs.julialang.org/en/v1/base/collections/#Dictionaries) where the keys are the ticker strings e.g., MSFT, etc and the values are the price [DataFrames](https://dataframes.juliadata.org/stable/).
* if no, we download new data from [Polygon.io](https://www.polygon.io), save this data locally as a `CSV` file (<ticker>.csv), and return the price data as a [DataFrame](https://dataframes.juliadata.org/stable/) in the `price_data_dictionary` dictionary.
The parameters for the [Polygon.io](https://www.polygon.io) application programming interface call are encoded in endpoint-specific [Structs](https://docs.julialang.org/en/v1/manual/types/#Composite-Types) defined in the [Serenity library](https://github.com/Pooksoft/Serenity).
"""
# ╔═╡ f94ecbae-e823-46f6-a69f-eb7edce7cfe5
# ╔═╡ dc5f6727-cd17-4c75-80ce-94915a0e359a
# ╔═╡ 9b9d7fdf-91b1-46e4-bd66-43e50add56be
# ╔═╡ 0e7d1741-88a1-4e8e-b964-e8ead4d1807e
# ╔═╡ 300b62c8-830a-472f-a07c-17153468c1fb
md"""
##### What ticker symbols are we going to model?
"""
# ╔═╡ 54efa70c-bac6-4d7c-93df-0dfd1b89769d
# Pooksoft Industrial Average (PSIA) -> the DJIA + some stuff
ticker_symbol_array = sort([
"MSFT", "ALLY", "MET", "AAPL", "GM", "PFE", "TGT", "WFC", "AIG", "F", "GE", "AMD",
"MMM", "AXP", "AMGN", "BA", "CAT", "CVX", "CSCO", "KO", "DIS", "DOW", "GS", "HD", "IBM",
"HON","INTC", "JNJ", "JPM", "MCD", "MRK", "NKE", "PG", "CRM", "TRV", "UNH", "VZ",
"V", "WBA", "WMT", "SPY", "SPYD", "SPYG", "SPYV", "SPYX", "VOO", "VTI", "VEA", "VWO",
"VNQ", "VGK", "MRNA"
]);
# ╔═╡ 866cc84d-86c1-40e2-bd29-deae01da9a2e
𝒫 = length(ticker_symbol_array); # the number of ticker symbols is given the symbol 𝒫
# ╔═╡ 7bcbdc4e-a38a-4201-a1ec-d2e4df4d2f6a
𝒯 = 14; # number of days that we simulate in the future
# ╔═╡ d1edad45-5df3-43cd-8abc-97d84fab699b
# ╔═╡ bb7582b4-3ecc-44a7-810a-aae0dc2fe816
# ╔═╡ 34db9c1e-6af7-4710-8de4-fd0caacbde36
# ╔═╡ 46fef026-6bac-401b-ab6f-75f2aff79e6a
# ╔═╡ 455b2bea-4d79-4dd8-964c-80835bb88727
# ╔═╡ 4d4230e5-28dc-4f87-b732-686a5c91fc4f
md"""
##### Pull down data from Polygon.io for our list of ticker symbols
"""
# ╔═╡ e2eb17d0-2ca3-437c-97f7-04e76ee879cb
# ╔═╡ a3a08666-f494-489d-a888-8fe7baa70729
# ╔═╡ b05cac4c-d5d9-47f7-ab38-d9be8322ab45
# ╔═╡ 61ab2949-d72f-4d80-a717-4b6a9227de0e
md"""
##### Estimate the daily return distributions
To estimate the return moel $\mathcal{D}\left(\bar{m},\sigma\right)$, we compute the historical returns for each ticker using the `compute_log_return_array` method in the [Serenity library](https://github.com/Pooksoft/Serenity.git).
Given the returns, we estimate the parameters of $\mathcal{D}\left(\bar{m},\sigma\right)$ using a variety of approaches e.g., [nonlinear least squares](https://en.wikipedia.org/wiki/Non-linear_least_squares) or [maximum likelihood estimation](https://en.wikipedia.org/wiki/Maximum_likelihood_estimation). However, there are a few technical questions with this approach:
* __Question 1__: What model for $\mathcal{D}\left(\bar{m},\sigma\right)$ do we choose? Conventional wisdom suggests a [Normal distribution](https://en.wikipedia.org/wiki/Normal_distribution). However, is this really correct, or is the data governed by another type of distribution?
* __Question 2__: An underlying assumption of the random walk is that the daily returns are independent and identically distributed, ie., the close price for the days $j$ and $j+1$ are independent of one another, they follow the same underlying distribution, and the parameters $(\bar{m},\sigma)$ don't change in time.
"""
# ╔═╡ e461b560-435b-4104-b42e-af04b1d25984
# ╔═╡ b7b618c2-d48b-45c7-aff8-600eda010169
# ╔═╡ a39b90ec-a4c5-472f-b00e-c81ee9c5576f
md"""
__Fig. 1__: Histogram of the adjusted daily returns computed using the `stephist` routine of the [StatsPlots.jl package](https://github.com/JuliaPlots/StatsPlots.jl) for 𝒫 = 40 ticker symbols in PSIA. The number of bins was set to 20% of the number of historical records for `AAPL` (shown in red) and was constant for each ticker. The returns were calculated using approximately two years of historical daily adjusted close price data (depending upon the ticker symbol).
Close price data was downloaded from the [Polygon.io](https://www.polygon.io) data warehouse.
"""
# ╔═╡ 3f9879fa-ec04-4d13-8207-2c77d9ddfca2
# ╔═╡ 22992de2-dfba-4a18-8909-62bddbf4e0e7
# ╔═╡ 367158be-9a7f-4b76-96c9-2806f9aad75e
# ╔═╡ fb83174c-fcde-4496-8232-545f17ac9d2d
# ╔═╡ edfbf364-e126-4e95-93d2-a6adfb340045
md"""
##### The daily return of individual ticker symbols is not normally distributed
A key assumption often made in mathematical finance is that the return $\mu_{j\rightarrow{j+1}}$ (growth rate) computed using the log of the prices is normally distributed (Question 1 raised above). However, a closer examination of the return data for our collection of ticker symbols suggests this is not true.
The return $\mu_{j\rightarrow{j+1}}$ values computed from historical data are not normally distributed for the vast majority of ticker symbols in our collection (Fig. 2). Visual inspection of the histograms computed using a [Laplace distribution](https://en.wikipedia.org/wiki/Laplace_distribution) (Fig 2, dark blue) for the returns appear to be closer to the historical data (Fig 2, red) compared to a [Normal distribution](https://en.wikipedia.org/wiki/Normal_distribution) (Fig 2, light blue). [QQplots](https://en.wikipedia.org/wiki/Q–Q_plot) and the [Kolmogorov–Smirnov (KS) test](https://en.wikipedia.org/wiki/Kolmogorov–Smirnov_test) further support this finding.
"""
# ╔═╡ a786ca10-06d2-4b76-97a9-2bcf879ea6cb
# fit a distribution to a ticker -
single_asset_ticker_symbol = "GS";
# ╔═╡ f067b633-fde0-4743-bd76-f8c390a90950
# ╔═╡ a3d29aa3-96ca-4681-960c-3b4b04b1e40d
md"""
__Fig 2__: Comparison of the actual (red line) and estimated histogram for the adjusted daily returns for ticker = $(single_asset_ticker_symbol) using a [Laplace distribution](https://en.wikipedia.org/wiki/Laplace_distribution) for the return model (blue line) and a [Normal distribution](https://en.wikipedia.org/wiki/Normal_distribution) for the return model (light blue line). The return model distributions were estimated using the `fit` routine of the [Distributions.jl](https://github.com/JuliaStats/Distributions.jl) package. The `fit` routine uses multiple approaches to estimate the parameters in the distribution including [Maximum Likelihood Estimation (MLE)](https://en.wikipedia.org/wiki/Maximum_likelihood_estimation).
"""
# ╔═╡ 4dff7597-bc0e-4288-9413-c26a132c1e44
# ╔═╡ 1d72b291-24b7-4ec6-8307-1da0bc4a9183
md"""
Beyond simply visualizing the histogram, we explored the question of a [Normal](https://en.wikipedia.org/wiki/Normal_distribution) versus [Laplace](https://en.wikipedia.org/wiki/Laplace_distribution) return distribution, by constructing [QQplots](https://en.wikipedia.org/wiki/Q–Q_plot) to visualize the historical return data versus a Laplace distribution (Fig. 3). Further, we performed the [Kolmogorov–Smirnov (KS) test](https://en.wikipedia.org/wiki/Kolmogorov–Smirnov_test), using the KS test implementation in the [HypothesisTests.jl](https://juliastats.org/HypothesisTests.jl/latest/nonparametric/#Kolmogorov-Smirnov-test-1) package. The KS test determines whether data follows a particular distribution, in our case we test whether the historical return data were either Normally or Laplace distributed (Table 1).
"""
# ╔═╡ 1867ecec-3c3d-4b2b-9036-1488e2184c40
md"""
__Fig 3__: Quantile-Quantile plot (QQplot) for historical $(single_asset_ticker_symbol) return data versus theoretical data generated using a Laplace distribution. If the historical data were governed by a Laplace distribution, the points would lie along the equality line.
"""
# ╔═╡ a3f1710e-eb98-46c6-aadb-5cf0b98e1bc6
# ╔═╡ 9380908a-8cc5-4d3a-9d6c-03b491198bc1
# ╔═╡ a07d661a-a0b4-4000-b7a4-5f17cda5edc3
md"""
###### Example: Kolmogorov–Smirnov (KS) test for a Laplace and Normal distrubution for ticker: $(single_asset_ticker_symbol)
The null hypothesis $h_0$ for the KS test is the data follows a specified distribution, in our case a Laplace distribution. Conversely, the alternative hypothesis $h_{1}$ is the data does not follow a particular distribution, again in this case, a Laplace distribution.
"""
# ╔═╡ fdc34643-2c27-4bc9-a077-8bac68dc56b7
# ╔═╡ 8897de5b-a6c7-4b05-98c6-d738bbb527af
# ╔═╡ 379373b1-e563-4341-9978-5b35c768b5c7
md"""
__Table 1__: [Kolmogorov–Smirnov (KS)](https://en.wikipedia.org/wiki/Kolmogorov–Smirnov_test) test results for Normal and Laplace distribution for PSIA tickers (𝒫 = 40). The historical return values computed over the last two years of historical data for 39 of the 40 members of the PSIA were governed by a Laplace distribution; MRNA failed the KS test for a Laplace distribution, and was estimated to be Normally distributed.
"""
# ╔═╡ 95495255-385a-424b-9b84-dcd8a1187282
# ╔═╡ d8af95e4-fe4c-4cf0-8195-dab80629177c
# ╔═╡ 3f62e075-4724-456e-ab59-9b85d4263ee6
# ╔═╡ bc4e93f5-7e76-4115-8cfd-039212181fb3
md"""
##### Are daily returns iid? The Wald-Wolfowitz runs test
A second key assumption of the random walk approach is that returns are independently and identically distributed. To test whether this is true for the ticker symbols in our data set, we performed the [Wald-Wolfowitz runs test](https://en.wikipedia.org/wiki/Wald–Wolfowitz_runs_test). The [Wald-Wolfowitz runs test](https://en.wikipedia.org/wiki/Wald–Wolfowitz_runs_test) is a non-parametric tool, that does not require returns to be normally distributed, which calculates the likelihood that a sequence is independent (the null hypothesis).
Each return is scored according to whether it is larger, smaller, or the same as the median; a score of +1 is assigned when the return is greater than the median, a score of -1 is assigned when the return is less than the median, and a score of 0 is assigned when the return equals the mean.
"""
# ╔═╡ 587c70c4-a3b8-4300-b7a4-aa9f6b1bc276
# ╔═╡ 421e213e-9780-4a4d-a411-009541c44a9e
# ╔═╡ 2d40603b-56e3-49ca-a8ea-e13c933f5e19
md"""
__Table XX__: Wald-Wolfowitz test results for historical price data from `2019-12-26` to `2021-12-23` for 𝒫 = 40 tickers in the PSIA. The Wald-Wolfowitz test implementation from the [HypothesisTests.jl]() package was used to compute the test results.
"""
# ╔═╡ c39168a1-dee2-4421-8f44-266df47dd08e
# ╔═╡ 4e6e394d-0d95-46cc-8344-0222b0fb761e
# ╔═╡ 0454a796-b35d-4caa-b847-f578191f2896
# ╔═╡ 10fa507e-1429-4eb0-b74c-1e6638725690
md"""
##### Monte Carlo simulations of the daily close price using a random walk model
We used [Monte-Carlo simulation](https://www.investopedia.com/articles/investing/112514/monte-carlo-simulation-basics.asp) to estimate the close price distribution of each ticker, 𝒯 days into the future, using the daily return model $\mathcal{D}\left(\bar{m},\sigma\right)$ we learned from historical price data. Monte-Carlo simulation is conceptually easy to understand but tricky to implement in an efficient way.
Imagine that we split our reality into a large number of structurally similar but parallel dimensions, such that in each of these dimensions there was a stock market in which company `XYZ` traded, and for each dimension, yesterday's close price for `XYZ` was $p_{j}$. Next, further, suppose that we cloned ourselves and placed a clone into each of these dimensions so that we could record the stock price of ticker `XYZ` at the end of the day for the specified number of days. Because dimensions were not identical, we expect the close price to vary between dimensions. After 𝒯 days the clones report their price recordings we put them all together. The data provided by each clone is called a _sample path_, and we can use these sample paths to compute a distribution of possible outcomes for the price of `XYZ`.
In a technical sense, starting from close price at time index $p_j$, we draw a random sample from the $\mathcal{D}\left(\bar{m},\sigma\right)$ distribution, and compute a value for $p_{j+1}$. We then advance the time index $p_{j+1}\rightarrow{p_{j}}$ and repeat the process over again until we reach the end of the prediction time horizon. Of course, because we are dealing with random variables, we repeat the calculation of each sample path many times which gives a distribution of possible price outcomes.
"""
# ╔═╡ 92673e3f-e436-4c7e-accf-216574233d58
# ╔═╡ e2df85a5-975c-472b-8538-d07b682d1647
# ╔═╡ 2e416e6d-ea7c-464c-9632-83b0f7f06b2a
# ╔═╡ 3d1a1f06-5707-46ff-b44a-539c62fe008b
# ╔═╡ 90a0a645-cd70-4edb-8240-a152d6e7bb3a
# ╔═╡ cdd66194-cb79-433e-a16c-64be76de83a4
# ╔═╡ 4f8a3476-93a8-414e-b169-7046f1a57547
# ╔═╡ 21791e69-db82-4081-97ec-e7f2c0a46b5d
# ╔═╡ 1f9459dd-57ba-4353-81b2-9e04aa8257af
# ╔═╡ 90722894-dc53-4964-8141-e35adfeb8a76
# ╔═╡ 4d97d757-ed9f-4e77-9b54-6b9c8f2f49ee
# ╔═╡ 9a3d5138-0490-42db-9f99-310d94124951
# ╔═╡ bdf1e4d0-d2e6-4ab5-92c5-5f25518a9acc
# ╔═╡ 0a55c3a1-a834-4ec4-beac-0788091f7a70
# ╔═╡ 4725bf3c-f058-4238-8c8f-297dc2851c6e
# ╔═╡ 3b9d8429-375d-46c3-a115-eb9022262e09
# ╔═╡ 23ae5b4c-f690-46a6-b2c9-3d753cf247d6
# ╔═╡ edf426b6-a571-4938-890a-01a089d02b29
# ╔═╡ c32725a4-e276-4372-8d06-d40ba52c9f09
md"""
### Conclusions
In this study, we explored random walks and the efficient market hypothesis. In particular, we simulated 𝒯 future price predictions based on a return model learned from historical data. There were a few takeaway points:
* Daily returns were not Normally distributed for a variety of ticker symbols (the DJIA plus 10 additional symbols) with the exception of MRNA, which appears to be normally distributed. Ticker returns more likely followed a Laplace distribution.
* The Wald-Wolfowitz runs test suggested that the daily returns for several members of the DJIA were not random, thus, violating the iid assumption of our random walk modeling approach. However, this violation did not appear to hinder the Monte-Carlo estimate of the close price distribution.
* A random walk model predicted future stock price distributions for short time horizons (𝒯 = 7 days), but was less successful for longer time horizons e.g., 𝒯 = 35 days.
"""
# ╔═╡ f4bd98b5-f4a8-424a-b974-41aceede92fb
# ╔═╡ 6086ed53-4fbe-4037-b435-8d8aa20a1417
# ╔═╡ defa9be8-4d19-488b-820c-2a3526401cbf
# ╔═╡ f1a71f47-fb19-4988-a439-2ff8d38be5b7
function ingredients(path::String)
# this is from the Julia source code (evalfile in base/loading.jl)
# but with the modification that it returns the module instead of the last object
name = Symbol("Serenity")
m = Module(name)
Core.eval(m,
Expr(:toplevel,
:(eval(x) = $(Expr(:core, :eval))($name, x)),
:(include(x) = $(Expr(:top, :include))($name, x)),
:(include(mapexpr::Function, x) = $(Expr(:top, :include))(mapexpr, $name, x)),
:(include($path))))
m
end
# ╔═╡ fe2848df-823a-4ed0-918c-2c200957ee80
begin
# setup: we need to specify the paths where we can find our project resources
_PATH_TO_ROOT = pwd()
_PATH_TO_SRC = joinpath(_PATH_TO_ROOT, "src")
_PATH_TO_DATA = joinpath(_PATH_TO_ROOT, "data")
_PATH_TO_CONFIG = joinpath(_PATH_TO_ROOT, "configuration")
# what packages are we going to use?
using TOML
using PlutoUI
using HypothesisTests
using PrettyTables
using Colors
using StatsPlots
using StatsBase
using Reexport
# these packages are reexported by Serenity
using DataFrames
using CSV
using HTTP
using Dates
using Statistics
using Distributions
using Optim
using Convex
using SCS
using MathOptInterface
using JSON
using Colors
# alias the Polygon.io URL -
DATASTORE_URL_STRING = "https://api.polygon.io"
# What we have here is a classic good news, bad news situation ...
# Bad news: We don't check in our Polygon.io API key to GitHub (sorry).
# Good news: Polygon.io API keys are free.
# check out: https://polygon.io -
configuration_dictionary = TOML.parsefile(joinpath(_PATH_TO_CONFIG, "Configuration.toml"))
# get some stuff from the configuration dictionary -
POLYGON_API_KEY = configuration_dictionary["API"]["polygon_api_key"]
# load the local version of the serenity library -
Serenity = ingredients(joinpath(_PATH_TO_SRC, "Include.jl"));
# show -
nothing
end
# ╔═╡ e36979d5-c1b6-4c17-a65a-d8de8e6bd8d0
md"""
Show actual price trajectory? $(@bind show_real_traj CheckBox())
"""
# ╔═╡ b04cba56-dd48-403b-82fc-1cf3713853a7
begin
# List of colors -
WHITE = RGB(1.0, 1.0, 1.0)
BACKGROUND = RGB(0.99, 0.98, 0.96)
BLUE = RGB(68 / 255, 119 / 255, 170 / 255)
LBLUE = RGB(102 / 255, 204 / 255, 238 / 255)
GRAY = RGB(187 / 255, 187 / 255, 187 / 255)
RED = RGB(238 / 255, 102 / 255, 119 / 255)
# show -
nothing
end
# ╔═╡ 91dae79f-e454-4b27-84a7-4cbc6bc33265
function aggregates_api_endpoint(ticker_symbol::String; sleeptime::Float64 = 20.0)::NamedTuple
# save the file locally to avoid the API limit -
savepath = joinpath(_PATH_TO_DATA,"polygon", "random_walk_model", "aggregates")
local_path_to_data_file = joinpath(savepath, "$(ticker_symbol).csv")
local_path_to_header_file = joinpath(savepath, "header", "$(ticker_symbol)-header.csv")
# do we have a saved file already?
if (ispath(local_path_to_data_file) == true && ispath(local_path_to_header_file) == true)
# we already have this ticker downloaded. load the existing file from disk -
data_table = CSV.read(local_path_to_data_file, DataFrame)
header = CSV.read(local_path_to_header_file, Dict)
# put the price DataFrame into the price_data_dictionary -
return (header=header, data=data_table)
else
# make the dir to save the data (if we don't have it already) -
mkpath(savepath)
mkpath(joinpath(savepath,"header"))
# Build an API model for the aggregates endpoint -
# see: https://polygon.io/docs/stocks/getting-started
aggregates_api_model = Serenity.PolygonAggregatesEndpointModel()
aggregates_api_model.adjusted = true
aggregates_api_model.sortdirection = "asc"
aggregates_api_model.apikey = POLYGON_API_KEY
aggregates_api_model.limit = 5000
aggregates_api_model.to = Date(2021, 12, 24)
aggregates_api_model.from = Date(2019,12, 24)
aggregates_api_model.multiplier = 1
aggregates_api_model.timespan = "day"
aggregates_api_model.ticker = ticker_symbol
# execute the API call for these parameters -
(header,df) = Serenity.polygon(DATASTORE_URL_STRING, aggregates_api_model);
# save locally -
CSV.write(local_path_to_data_file, df)
CSV.write(local_path_to_header_file, header)
# sleep sometime before we return - helps avoid API limit issue -
sleep(sleeptime)
# put the price DataFrame into the price_data_dictionary -
return (header=header, data=df)
end
end
# ╔═╡ 5c5d5eeb-6775-452f-880d-7b4fa2acda57
begin
# initialize -
price_data_dictionary = Dict{String,DataFrame}()
# process each member of the ticker symbol array -
for ticker_symbol ∈ ticker_symbol_array
# make a call to Polygon.io (or load local cached data)
# the aggregates_api_endpoint method is defined at the bottom of this notebook
(h,d) = aggregates_api_endpoint(ticker_symbol)
# grab the price data -
price_data_dictionary[ticker_symbol] = d
end
# show -
nothing
end
# ╔═╡ 34b06415-21c1-4904-97f0-ab614447355c
begin
# initialize -
return_data_dictionary = Dict{String,DataFrame}()
# compute -
for ticker_symbol ∈ ticker_symbol_array
# Serenity -> computes the log return given a DataFrame, returns a DataFrame
return_data_dictionary[ticker_symbol] =
Serenity.compute_log_return_array(price_data_dictionary[ticker_symbol],
:timestamp => :close; Δt = (1.0 / 1.0))
end
end
# ╔═╡ cbbd8670-49ab-4601-b8d7-9f3f456752e8
begin
# compute some ranges -
ticker_symbol = "AAPL"
μ_avg = mean(return_data_dictionary[ticker_symbol][!, :μ])
# number of bins - 10% of the length of a test ticker
number_of_bins = convert(Int64, (floor(0.20 * length(return_data_dictionary[ticker_symbol][!, :μ]))))
# number of tickers -
number_of_ticker_symbols = length(ticker_symbol_array)
for ticker_index = number_of_ticker_symbols:-1:1
local_ticker_symbol = ticker_symbol_array[ticker_index]
if (ticker_index == number_of_ticker_symbols)
# make the first plot -
stephist(return_data_dictionary[local_ticker_symbol][!, :μ], bins = number_of_bins, normed = :true,
background_color = BACKGROUND, background_color_outside = WHITE,
foreground_color_minor_grid = RGB(1.0, 1.0, 1.0),
lw = 1, c = GRAY, foreground_color_legend = nothing, label = "")
elseif (ticker_index != 1 && ticker_index != number_of_ticker_symbols)
stephist!(return_data_dictionary[local_ticker_symbol][!, :μ], bins = number_of_bins, normed = :true, lw = 1,
c = GRAY, label = "")
else
stephist!(return_data_dictionary[local_ticker_symbol][!, :μ], bins = number_of_bins, normed = :true, lw = 2,
c = RED, label = "$(local_ticker_symbol)")
end
end
# label the plots -
xlabel!("Daily return μ (1/day)", fontsize = 18)
ylabel!("Frequency (N=$(number_of_bins); dimensionless)", fontsize = 14)
xlims!((-100.0 * μ_avg, 100.0 * μ_avg))
end
# ╔═╡ 012ef00f-6176-4d42-801f-5765c47df7ba
begin
# get the historical return data -
μ_vector = return_data_dictionary[single_asset_ticker_symbol][!, :μ]
# fit a Laplace -
LAPLACE = fit(Laplace, μ_vector)
# fit a normal -
NORMAL = fit(Normal, μ_vector)
# show -
nothing
end
# ╔═╡ f0ee3633-1d28-4344-9b85-f5433679582a
let
# perform the KS test -
test_result = HypothesisTests.ExactOneSampleKSTest(unique(μ_vector), LAPLACE)
end
# ╔═╡ 345d8feb-cfd0-4acb-a626-dc16181ddb68
let
# perform the KS test for Laplace -
test_result = HypothesisTests.ExactOneSampleKSTest(unique(μ_vector), NORMAL)
end
# ╔═╡ 6bf06c12-cf25-43c4-81f3-b1d79d13fc94
let
# generate 20_000 samples
S = rand(LAPLACE, 20000)
SN = rand(NORMAL, 20000)
# plot against actual -
stephist(return_data_dictionary[single_asset_ticker_symbol][!, :μ],
bins = convert(Int64,round(1.2*number_of_bins)),
normed = :true,
lw = 2, c = RED,
label = "$(single_asset_ticker_symbol)", background_color = BACKGROUND,
background_color_outside = WHITE, foreground_color_legend = nothing)
stephist!(S, bins = number_of_bins, normed = :true, lw = 2, c = BLUE,
label = "$(single_asset_ticker_symbol) Laplace Model")
stephist!(SN, bins = number_of_bins, normed = :true, lw = 2, c = LBLUE,
label = "$(single_asset_ticker_symbol) Normal Model")
xlabel!("Daily return μ (1/day)", fontsize = 18)
ylabel!("Frequency (N=$(number_of_bins); dimensionless)", fontsize = 14)
xlims!((-75.0 * μ_avg, 75.0 * μ_avg))
end
# ╔═╡ 0e09d312-2ddf-4d1f-8ad5-a50fb48ca4dd
let
# get the historical return data -
μ_vector = return_data_dictionary[single_asset_ticker_symbol][!, :μ]
qqplot(Laplace, μ_vector, label="QQPlot $(single_asset_ticker_symbol)", legend=:topleft,
foreground_color_legend = nothing, c=LBLUE, markerstrokecolor=BLUE, lw=2,
background_color = BACKGROUND, background_color_outside = WHITE)
xlabel!("Theoretical Laplace Quantiles", fontsize=18)
ylabel!("Sample Quantiles", fontsize=18)
end
# ╔═╡ 8b2725a2-8007-46b8-a160-75042562794d
with_terminal() do
number_of_ticker_symbols = length(ticker_symbol_array)
state_table = Array{Any,2}(undef, number_of_ticker_symbols, 5)
for ticker_index ∈ 1:number_of_ticker_symbols
my_ticker_symbol = ticker_symbol_array[ticker_index]
μ_vector = return_data_dictionary[my_ticker_symbol][!, :μ]
LAPLACE = fit(Laplace, μ_vector)
NORMAL = fit(Normal, μ_vector)
test_result_laplace = HypothesisTests.ExactOneSampleKSTest(unique(μ_vector), LAPLACE)
test_result_normal = HypothesisTests.ExactOneSampleKSTest(unique(μ_vector), NORMAL)
state_table[ticker_index,1] = my_ticker_symbol
state_table[ticker_index,2] = pvalue(test_result_normal)
state_table[ticker_index,3] = pvalue(test_result_normal)≥0.05 ? true : false
state_table[ticker_index,4] = pvalue(test_result_laplace)
state_table[ticker_index,5] = pvalue(test_result_laplace)≥0.05 ? true : false
end
table_header = (
["ticker", "Normal", "pₙ ≥ 0.05", "Laplace", "pₗ ≥ 0.05"],
["", "p-value", "95% CI", "p-value", "95% CI"]
)
pretty_table(state_table, header=table_header)
end
# ╔═╡ 20bba789-504b-4d27-a2fc-4f08badc9a53
begin
μ_local = return_data_dictionary[single_asset_ticker_symbol][!,:μ]
WaldWolfowitzTest(μ_local)
end
# ╔═╡ 1c816d04-3b76-4c0c-9ed9-9b20b5ad50d9
with_terminal() do
# initialize -
run_array = Array{Union{Int,String, Float64},2}(undef,𝒫,10)
for (ticker_index, ticker) ∈ enumerate(ticker_symbol_array)
# get the return for this ticker -
μ_local = return_data_dictionary[ticker][!,:μ]
N = length(μ_local)
# what is the mean return for this ticker?
median_value = median(μ_local)
tmp_array = Array{Int64,2}(undef,N,3)
fill!(tmp_array,0)
for time_index ∈ 1:N
# classify -
if (μ_local[time_index] >= median_value)
tmp_array[time_index,1] += 1
tmp_array[time_index,2] += 0
tmp_array[time_index,3] += 1
elseif (μ_local[time_index] < median_value)
tmp_array[time_index,1] += 0
tmp_array[time_index,2] += 1
tmp_array[time_index,3] = -1
end
end
run_array[ticker_index,1] = ticker
run_array[ticker_index,2] = N
# count the number of runs -
U = 1
for time_index ∈ 2:N
old_value = tmp_array[time_index - 1,3]
new_value = tmp_array[time_index,3]
if (old_value!=new_value)
U += 1
end
end
run_array[ticker_index,3] = sum(tmp_array[:,1])
run_array[ticker_index,4] = sum(tmp_array[:,2])
run_array[ticker_index,5] = U
# run the test -
local_test_result = WaldWolfowitzTest(μ_local)
run_array[ticker_index,6] = local_test_result.μ
run_array[ticker_index,7] = local_test_result.σ
run_array[ticker_index,8] = local_test_result.z
run_array[ticker_index,9] = pvalue(local_test_result)
run_array[ticker_index,10] = (pvalue(local_test_result) >= 0.05) ? 1 : 0
end
header_data = (["ticker", "N", "N₊", "N₋", "U","μ","σ","Z","p-value", "p-value ≥ 0.05"])
pretty_table(run_array, header=header_data)
end
# ╔═╡ 5a3500c2-4f82-43e9-a31b-d530f56fdbe9
begin
# how many steps, sample paths etc -
number_of_sample_paths = 12500;
number_of_strata = 1;
monte_carlo_simulation_dictionary = Dict{String,Array{Float64,2}}()
for ticker_symbol ∈ ticker_symbol_array
# what is the *actual* price data?
local actual_price_data = price_data_dictionary[ticker_symbol][end-𝒯:end, :close]
# get initial price -
initial_price_value = log(actual_price_data[1])
# compute a set of possible trajectories -> convert back to actual price -
monte_carlo_simulation_dictionary[ticker_symbol] = LAPLACE(initial_price_value, 𝒯;
number_of_sample_paths = number_of_sample_paths, number_of_strata = number_of_strata) .|> exp
end
# show -
nothing
end
# ╔═╡ ff11bdd2-8ab6-40c0-844b-a3474d7e9a04
Z = monte_carlo_simulation_dictionary[single_asset_ticker_symbol]
# ╔═╡ cac02388-31c4-40b9-8288-a6685e1854fb
begin
# plot the histogram -
stephist(Z[end,:], normed=true, lw=2, c=BLUE,
label="Close price $(single_asset_ticker_symbol) (T = $(𝒯))",
background_color = BACKGROUND, background_color_outside = WHITE,
foreground_color_legend = nothing)
xlabel!("Simulated close price $(single_asset_ticker_symbol) (T = $(𝒯)) (USD/share)", fontsize=18)
ylabel!("Frequency (dimensionless)", fontsize = 14)
end
# ╔═╡ a1e1d5f8-e06e-4682-ab54-a9454a8e3b30
md"""
__Fig 4__: In sample random walk simulation of ticker = $(single_asset_ticker_symbol) for a 𝒯 = $(𝒯) day prediction horizon. Blue lines denotes simulated sample paths while the red line denotes the actual price trajectory for ticker $(single_asset_ticker_symbol). The simulation consisted of N = $(2*number_of_sample_paths) sample paths.
"""
# ╔═╡ b547311c-ddf0-4053-9de4-f0e85b861e63
md"""
__Table 2__: Comparison of the actual versus simulated close price for a 𝒯 = $(𝒯) day prediction horizon for each ticker in the PSIA (𝒫 = 40). Each ticker was classified c ∈ {-1,0,1} based upon whether the actual close price Pₐ ∈ Pₑ ± σ, where Pₐ denotes the actual close price (units: USD/share), Pₑ denotes the mean simulated close price (units: USD/share), and σ denotes the standard deviation of the simulated close price (units: USD/share) computed over the family Monte Carlo trajectories (N = $(2*number_of_sample_paths)). Classes: +1 HIGH, 0 INSIDE, or -1 LOW.
"""
# ╔═╡ aeafe1ed-f217-48fd-9624-add5f6f791e6
begin
# setup some preliminaries -
skip_factor = convert(Int64, round(0.01*(2*number_of_sample_paths*number_of_strata)))
plot_index_array = 1:skip_factor:(2*number_of_sample_paths*number_of_strata) |> collect
simulated_price_trajectory = monte_carlo_simulation_dictionary[single_asset_ticker_symbol]
# what is the *actual* price data?
actual_price_data = price_data_dictionary[single_asset_ticker_symbol][end-𝒯:end, :close]
# plot -
plot(simulated_price_trajectory[:, plot_index_array], c = LBLUE, legend = false, label = "", lw = 1,
background_color = BACKGROUND, background_color_outside = WHITE)
if (show_real_traj == true)
plot!(actual_price_data[1:end], c = RED, lw = 3, legend = :topleft,
label = "$(single_asset_ticker_symbol) actual", foreground_color_legend = nothing)
end
xlabel!("Time step index (day)", fontsize = 18)
ylabel!("Simulated $(single_asset_ticker_symbol) close price (USD/share)", fontsize = 14)
# title!("Random walk simulation $(single_asset_ticker_symbol) (N = $(number_of_sample_paths))", fontsize=12)
end
# ╔═╡ 2ed2f3c3-619b-4aed-b88b-b92a43578d84
with_terminal() do
# initialize some storage -
price_state_table = Array{Any,2}(undef, number_of_ticker_symbols, 10)
for ticker_symbol_index ∈ 1:number_of_ticker_symbols
# get the symbol -
ticker_symbol = ticker_symbol_array[ticker_symbol_index]
# compute some data re this symbol -
simulated_price_trajectory = monte_carlo_simulation_dictionary[ticker_symbol]
estimated_mean_price = round(mean(simulated_price_trajectory[end, :]), sigdigits = 4)
std_estimated_price = round(std(simulated_price_trajectory[end, :]), sigdigits = 4)
actual_price_data = price_data_dictionary[ticker_symbol][end-𝒯:end, :close]
price_actual = actual_price_data[end]
tmp_LB = estimated_mean_price - 1*std_estimated_price
tmp_UB = estimated_mean_price + 1*std_estimated_price
# populate state table -
price_state_table[ticker_symbol_index,1] = ticker_symbol
price_state_table[ticker_symbol_index,2] = actual_price_data[1]
price_state_table[ticker_symbol_index,3] = price_actual
price_state_table[ticker_symbol_index,4] = estimated_mean_price
price_state_table[ticker_symbol_index,5] = ((price_actual - estimated_mean_price)/price_actual)*100
price_state_table[ticker_symbol_index,6] = tmp_LB
price_state_table[ticker_symbol_index,7] = tmp_UB
δL = max(0,round(tmp_LB - price_actual, sigdigits = 4))
δU = max(0,round(price_actual - tmp_UB, sigdigits = 4))
price_state_table[ticker_symbol_index,8] = δL
price_state_table[ticker_symbol_index,9] = δU
if (δL == 0.0 && δU == 0.0)
price_state_table[ticker_symbol_index,10] = 0 # exepcted
elseif (δL>0.0 && δU == 0.0)
price_state_table[ticker_symbol_index,10] = -1 # oversold
elseif (δL == 0.0 && δU > 0.0)
price_state_table[ticker_symbol_index,10] = 1 # overbought
end
end
price_table_header = (
["ticker", "P₀ (𝒯 = 0)", "Pₐ (𝒯 = 14)", "Pₑ (𝒯 = 14)", "ΔP/Pₐ", "ℒ = (Pₑ - σ)", "𝒰 = (Pₑ + σ)", "δL = max(0, ℒ - Pₐ)",
"δU = max(0, Pₐ - 𝒰)", "class c"],
["", "USD/share", "USD/share", "USD/share", "%", "USD/share", "", "USD/share", "USD/share","c ∈ {-1,0,1}"]
)
pretty_table(price_state_table, header=price_table_header)
end
# ╔═╡ c8c3fe32-560d-11ec-0617-2dc33608384a
html"""
<style>
main {
max-width: 1200px;
width: 85%;
margin: auto;
font-family: "Roboto, monospace";
}
a {
color: blue;
text-decoration: none;
}
.H1 {
padding: 0px 30px;
}
</style>"""
# ╔═╡ 5394b13a-e629-47c8-902d-685c061b37ae
html"""
<script>
// initialize -
var section = 0;
var subsection = 0;
var headers = document.querySelectorAll('h3, h5');
// main loop -
for (var i=0; i < headers.length; i++) {
var header = headers[i];
var text = header.innerText;
var original = header.getAttribute("text-original");
if (original === null) {
// Save original header text
header.setAttribute("text-original", text);
} else {
// Replace with original text before adding section number
text = header.getAttribute("text-original");
}
var numbering = "";
switch (header.tagName) {
case 'H3':
section += 1;
numbering = section + ".";
subsection = 0;
break;
case 'H5':
subsection += 1;
numbering = section + "." + subsection;
break;