-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcommits_2024_09_alphar.txt
2279 lines (2217 loc) · 168 KB
/
commits_2024_09_alphar.txt
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
5562d69934df98736b4e037b9e68ac422e5b2e1a MislavSag Wed Sep 4 13:23:46 2024 +0000 update
diff --git a/R/exlusion_list.R b/R/exlusion_list.R
new file mode 100644
index 0000000..116908d
--- /dev/null
+++ b/R/exlusion_list.R
@@ -0,0 +1,84 @@
+library(data.table)
+library(tabulizer)
+library(stringr)
+library(AzureStor)
+library(xts)
+
+
+# PDF url
+url = "https://www.robeco.com/files/docm/docu-exclusion-list.pdf"
+
+# Get PDF tables
+result = list()
+for (i in 2:5){
+ out = as.data.table(extract_tables(url, page = i, method = 'stream'))
+ result[[i-1]] = out
+}
+
+# Remove all empty rows
+dt = lapply(result, function(x) {
+ ns = unlist(x[, lapply(.SD, function(y) all(y == ''))], use.names = TRUE)
+ col_ = names(ns[ns == TRUE])
+ x[, (col_) := NULL]
+ x
+})
+
+# Check if all values in column are numbers. If yes, bind with next column
+dt = lapply(dt, function(x) {
+ vector_delete = c()
+ for (i in 1:(ncol(x)-1)) {
+ if (all(str_detect(x[[i]], "^[0-9]+$"))) {
+ x[[i]] = paste0(x[[i]], " ", x[[i+1]])
+ vector_delete = c(vector_delete, i+1)
+ }
+ }
+ x[, (colnames(x)[vector_delete]) := NULL]
+ x
+})
+dt[[2]]
+
+# Make multicolumn data.table one column data.table
+dt = lapply(dt, function(x) {
+ if (ncol(x) > 1) {
+ x = melt(x, measure.vars = colnames(x))
+ }
+ x[, 2]
+})
+dt = rbindlist(dt)
+dt = dt[value != ""]
+
+# Check if row contain number
+dt[, number := str_extract(value, "^[0-9]+")]
+dt[200:250]
+dt[250:300]
+dt[, meta_logical := is.na(number) &
+ ((shift(number, 1, type = "lead") == 1 & !grepl("level", value, ignore.case = TRUE)) |
+ grepl("level", shift(value, 1, type = "lead"), ignore.case = TRUE))]
+dt[meta_logical == TRUE, meta := value]
+dt[, meta := na.locf(meta)]
+dt = dt[, .(meta, company = value)]
+
+# Check
+dt[130:200]
+
+# Remove first numbersequence tokenized by spce form comapny column
+dt[, company := str_remove(company, "^[0-9]+\\s+")]
+
+# Remove meta meta
+dt = dt[meta != company]
+
+# Remove all rows that contain onlz umbers in company column
+dt = dt[!grepl("^[0-9]+$", company)]
+
+# Exclude list
+dt[, unique(meta)]
+pat = "Controversial weapons|Thermal coal mining|Thermal coal power|Coal power expansion plans"
+dt[, exclude := grepl(pat, meta)]
+
+# Save
+fwrite(dt, "F:/meta/exclusion_list.csv")
+
+# Add to Azure
+bl_endp_key = storage_endpoint(Sys.getenv("BLOB-ENDPOINT-SNP"), Sys.getenv("BLOB-KEY-SNP"))
+cont = storage_container(bl_endp_key, "qc-live")
+storage_write_csv(dt, cont, "exclusion_list.csv")
diff --git a/R/exuber_v4.R b/R/exuber_v4.R
index 7d3a301..d798e3c 100644
--- a/R/exuber_v4.R
+++ b/R/exuber_v4.R
@@ -10,6 +10,8 @@ library(runner)
library(glue)
library(tsDyn)
library(AzureStor)
+library(gausscov)
+library(readr)
# library(vars)
# library(ggplot2)
@@ -639,8 +641,6 @@ charts.PerformanceSummary(backtest_xts)
# ROLLING GAUSSCOV --------------------------------------------------------
-library(gausscov)
-
# Prepare data
dt = copy(backtest_data)
dt[, y := shift(close, n = 1, type = "lead") / close - 1]
@@ -716,6 +716,7 @@ dates = f1st_res_dt[, unique(date)]
min_date = dt[, min(date)]
predictions = vector("numeric", length(dates))
for (i in seq_along(dates)) {
+ # i = 1000
sample_dt = dt[date %between% c(min_date, dates[i]),
.SD,
.SDcols = c("y", na.omit(f1st_res_dt[date == dates[i]]$cols))]
@@ -730,21 +731,25 @@ predictions_dt = merge(dt[, .(date, close)], predictions_dt, by = "date")
# Backtest
predictions_dt[, signal := predictions > 0]
predictions_dt[, spy := close / shift(close) - 1]
-predictions_dt[, strategy := spy * shift(signal)]
+predictions_dt[, strategy := spy * shift(signal, 1)]
+predictions_dt = predictions_dt[date > as.Date("2002-10-01")] # to match QC backtest
backtest_xts = as.xts.data.table(predictions_dt[, .(date, spy, strategy)])
charts.PerformanceSummary(backtest_xts)
-charts.PerformanceSummary(backtest_xts[35000:nrow(backtest_xts)])
+# charts.PerformanceSummary(backtest_xts[35000:nrow(backtest_xts)])
+# charts.PerformanceSummary(backtest_xts[2180:nrow(backtest_xts)]) # same as QC
# Save for QC backtesting
qc_data = predictions_dt[, .(date, signal)]
qc_data = na.omit(qc_data)
-qc_data[, date := as.character(date)]
+qc_data[, let(
+ date = as.character(date),
+ signal = as.integer(signal)
+)]
bl_endp_key = storage_endpoint(Sys.getenv("BLOB-ENDPOINT-SNP"), Sys.getenv("BLOB-KEY-SNP"))
cont = storage_container(bl_endp_key, "qc-backtest")
storage_write_csv(qc_data, cont, "exuber_gausscov.csv", col_names = FALSE)
-
# TVAR --------------------------------------------------------------------
# prepare data2
varvar = "sd_radf_sum" # kurtosis_bsadf_log, sd_radf_sum
@@ -888,8 +893,8 @@ tvar_backtest <- function(tvar_res_i) {
sides[i] <- 0
} else if (indicator[i-1] > threshold_1[i-1] & coef_ret_1_middle[i-1] < 0 & coef_ret_2_middle[i-1] < 0) {
sides[i] <- 0
- # } else if (indicator[i-1] < threshold_1[i-1] & coef_ret_1_down[i-1] < 0 & coef_ret_2_down[i-1] < 0 & coef_ret_3_down[i-1] < 0) {
- # sides[i] <- 0
+ # } else if (indicator[i-1] < threshold_1[i-1] & coef_ret_1_down[i-1] < 0 & coef_ret_2_down[i-1] < 0 & coef_ret_3_down[i-1] < 0) {
+ # sides[i] <- 0
} else {
sides[i] <- 1
}
diff --git a/R/fund_price_disbalanse.R b/R/fund_price_disbalanse.R
index 4bed0f1..8f7aa46 100644
--- a/R/fund_price_disbalanse.R
+++ b/R/fund_price_disbalanse.R
@@ -171,9 +171,10 @@ backtest = function(uni,
# DEBUG
# uni[, .(symbol, date, date_month, target)][date_month == as.Date("2024-01-31")]
if (ret_sharpe) {
- uni = uni[, .(ret = sum(target * (1 / length(target)))), by = date_month]
- # sr = PerformanceAnalytics::SharpeRatio(as.xts.data.table(uni))
- sr = PerformanceAnalytics::SortinoRatio(as.xts.data.table(uni))
+ uni[, weight := 1 / length(target), by = date_month]
+ uni = uni[, .(ret = sum(target * weight)), by = date_month]
+ sr = PerformanceAnalytics::SharpeRatio(as.xts.data.table(uni))
+ # sr = PerformanceAnalytics::SortinoRatio(as.xts.data.table(uni))
# sr = Return.annualized(as.xts.data.table(uni))
return(sr[1, ])
} else {
@@ -181,11 +182,11 @@ backtest = function(uni,
}
}
params = expand.grid(
- eps_thresh = c(-100, 0), # min EPS to include stock in universe
+ eps_thresh = c(-100, 0), # min EPS to include stock in universe. -100 means all.
close_raw_thresh = c(1, 10, 20), # min price to include stock in universe
epsg_thresh = c(100, 200, 500), # how many stocks to possibly include in universe
return_mom = cols[c(1, 6, 12)], # return period to calculate to identify mean reversion
- eps_n = cols_epsg[c(1, 3, 6)], # number of months to calculate EPS SD
+ eps_n = cols_epsg[c(1, 3, 6, 9)],# number of months to calculate EPS SD
mom_n = c(10, 20, 50), # number of stocks to include in universe
coarse_n = c(1000, 2000), # number of stocks to include in coarse universe
rev_positive = c(TRUE, FALSE), # include only stocks with positive revenue growth
@@ -204,7 +205,7 @@ results[ind_]
# Check best backtest
best_ = backtest(universe, params[ind_, 1], params[ind_, 2], params[ind_, 3],
params[ind_, 4], params[ind_, 5], params[ind_, 6],
- params[ind_, 7], FALSE)
+ params[ind_, 7], params[ind_, 8], FALSE)
best_ret = best_[, .(ret = sum(target * (1 / length(target)))), by = date_month]
best_xts = as.xts.data.table(best_ret[, .(date_month, ret)])
Return.annualized(best_xts)
diff --git a/R/ib_history.R b/R/ib_history.R
new file mode 100644
index 0000000..6531bb3
--- /dev/null
+++ b/R/ib_history.R
@@ -0,0 +1,68 @@
+library(ibrestr)
+library(data.table)
+library(AzureStor)
+
+
+# Init IB
+ib = IB$new(
+ host = "cgspaperpra.eastus.azurecontainer.io",
+ port = 5000,
+ strategy_name = "Least Volatile Local",
+ account_id = "DU6474915",
+ email_config = list(
+ email_from = "[email protected]",
+ email_to = "[email protected]",
+ smtp_host = "mail.contentio.biz",
+ smtp_port = 587,
+ smtp_user = "[email protected]",
+ smtp_password = "s8^t5?}r-x&Q"
+ ),
+ logger = NULL
+)
+
+# Check gateway
+ib$check_gateway()
+
+# Find VIX conid
+vix_symbols = ib$search_contract_by_symbol("VIX")
+vix_symbols[[1]]
+
+# Get history data for VIX
+dates = seq.POSIXt(as.POSIXct("2005-09-01 16:00:00"), Sys.time(), by = "130 days")
+vix_history = list()
+for (i in seq_along(dates)) {
+ print(dates[i])
+ test_ = tryCatch({
+ vix_history[[i]] = ib$get_historical_data_hmds(
+ conid = "13455763",
+ barType = "Last",
+ period = "150d",
+ bar = "1h",
+ startTime = format.POSIXct(dates[i], "%Y%m%d-%H:%M:%S"),
+ clean = TRUE
+ )
+ }, error = function(e) NULL)
+ if (is.null(test_)) {
+ Sys.sleep(15L)
+ vix_history[[i]] = ib$get_historical_data_hmds(
+ conid = "13455763",
+ barType = "Last",
+ period = "150d",
+ bar = "1h",
+ startTime = format.POSIXct(dates[i], "%Y%m%d-%H:%M:%S"),
+ clean = TRUE
+ )
+ }
+}
+vix_history_dt = rbindlist(vix_history)
+vix_history_dt = unique(vix_history_dt)
+
+# Checks
+head(vix_history_dt[as.Date(datetime) > as.Date("2020-01-01")], 20)
+
+# Save to Azure
+qc_data = vix_history_dt[, .(date = datetime, open = o, high = h, low = l, close = c)]
+qc_data[, date := as.character(date)]
+bl_endp_key = storage_endpoint(Sys.getenv("BLOB-ENDPOINT-SNP"), Sys.getenv("BLOB-KEY-SNP"))
+cont = storage_container(bl_endp_key, "qc-backtest")
+storage_write_csv(qc_data, cont, "vix.csv", col_names = FALSE)
diff --git a/R/mining_sesonality_rolling.R b/R/mining_sesonality_rolling.R
index fa9777a..6b6ecd0 100644
--- a/R/mining_sesonality_rolling.R
+++ b/R/mining_sesonality_rolling.R
@@ -1,119 +1,161 @@
library(data.table)
library(quantreg)
-library(AzureStor)
library(qlcal)
library(lubridate)
+library(AzureStor)
+# SET UP ------------------------------------------------------------------
+# global vars
+PATH = "F:/data/equity/us"
-# DATA IMPORT -------------------------------------------------------------
-# set up
+# Set calendar
+calendars
setCalendar("UnitedStates/NYSE")
-# import daily market data
-system.time({dt = fread("F:/lean_root/data/all_stocks_daily.csv")})
-# this want be necessary after update
-setnames(dt, c("date", "open", "high", "low", "close", "volume", "close_adj", "symbol"))
+# PRICE DATA --------------------------------------------------------------
+# Import QC daily data
+prices = fread("F:/lean/data/stocks_daily.csv")
+setnames(prices, gsub(" ", "_", c(tolower(colnames(prices)))))
+
+# Remove duplicates
+prices = unique(prices, by = c("symbol", "date"))
+
+# Remove duplicates - there are same for different symbols (eg. phun and phun.1)
+dups = prices[, .(symbol , n = .N),
+ by = .(date, open, high, low, close, volume, adj_close,
+ symbol_first = substr(symbol, 1, 1))]
+dups = dups[n > 1]
+dups[, symbol_short := gsub("\\.\\d$", "", symbol)]
+symbols_remove = dups[, .(symbol, n = .N),
+ by = .(date, open, high, low, close, volume, adj_close,
+ symbol_short)]
+symbols_remove[n >= 2, unique(symbol)]
+symbols_remove = symbols_remove[n >= 2, unique(symbol)]
+symbols_remove = symbols_remove[grepl("\\.", symbols_remove)]
+prices = prices[symbol %notin% symbols_remove]
+
+# Adjust all columns
+prices[, adj_rate := adj_close / close]
+prices[, let(
+ open = open*adj_rate,
+ high = high*adj_rate,
+ low = low*adj_rate
+)]
+setnames(prices, "close", "close_raw")
+setnames(prices, "adj_close", "close")
+prices[, let(adj_rate = NULL)]
+setcolorder(prices, c("symbol", "date", "open", "high", "low", "close", "volume"))
+
+# Remove observations where open, high, low, close columns are below 1e-008
+# This step is opional, we need it if we will use finfeatures package
+prices = prices[open > 1e-008 & high > 1e-008 & low > 1e-008 & close > 1e-008]
+
+# Remove missing values
+prices = na.omit(prices)
+
+# Keep only symbol with at least 2 years of data
+# This step is optional
+symbol_keep = prices[, .N, symbol][N >= 2 * 252, symbol]
+prices = prices[symbol %chin% symbol_keep]
+
+# Sort
+setorder(prices, symbol, date)
-# remove duplicates
-dt = unique(dt, by = c("symbol", "date"))
+# save SPY for later and keep only events symbols
+spy = prices[symbol == "spy"]
-# remove missing values
-dt = na.omit(dt)
+# free memory
+gc()
-# order data
-setorder(dt, "symbol", "date")
-# adjust all prices, not just close
-adjust_cols <- c("open", "high", "low")
-adjust_cols_new <- c("open_adj", "high_adj", "low_adj")
-dt[, (adjust_cols_new) := lapply(.SD, function(x) x * (close_adj / close)), .SDcols = adjust_cols] # adjust open, high and low prices
+# PREPARE DATA FOR SEASONALITY ANALYSIS -----------------------------------
+# Calculate return
+prices[, returns := close / shift(close) - 1, by = symbol] # calculate returns
-# calculate returns
-dt[, returns := close_adj / shift(close_adj) - 1, by = symbol] # calculate returns
-dt <- dt[returns < 1] # TODO:: better outlier detection mechanism. For now, remove daily returns above 100%
+# Remove outliers
+nrow(prices[returns > 1]) / nrow(prices)
+prices = prices[returns < 1] # TODO:: better outlier detection mechanism. For now, remove daily returns above 100%
-# plot
-plot(as.xts.data.table(dt[symbol == "aapl", .(date, close_adj)]))
-plot(as.xts.data.table(dt[symbol == "meta", .(date, close_adj)]))
-plot(as.xts.data.table(dt[symbol == "fb", .(date, close_adj)]))
+# define target variables
+prices[, return_day := shift(close, 1, type = "lead") / close - 1, by = symbol]
+prices[, return_day3 := shift(close, 3, type = "lead") / close - 1, by = symbol]
+prices[, return_week := shift(close, 5, type = "lead") / close - 1, by = symbol]
+prices[, return_week2 := shift(close, 10, type = "lead") / close - 1, by = symbol]
-# check for zero prices
-dt[close_adj == 0] # there is not zero prices
-dt = dt[close > 0 & close_adj > 0]
+# define frequency unit
+prices[, yearmonthid := yearmon(date)]
+prices[, day_of_month := 1:.N, by = .(symbol, yearmonthid)]
+prices[, day_of_month := as.factor(day_of_month)]
-# remove symobls with < 252 observations
-dt_n <- dt[, .N, by = symbol]
-dt_n <- dt_n[N > 252 * 4]
-dt <- dt[symbol %in% dt_n[, symbol]]
+# Remove missing values and select columns we need
+dt = na.omit(prices, cols = c("symbol", "return_week2", "day_of_month"))
-# save SPY for later and keep only events symbols
-spy <- dt[symbol == "spy"]
+# Structure of dates
+dt[, .N, by = day_of_month] # we probbably want to turn 23 to 22
+dt[day_of_month == 23, day_of_month := 22] # 23 day to 22 day
+dt[day_of_month == 22, day_of_month := 21] # not sure about this but lets fo with it
+# Remove symbols with less than 750 observations (3 years of data)
+symbols_keep = dt[, .N, by = symbol]
+symbols_keep = symbols_keep[N >= 750, symbol]
+dt = dt[symbol %in% symbols_keep]
# SEASONALITY MINING ------------------------------------------------------
-# define target variables
-dt[, return_day := shift(close_adj, 1, type = "lead") / close_adj - 1, by = symbol]
-dt[, return_day3 := shift(close_adj, 3, type = "lead") / close_adj - 1, by = symbol]
-dt[, return_week := shift(close_adj, 5, type = "lead") / close_adj - 1, by = symbol]
-dt[, return_week2 := shift(close_adj, 10, type = "lead") / close_adj - 1, by = symbol]
-
-# define frequency unit
-dt[, yearmonthid := round(date, digits = "month")]
-dt[, day_of_month := 1:.N, by = .(symbol, yearmonthid)]
-dt[, day_of_month := as.factor(day_of_month)]
+# define all year-months and start year
+yearmonthids = dt[, sort(unique(yearmonthid))]
+end_dates = seq.Date(as.Date("2019-01-01"), dt[, max(date)], by = "month")
+end_dates = as.IDate(end_dates)
-# remove missing values
-dt = na.omit(dt, cols = c("symbol", "return_week2", "day_of_month"))
+# Remove symbols inactive before first date. This can produce survivorship bias,
+# but we will be faster. If this doesn't work, it want work with all data fro sure.
+symbols_keep = dt[, (end_dates[1] - max(date)) < 7, by = symbol] # we must have at least 7 days of data
+dt = dt[symbol %in% symbols_keep[V1 == TRUE, symbol]]
-# get coeffs from summary of quantile regression
+# Get coeffs from summary of quantile regression
get_coeffs = function(df, y = "return_week") {
- # df = dt[symbol == "a.1"]
res = rq(as.formula(paste0(y, " ~ day_of_month")), data = as.data.frame(df))
summary_fit = summary.rq(res, se = 'nid')
as.data.table(summary_fit$coefficients, keep.rownames = TRUE)
}
-# define all year-months and start year
-yearmonthids = dt[, sort(unique(yearmonthid))]
-end_years = seq.Date(as.Date("2019-01-01"),
- as.Date("2023-05-01"), by = "month")
-end_years = as.character(end_years)
-# first_year = "2010-01-01"
-
-# get median regression coefficients
-# symbols = dt[, unique(symbol)]
-# sample_ = dt[symbol %in% symbols[1:20000]]
-dt[day_of_month == 23, day_of_month := 22] # 23 day to 22 day
-dt_sample = dt[, .SD[(as.IDate(end_years[1])-max(date)) < 7], by = symbol] # we must have
-dt_sample = dt_sample[, .SD[nrow(.SD) > 1008], by = symbol] # we must have at least 3 yers of data
+# Sample data - this is just for test
+dt_sample = dt[symbol %in% dt[, sample(unique(symbol), 10)]]
-# dt_sample[, year := year(date)]
-X_seasons_day3 = dt_sample[, lapply(as.IDate(end_years), function(y) {
- if ((y - max(date)) > 7) return(list(NA))
- tryCatch(list(get_coeffs(.SD[yearmonthid %between% c(y - 2520, y)]), "return_day3"),
+# get median regression coefficients - experiment
+sample_size_days = 2520
+seasonality_results = dt[, lapply(end_dates, function(date_) {
+ if ((date_ - max(date)) > 7) return(list(NA))
+ # print(date_ - sample_size_days)
+ # get_coeffs(.SD[yearmonthid %between% c(yearmon(y - sample_size_days), yearmon(y))])
+ tryCatch(list(get_coeffs(.SD[yearmonthid %between% c(yearmon(date_ - sample_size_days), yearmon(date_))])),
error = function(e) list(NA))
- }), by = .(symbol)]
-
-cols = paste0("month", strftime(end_years, format = "%y%m%d"))
-colnames(X_seasons_day3)[2:length(colnames(X_seasons_day3))] = cols
+ }), by = symbol]
+cols = paste0("month", strftime(end_dates, format = "%y%m%d"))
+colnames(seasonality_results)[2:length(colnames(seasonality_results))] = cols
# save
time = strftime(Sys.time(), "%Y%m%d%H%M%S")
-saveRDS(X_seasons_day3, file.path("D:/features", paste0("seasonality-day3", time, ".rds")))
+saveRDS(seasonality_results, file.path("D:/features", paste0("seasonality-week", time, ".rds")))
+
+# Import data
+
+
+# INSPECT RESULTS ---------------------------------------------------------
+# seasonality_results[1, month190101]
# CREATE PORTFOLIOS -------------------------------------------------------
-# create portfolio function
+# Portfolio 1 - keep min Pr for every symbol
portfolios_l = list()
for (i in seq_along(cols)) {
# sample
col = cols[i]
cols_ = c("symbol", col)
- x = X_seasons[, ..cols_]
+ x = seasonality_results[, ..cols_]
# remove missing values
x[, number_of_rows := vapply(get(col), function(y) length(y), FUN.VALUE = integer(1L))]
@@ -144,7 +186,7 @@ for (i in seq_along(cols)) {
# sample
col = cols[i]
cols_ = c("symbol", col)
- x = X_seasons[, ..cols_]
+ x = seasonality_results[, ..cols_]
# remove missing values
x[, number_of_rows := vapply(get(col), function(y) length(y), FUN.VALUE = integer(1L))]
@@ -179,7 +221,7 @@ for (i in seq_along(cols)) {
# sample
col = cols[i]
cols_ = c("symbol", col)
- x = X_seasons[, ..cols_]
+ x = seasonality_results[, ..cols_]
# remove missing values
x[, number_of_rows := vapply(get(col), function(y) length(y), FUN.VALUE = integer(1L))]
@@ -211,12 +253,14 @@ portfolio3[, Value := 1]
# clean portfolios
portfolio_prepare = function(portfolio) {
+ # portfolio = copy(portfolio1)
+
# set trading dates
- portfolio[, date := as.Date(gsub("month", "", date), format = "%y%m%d")]
+ # portfolio[, date := as.Date(gsub("month", "", date), format = "%y%m%d")]
portfolio[, rn := gsub("day_of_month", "", rn)]
# get trading days
- date_ = portfolio[, date]
+ date_ = portfolio[, as.Date(paste0(gsub("month", "", date), "01"), format = "%y%m%d")]
seq_ = 1:nrow(portfolio)
seq_dates = lapply(date_, function(x) getBusinessDays(x, x %m+% months(1) - 1))
dates = mapply(function(x, y) x[y], x = seq_dates, y = portfolio[, as.integer(rn)])
diff --git a/R/minmax_panel.R b/R/minmax_panel.R
index 9b65485..d712d2e 100644
--- a/R/minmax_panel.R
+++ b/R/minmax_panel.R
@@ -1,12 +1,11 @@
library(data.table)
+library(Rcpp)
+library(TTR)
library(lubridate)
library(ggplot2)
-library(moments)
-library(TTR)
library(PerformanceAnalytics)
-library(gausscov)
library(runner)
-library(doParallel)
+library(glue)
# UTILS -------------------------------------------------------------------
@@ -17,67 +16,23 @@ AFTER_COVID = c("2021-06-01", "2022-01-01")
CORECTION = c("2022-01-01", "2022-08-01")
NEW = c("2022-08-01", as.character(Sys.Date()))
+# Globals
+RESULTS = "F:/strategies/MinMaxWfo"
-# DATA --------------------------------------------------------------------
-# Import prices and MinMax data
-list.files("F:/predictors/minmax")
-dt = fread("F:/predictors/minmax/20240228.csv")
-
-# check timezone
-dt[, attr(date, "tz")]
-dt[, date := with_tz(date, tzone = "America/New_York")]
-dt[, attr(date, "tz")]
-
-# Spy data
-spy = dt[symbol == "spy", .(date, close, returns)]
-
-# Extreme returns
-cols = colnames(dt)[grep("^p_9", colnames(dt))]
-cols_new_up = paste0("above_", cols)
-dt[, (cols_new_up) := lapply(.SD, function(x) ifelse(returns > x, returns - shift(x), 0)),
- by = .(symbol), .SDcols = cols] # Shifted to remove look-ahead bias
-cols = colnames(dt)[grep("^p_0", colnames(dt))]
-cols_new_down = paste0("below_", cols)
-dt[, (cols_new_down) := lapply(.SD, function(x) ifelse(returns < x, abs(returns - shift(x)), 0)),
- by = .(symbol), .SDcols = cols]
-
-
-# SYSTEMIC RISK -----------------------------------------------------------
-# help function to calcualte tail risk measures from panel
-tail_risk = function(dt, FUN = mean, cols_prefix = "mean_") {
- cols = colnames(dt)[grep("below_p|above_p", colnames(dt))]
- indicators_ = dt[, lapply(.SD, function(x) f(x, na.rm = TRUE)),
- by = .(date), .SDcols = cols,
- env = list(f = FUN)]
- colnames(indicators_) = c("date", paste0(cols_prefix, cols))
- setorder(indicators_, date)
- above_sum_cols = colnames(indicators_)[grep("above", colnames(indicators_))]
- below_sum_cols = colnames(indicators_)[grep("below", colnames(indicators_))]
- excess_sum_cols = gsub("above", "excess", above_sum_cols)
- indicators_[, (excess_sum_cols) := indicators_[, ..above_sum_cols] - indicators_[, ..below_sum_cols]]
-}
-
-# get tail risk mesures
-indicators_mean = tail_risk(dt, FUN = "mean", cols_prefix = "mean_")
-indicators_sd = tail_risk(dt, FUN = "sd", cols_prefix = "sd_")
-indicators_sum = tail_risk(dt, FUN = "sum", cols_prefix = "sum_")
-indicators_skewness = tail_risk(dt, FUN = "skewness", cols_prefix = "skewness_")
-indicators_kurtosis = tail_risk(dt, FUN = "kurtosis", cols_prefix = "kurtosis_")
-
-# merge indicators and spy
-indicators = Reduce(function(x, y) merge(x, y, by = "date", all.x = TRUE, all.y = FALSE),
- list(indicators_mean, indicators_sd, indicators_sum,
- indicators_skewness, indicators_kurtosis))
-# Inspect final table
-dim(indicators)
-excess_cols = colnames(indicators)[grepl("excess", colnames(indicators))]
-
-# Free memory
-rm(dt)
+# DATA --------------------------------------------------------------------
+# SPY data
+spy = fread("F:/predictors/minmax/20240228.csv")
+spy[, attr(date, "tz")]
+spy[, date := with_tz(date, tzone = "America/New_York")]
+spy[, attr(date, "tz")]
+spy = spy[symbol == "spy", .(date, close, returns)]
gc()
-# merge spy and indicators
+# Import indicators
+indicators = fread("F:/predictors/minmax/indicators.csv")
+
+# Merge spy and indicators
sysrisk = merge(indicators, spy, by = "date", all.x = TRUE, all.y = FALSE)
sysrisk = na.omit(sysrisk, cols = "returns")
@@ -113,75 +68,121 @@ na.omit(data_plot)[, mean(returns), by = .(alpha)] |>
ggplot(aes(x = alpha, y = V1)) +
geom_bar(stat = "identity")
-# Prepare backtest data
-# cols = c("date", "close", "returns", excess_cols)
-cols = c("date", "close", "returns", excess_cols[grep("sd_", excess_cols)])
-# colnames(indicators)[grepl("sd_", colnames(indicators))]
+# Choose columns
+# 1) Choose subset of columns
+cols = c("date", "close", "returns", colnames(indicators)[grepl("sum_ex", colnames(indicators))])
backtest_dt = sysrisk[, ..cols]
+# 2) choose all columns
+backtest_dt = copy(sysrisk)
+
+# Remove columns with many NA values
cols_keep = colnames(backtest_dt)[sapply(backtest_dt, function(x) sum(is.na(x))/length(x) < 0.5)]
backtest_dt = backtest_dt[, ..cols_keep]
+
+# Remove NA values
backtest_dt = na.omit(backtest_dt)
-predictors = backtest_dt[, colnames(backtest_dt)[4:ncol(backtest_dt)]]
-# Optimization insample parameters
-params = backtest_dt[, ..predictors]
-params = params[, lapply(.SD, quantile, probs = seq(0, 1, 0.02), na.rm = TRUE)]
-params = melt(params)
-params = merge(data.frame(sma_width=c(1, 5, 15, 22)), params, by=NULL)
-params = unique(params)
+# Define predictors
+predictors = setdiff(colnames(backtest_dt), c("date", "close", "returns"))
+predictors_excess = predictors[grepl("excess", predictors)]
+predictors_sum = predictors[grepl("sum", predictors)]
+predictors_sd = predictors[grepl("sd", predictors)]
+predictors_skew = predictors[grepl("skew", predictors)]
+predictors_kurtosis = predictors[grepl("kurtosis", predictors)]
+
+
+# INSAMPLE OPTIMIZATION ---------------------------------------------------
+# backtest Rcpp
+Rcpp::cppFunction("
+ double backtest_cpp(NumericVector returns, NumericVector indicator, double threshold) {
+ int n = indicator.size();
+ NumericVector sides(n);
+
+ for(int i=0; i<n; i++){
+ if(i==0 || R_IsNA(indicator[i-1])) {
+ sides[i] = 1;
+ } else if (indicator[i-1] < threshold){
+ sides[i] = 0;
+ } else {
+ sides[i] = 1;
+ }
+ }
+
+ NumericVector returns_strategy = returns * sides;
+
+ double cum_returns{ 1 + returns_strategy[0]} ;
+ for(int i=1; i<n; i++){
+ cum_returns *= (1 + returns_strategy[i]);
+ }
+ cum_returns = cum_returns - 1;
+
+ return cum_returns;
+ }
+", rebuild = TRUE)
+Rcpp::cppFunction("
+ double backtest_above_threshold(NumericVector returns, NumericVector indicator, double threshold) {
+ int n = indicator.size();
+ NumericVector sides(n);
+
+ for(int i=0; i<n; i++){
+ if(i==0 || R_IsNA(indicator[i-1])) {
+ sides[i] = 1;
+ } else if (indicator[i-1] > threshold){
+ sides[i] = 0;
+ } else {
+ sides[i] = 1;
+ }
+ }
+
+ NumericVector returns_strategy = returns * sides;
+
+ double cum_returns{ 1 + returns_strategy[0]} ;
+ for(int i=1; i<n; i++){
+ cum_returns *= (1 + returns_strategy[i]);
+ }
+ cum_returns = cum_returns - 1;
+
+ return cum_returns;
+ }
+", rebuild = TRUE)
-# help vectors
-returns_ = backtest_dt[, returns]
-thresholds_ = params[, 3]
-vars = as.vector(params[, 2])
-ns = params[, 1]
-
-# backtest vectorized
-# library(Rcpp)
-# Rcpp::cppFunction("
-# double backtest_cpp(NumericVector returns, NumericVector indicator, double threshold) {
-# int n = indicator.size();
-# NumericVector sides(n);
-#
-# for(int i=0; i<n; i++){
-# if(i==0 || R_IsNA(indicator[i-1])) {
-# sides[i] = 1;
-# } else if(indicator[i-1] < threshold){
-# sides[i] = 0;
-# } else {
-# sides[i] = 1;
-# }
-# }
-#
-# NumericVector returns_strategy = returns * sides;
-#
-# double cum_returns{ 1 + returns_strategy[0]} ;
-# for(int i=1; i<n; i++){
-# cum_returns *= (1 + returns_strategy[i]);
-# }
-# cum_returns = cum_returns - 1;
-#
-# return cum_returns;
-# }
-# ", rebuild = TRUE)
backtest_vectorized = function(returns, indicator, threshold, return_cumulative = TRUE) {
- sides = ifelse(c(NA, head(indicator, -1)) > threshold, 0, 1)
+ # returns = returns_
+ # i = 1
+ # indicator = SMA(backtest_dt[, get(vars[i])], ns[i])
+ # threshold = thresholds_[i]
+ # return_cumulative = TRUE
+
+ # sides = ifelse(c(NA, head(indicator, -1)) > threshold, 0, 1)
+ sides = ifelse(shift(indicator) < threshold, 0, 1)
sides[is.na(sides)] = 1
- returns_strategy <- returns * sides
+ returns_strategy = returns * sides
+ # returns_strategy_1 = returns_strategy
if (return_cumulative) {
+ # cum_returns = 1 + returns_strategy[1]
+ # for (i in 2:length(returns_strategy)) {
+ # cum_returns = cum_returns * (1 + returns_strategy[i])
+ # }
+ # return(cum_returns - 1)
return(PerformanceAnalytics::Return.cumulative(returns_strategy))
} else {
return(returns_strategy)
}
}
backtest <- function(returns, indicator, threshold, return_cumulative = TRUE) {
+ # returns = returns_
+ # i = 1
+ # indicator = SMA(backtest_dt[, get(vars[i])], ns[i])
+ # threshold = thresholds_[i]
+ # return_cumulative = TRUE
+
sides <- vector("integer", length(indicator))
for (i in seq_along(sides)) {
if (i %in% c(1) || is.na(indicator[i-1])) {
- sides[i] <- NA
- } else if (indicator[i-1] > threshold) {
+ sides[i] <- 1
+ } else if (indicator[i-1] < threshold) {
sides[i] <- 0
} else {
sides[i] <- 1
@@ -189,6 +190,8 @@ backtest <- function(returns, indicator, threshold, return_cumulative = TRUE) {
}
sides <- ifelse(is.na(sides), 1, sides)
returns_strategy <- returns * sides
+ # returns_strategy_2 = returns_strategy
+
if (return_cumulative) {
return(PerformanceAnalytics::Return.cumulative(returns_strategy))
} else {
@@ -212,42 +215,295 @@ performance <- function(x) {
return(Perf)
}
+# Function to get parameterss
+get_params = function(dt, predictors) {
+ # Optimization insample parameters
+ params = dt[, ..predictors]
+ params = params[, lapply(.SD, quantile, probs = seq(0, 1, 0.02), na.rm = TRUE)]
+ params = melt(params, variable.factor = FALSE)
+ param_sman = c(1, 5, 15, 22, 44, 66)
+
+ # Combine variables, thresholds and sma_n
+ params_expanded = params[rep(1:.N, each = length(param_sman))]
+ params_expanded[, new_col := rep(param_sman, times = nrow(params))]
+ params_expanded = unique(params_expanded)
+ setnames(params_expanded, c("variable", "thresholds", "sma_n"))
+
+ return(params_expanded)
+}
+
+# Parameters
+params_above_threshold = get_params(backtest_dt, predictors_sd)
+
+# help vectors
+returns_ = backtest_dt[, returns]
+vars = params_expanded[, 1][[1]]
+thresholds_ = params_expanded[, 2][[1]]
+ns = params_expanded[, 3][[1]]
+vars_above = params_above_threshold[, 1][[1]]
+thresholds_above = params_above_threshold[, 2][[1]]
+ns_above = params_above_threshold[, 3][[1]]
+
# optimization loop
system.time({
- opt_results_l =
- vapply(1:nrow(params), function(i)
- backtest_cpp(returns_,
- SMA(sysrisk[, get(vars[i])], ns[i]),
- thresholds_[i]),
- numeric(1))
+ opt_results = vapply(1:nrow(params_expanded), function(i) {
+ backtest_cpp(returns_, SMA(backtest_dt[, get(vars[i])], ns[i]), thresholds_[i])
+ }, numeric(1))
})
-opt_results = cbind.data.frame(params, opt_results_l)
-opt_results = opt_results[order(opt_results$opt_results_l), ]
+opt_results_dt = as.data.table(
+ cbind.data.frame(params_expanded, cum_return = opt_results)
+)
+setnames(opt_results_dt, c("var", "threshold", "sma_n", "cum_return"))
+setorder(opt_results_dt, -cum_return)
+first(opt_results_dt, 10)
+
+# optimization loop for above threshold backtest
+system.time({
+ opt_results = vapply(1:nrow(params_expanded), function(i) {
+ backtest_above_threshold(returns_, SMA(backtest_dt[, get(vars[i])], ns[i]), thresholds_[i])
+ }, numeric(1))
+})
+opt_results_dt = as.data.table(
+ cbind.data.frame(params_expanded, cum_return = opt_results)
+)
+setnames(opt_results_dt, c("var", "threshold", "sma_n", "cum_return"))
+setorder(opt_results_dt, -cum_return)
+first(opt_results_dt, 10)
# optimization loop vectorized
system.time({
- opt_results_vect_l =
- vapply(1:nrow(params), function(i)
- backtest_vectorized(returns_,
- SMA(backtest_dt[, get(vars[i])], ns[i]),
- thresholds_[i]),
+ opt_results_vect =
+ vapply(1:nrow(params_expanded), function(i)
+ backtest_vectorized(returns_, SMA(backtest_dt[, get(vars[i])], ns[i]), thresholds_[i]),
numeric(1))
})
-opt_results_vectorized = cbind.data.frame(params, opt_results_vect_l)
-opt_results_vectorized = opt_results_vectorized[order(opt_results_vectorized$opt_results_vect_l), ]
-
-# Same!
-tail(opt_results_vectorized, 40) # best results
-
-# inspect results
-strategy_returns <- backtest(returns_,
- SMA(backtest_dt[, sd_excess_p_999_halfyear ], 1),
- 0.0001708726,
- FALSE)
+opt_results_vect_dt = as.data.table(
+ cbind.data.frame(params_expanded, cum_return = opt_results_vect)
+)
+setnames(opt_results_vect_dt, c("var", "threshold", "sma_n", "cum_return"))
+setorder(opt_results_vect_dt, -cum_return)
+first(opt_results_vect_dt, 10)
+
+# # optimization loop with backtest
+# system.time({
+# opt_results_r =
+# vapply(1:nrow(params_expanded), function(i)
+# backtest(returns_, SMA(backtest_dt[, get(vars[i])], ns[i]), thresholds_[i]),
+# numeric(1))
+# })
+# # user system elapsed
+# # 1619.35 1.19 1622.57
+# opt_results_r_dt = cbind.data.frame(params_expanded, opt_results_r)
+# setnames(opt_results_r_dt, c("threshold", "sma_n", "var", "cum_return"))
+# setorder(opt_results_r_dt, -cum_return)
+# first(opt_results_r_dt, 10)
+
+# Compare above results. Should be all the same. If all test TRUE, they are same
+all.equal(length(opt_results_vect), length(opt_results_r), length(opt_results))
+all(round(opt_results_vect, 2) == round(opt_results_r, 2))
+all(round(opt_results_vect, 2) == round(opt_results, 2))
+
+# Results across vars
+vars_results = opt_results_dt[, .(var_mean = mean(cum_return)), by = var]
+vars_results[, var_agg := gsub("_.*", "", var)]
+vars_results[, mean(var_mean), by = var_agg]
+
+# inspect best results
+best_strategy = opt_results_dt[1, ]
+strategy_returns = backtest(returns_,
+ SMA(backtest_dt[, .SD, .SDcols = best_strategy$var],
+ best_strategy$sma_n),
+ best_strategy$threshold,
+ FALSE)
dt_xts = xts(cbind(returns_, strategy_returns), order.by = backtest_dt[, date])
charts.PerformanceSummary(dt_xts)
-performance(dt_xts[, 1])
-performance(dt_xts[, 2])
+charts.PerformanceSummary(dt_xts["2020/"])
+charts.PerformanceSummary(dt_xts["2022/"])
+charts.PerformanceSummary(dt_xts["2023/"])
+
+# Results across lags
+dt_ = as.data.table(opt_results_dt)
+dt_[, .(mean = mean(cum_return),
+ median = median(cum_return)), by = sma_n]
+
+# Optimization for above threshold
+opt_results_above = vapply(1:nrow(params_above_threshold), function(i) {
+ backtest_cpp(returns_,
+ SMA(backtest_dt[, get(vars_above[i])], ns_above[i]),
+ thresholds_above[i])
+}, numeric(1))
+opt_results_above_dt = as.data.table(
+ cbind.data.frame(params_above_threshold, cum_return = opt_results_above)
+)
+setnames(opt_results_above_dt, c("var", "threshold", "sma_n", "cum_return"))
+setorder(opt_results_above_dt, -cum_return)
+first(opt_results_above_dt, 10)
+
+
+# RCPP VS R ---------------------------------------------------------------
+# Source backtest.cpp file
+sourceCpp("backtest.cpp")
+
+# Backtest function
+system.time({
+ x = backtest(
+ returns_,
+ SMA(backtest_dt[, .SD, .SDcols = best_strategy$var], best_strategy$sma_n),
+ best_strategy$threshold,
+ TRUE)
+})
+system.time({
+ y = backtest_sell_below_threshold(
+ returns_,