-
Notifications
You must be signed in to change notification settings - Fork 0
/
libtrade.R
1540 lines (1267 loc) · 48 KB
/
libtrade.R
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
##############################################################################################
#
# trading library
#
# version : 1.01
# modified on : 22 Nov 2013
#
# version 1.01 - fix defect on gen_sig_trade_rule1 when upperbound is value
#
##############################################################################################
#
# TODO:
#
# 1) Once the matched stock found, observation found it can continue going down
# substantially. A monitoring procedure should be implement to only buy
# when there is 10% reverse from the open price to the buttom, and the current
# price is lower then the permited gap. eg. EXEP on 20131014
#
# 2) set max trade to 10 and min trade to 4. The
# the max allocation should 25% for each stock.
#
# 3) check the daily volumn of the stock before placing order. Avoid those very
# low volumne stock especially in SP600. eg. PCTI
# 4) put a horizontal line at the trade report chart to indicate avg buying price
#
##############################################################################################
source(Sys.getenv('R_USER_DIR_CFG_FILE'));
source(cfg_file_libtrade);
#########################################################################
#
# Date 24 AUG 2012
#
# my library
#
##########################################################################
library('quantmod');
library("PerformanceAnalytics");
convert_number_scale_to_numeric <- function(strValue){
if (is.na(strValue)) {
return(NA);
}
# remove whitespace
strTemp <- gsub("^\\s+|\\s+$", "", strValue);
# remove $ and comma
strTemp <- toupper(gsub(",","",(gsub("\\$", "", strTemp))));
strScale <- substr(strTemp, nchar(strTemp), nchar(strTemp));
if(strScale == 'B' || strScale == 'M' || strScale == 'K'){
strNum <- substr(strTemp, 1, nchar(strTemp)-1);
} else {
strNum <- strTemp;
}
if(strScale == 'B'){
num <- as.numeric(strNum) * 1000000000;
} else if(strScale == 'M'){
num <- as.numeric(strNum) * 1000000;
} else if(strScale == 'K'){
num <- as.numeric(strNum) * 1000;
} else{
num <- as.numeric(strNum);
}
return(num);
}
# search my downloaded price and set symbols to local lookup from the
# csv file
create_local_symbol_lookup <- function
(
SymLookUpFile = 'SymLookUpFile.dat',
SymLookUpDir = '../data/finance/'
)
{
library('quantmod')
US_stock_dir = '../data/finance/US/price'
stock_date_format = '%Y-%m-%d'
#find the symbols of the list of historical price file in drive.
downloaded_sym <- list.files(path=US_stock_dir)
downloaded_sym <- toupper(gsub("\\.csv","",downloaded_sym))
for(s in downloaded_sym) {
temp = list()
temp[[ s ]] = list(src='csv', format=stock_date_format, dir=US_stock_dir)
setSymbolLookup(temp)
}
KL_stock_dir = '../data/finance/MY/price'
stock_date_format = '%Y-%m-%d'
#find the symbols of the list of historical price file in drive.
downloaded_sym <- list.files(path=KL_stock_dir)
downloaded_sym <- toupper(gsub("\\.csv","",downloaded_sym))
for(s in downloaded_sym) {
temp = list()
temp[[ s ]] = list(src='csv', format=stock_date_format, dir=KL_stock_dir)
setSymbolLookup(temp)
}
saveSymbolLookup(SymLookUpFile,dir=SymLookUpDir)
}
# init the local symbol lookup
set_local_symbol_lookup <- function()
{
SymLookUpFile = 'SymLookUpFile.dat'
SymLookUpDir = '../data/finance/'
loadSymbolLookup(SymLookUpFile,dir=SymLookUpDir)
}
# used in calculating seasonality
subset_full_yr <- function(x)
{
if(format(index(x[1]), '%m') != '01'){
yr <- as.numeric(format(index(x[1]), '%Y')) + 1
subset <- paste(yr, '/' ,sep='')
x <- x[subset]
}
if(format(index(x[nrow(x)]), '%m') != '12'){
yr <- as.numeric(format(index(x[nrow(x)]), '%Y')) -1
subset <- paste('/',yr ,sep='')
x <- x[subset]
}
return(x)
}
#################################################################################
# RSI weight
#################################################################################
create_weight <- function(long_cond, long_exit_cond,
short_cond, short_exit_cond)
{
long_weight <- ifelse(long_cond, 1, (ifelse(long_exit_cond, NA, 0)))
short_weight <- ifelse(short_cond, -1, (ifelse(short_exit_cond, NA, 0)))
if(is.na(long_weight[1])) long_weight[1] = 0 #set to 0 if not a buy long level signal
long_weight <- na.locf(long_weight)
if(is.na(short_weight[1])) short_weight[1] = 0 #set to 0 if not a buy short level signal
short_weight <- na.locf(short_weight)
long_short_weight <- long_weight + short_weight
long_short_weight <- lag(long_short_weight)
long_short_weight[is.na(long_short_weight)] = 0
return(long_short_weight)
}
# allow the short thresold lower then long level and long thresold higher then short level
create_weight_1 <- function(long_cond, long_exit_cond,
short_cond, short_exit_cond)
{
long_weight <- ifelse(long_cond, 1, (ifelse(long_exit_cond, NA, 0)))
short_weight <- ifelse(short_cond, -1, (ifelse(short_exit_cond, NA, 0)))
if(is.na(long_weight[1])) long_weight[1] = 0 #set to 0 if not a buy long level signal
long_weight <- na.locf(long_weight)
if(is.na(short_weight[1])) short_weight[1] = 0 #set to 0 if not a buy short level signal
short_weight <- na.locf(short_weight)
# if both long and short have non-zero, its value is depend on the previous value.
# if both previous value is 0, then 1, < longlevel and 0, > shortlevel
for(i in 2:length(long_weight))
{
if(long_weight[i] == 1 && short_weight == -1)
{
# if both previous value is 0, then 1, < longlevel and 0, > shortlevel
if(long_weight[i-1] == 0 && short_weight[i-1] == -1){
long_weight[i] = 0
short_weight[i] = -1
}else if(long_weight[i-1] == 1 && short_weight[i-1] == 0){
long_weight[i] = 1
short_weight[i] = 0
}
else if(long_weight[i-1] == 0 && short_weight[i-1] == 0)
{
if(long_cond[i]){
long_weight[i] = 1
short_weight[i] = 0
}else if(short_cond[i]){
long_weight[i] = 0
short_weight[i] = -1
}
}
}
}
long_short_weight <- long_weight + short_weight
long_short_weight <- lag(long_short_weight)
long_short_weight[is.na(long_short_weight)] = 0
return(long_short_weight)
}
create_weight_2 <- function(long_cond, long_exit_cond,
short_cond, short_exit_cond)
{
long_weight <- ifelse(long_cond, 1, (ifelse(long_exit_cond, NA, 0)))
short_weight <- ifelse(short_cond, -1, (ifelse(short_exit_cond, NA, 0)))
if(is.na(long_weight[1])) long_weight[1] = 0 #set to 0 if not a buy long level signal
long_weight <- na.locf(long_weight)
if(is.na(short_weight[1])) short_weight[1] = 0 #set to 0 if not a buy short level signal
short_weight <- na.locf(short_weight)
# if both long and short have non-zero, its value is depend on the previous value.
idx <- which(long_weight==1 & short_weight==-1)
# if both previous value is 0, then 1, < longlevel and 0, > shortlevel
for(i in idx)
{
# if both previous value is 0, then 1, < longlevel and 0, > shortlevel
if(long_weight[i-1] == 0 && short_weight[i-1] == -1){
long_weight[i] = 0
short_weight[i] = -1
}else if(long_weight[i-1] == 1 && short_weight[i-1] == 0){
long_weight[i] = 1
short_weight[i] = 0
}
else if(long_weight[i-1] == 0 && short_weight[i-1] == 0)
{
if(long_cond[i]){
long_weight[i] = 1
short_weight[i] = 0
}else if(short_cond[i]){
long_weight[i] = 0
short_weight[i] = -1
}
}
}
long_short_weight <- long_weight + short_weight
long_short_weight <- lag(long_short_weight)
long_short_weight[is.na(long_short_weight)] = 0
return(long_short_weight)
}
rsi_weight <- function(indlonglevel=10, indlongthresold=20,
indshortlevel=90, indshortthresold=80, rsi)
{
weight <- create_weight(rsi < indlonglevel, rsi < indlongthresold,
rsi > indshortlevel, rsi > indshortthresold)
return(weight)
}
create_rsi_sig <- function(R, indlonglevel, indlongthresold,
indshortlevel, indshortthresold, rsi_period)
{
rsi <- RSI(R, rsi_period);
rsi[is.na(rsi)] = 50
sig <- create_weight_2(rsi < indlonglevel, rsi < indlongthresold,
rsi > indshortlevel, rsi > indshortthresold);
return(sig)
}
print_stat <- function(idvSta)
{
cat(paste('Num of non-trading day : ', nrow(idvSta[idvSta==0]) ,'\n'))
cat(paste('Num of ret > 0 : ', nrow(idvSta[idvSta>0]),'\n'))
cat(paste('Num of ret < 0 : ', nrow(idvSta[idvSta<0]),'\n'))
cat(paste('Winning Rate : ', round(nrow(idvSta[idvSta>0]) / ( nrow(idvSta[idvSta>0]) + nrow(idvSta[idvSta<0])) , digits=2),'\n'))
cat(paste('SUM of ret > 0 : ', round(sum(idvSta[idvSta>0]), digits=2),'\n'))
cat(paste('SUM of ret < 0 : ', round(sum(idvSta[idvSta<0]), digits=2),'\n'))
cat(paste('Mean Return : ', round(mean(idvSta, na.rm=TRUE), digits=2),'\n'))
cat('\n')
idvSta_wo_zero <- idvSta[idvSta !=0]
cat('Return Distribution:\n')
print(table(cut(idvSta_wo_zero, c(-Inf,seq(-10, 10, by=1)/100,Inf))))
cat('\n')
cat('Return greater then 10% :\n')
print(idvSta[idvSta>0.1])
cat('\n')
print(Return.annualized(idvSta))
cat('\n Top 5 Max Drawdraw')
print(table.Drawdowns(idvSta))
# par(no.readonly = T)
# chart.Histogram(idvSta, methods=c('add.centered', 'add.density', 'add.rug'))
layout(rbind(c(1,2),c(3,4)))
chart.Histogram(idvSta_wo_zero, main = "Plain", methods = NULL)
chart.Histogram(idvSta_wo_zero, main = "Density", breaks=40, methods = c("add.density", "add.normal"))
chart.Histogram(idvSta_wo_zero, main = "Skew and Kurt", methods = c("add.centered", "add.rug"))
chart.Histogram(idvSta_wo_zero, main = "Risk Measures", methods = c("add.risk"))
}
#############################################################################
#
#
# Combine all results from all strategies, prepare data for analysis.
#
#
#############################################################################
generate_BuyOnGap_result <- function(nStockTradeVec, strategy_tag)
{
nskip <- 0
yr_ShRate <- data.frame();
idx <- 0
for( yr in 2003:2012){
for(stdLookback in c(132, 66, 44, 22, 10, 5 )){
for(stdMultiple in c(0,0.5,0.7,1)){
for(nStocksBuy in c(1,2,4,5,8,10,20,40,60)){
nStocksBuy_full <- paste("BuyOnGap.",nStocksBuy,sep="");
cmd <- paste("(nStockTradeVec[[\'",nskip,"\']][[\'",stdLookback,
"\']][[\'",stdMultiple,"\']])[\'",yr,"\'][,\'",nStocksBuy_full,"\']",sep="");
print(cmd);
tradeVec <- eval(parse(text=cmd));
#ShpRate <- SharpeRatio.annualized(tradeVec);
result <- table.AnnualizedReturns(tradeVec)
AnnRet <- result[1,]
AnnSD <- result[2,]
AnnSR <- result[3,]
maxDD <- maxDrawdown(tradeVec);
RowName <- paste(nskip,"_",stdLookback,"_",stdMultiple,"_",nStocksBuy_full,"_",
strategy_tag,"_",yr,sep="");
dt <- data.frame(AnnRet,AnnSD,AnnSR, maxDD, nskip,stdLookback,
stdMultiple,nStocksBuy, yr, RowName, strategy_tag)
colnames(dt) <- c( 'AnnRet', 'AnnSD','AnnSR', 'MaxDD',
'nskip','stdLookback','stdMultiple','nStocksBuy','Year','long_name','strategy');
if(idx == 0){
yr_ShRate <- dt
idx <- idx + 1;
}else{
yr_ShRate <- rbind(yr_ShRate, dt);
}
}
}
}
# colnames(yr_ShRate) <- as.character(yr);
#SharpeRateList[[as.character(yr)]] <- yr_ShRate
}
return(yr_ShRate)
}
print_AnnualizedReturns <- function(nStockTradeVec)
{
for(yr in 2003:2012)
{
cat('YEAR ', yr,'\n');
print(round(table.AnnualizedReturns(
as.xts((nStockTradeVec[['0']][['132']][['0.5']]))[as.character(yr)]), digits=2))
}
}
print_maxDD <- function(nStockTradeVec)
{
for(yr in 2003:2012)
{
cat('YEAR ', yr,'\n');
print(round(maxDrawdown(
as.xts((nStockTradeVec[['0']][['132']][['0.5']]))[as.character(yr)]), digits=2))
}
}
print_daily_trade_Matrix <- function(conditionsMet, tradeMat, nStockTradeVec, month_yr)
{
buy_on_gap.numTradePerDay((conditionsMet[['0']][['132']][['0.5']])[month_yr],
(tradeMat[['0']][['132']][['0.5']])[month_yr],
(nStockTradeVec[['0']][['132']][['0.5']])[month_yr]);
}
#########################################################
# BuyOnGap
# number of trade per stock
#########################################################
buy_on_gap.numTradePerStock <- function(conditionsMet, TradeMat)
{
count <- apply(conditionsMet, 2, function(x) sum(x, na.rm=TRUE))
totalRet <- round(apply(TradeMat, 2, function(x) sum(x, na.rm=TRUE)), digits=3)
numPosTrade <- apply(TradeMat, 2, function(x) length(x[x>0]))
winRate <- round(numPosTrade/count , digits=2);
meanRet <- round(totalRet/count, digits=3);
meanRet <- ifelse(is.nan(meanRet), 0, meanRet)
e2 <- data.frame(gsub('.LowOpenRet','',names(count)), count, totalRet, meanRet, winRate, stringsAsFactors=FALSE)
colnames(e2) <- c('Symbol', 'Count', 'TotalRet', 'MeanRet', 'WinRate')
rownames(e2) <- NULL
numTrade <- e2[order(-e2$Count),]
return(numTrade)
}
#########################################################
# BuyOnGap
# number of trade per day
#########################################################
buy_on_gap.numTradePerDay <- function(conditionsMet, tradeMat, nStockTradeVec)
{
ff <- as.xts(apply(conditionsMet, 1, sum))
colnames(ff) <- 'numOfTrade'
f2 <- apply(conditionsMet, 1, function(x) paste(names(sort(which(x>0))), collapse=','))
names(f2) <- 'Stock';
numTradePerDay <- as.xts(data.frame(ff,f2, stringsAsFactors = FALSE));
# get_stock_return <- function(TradeMat, matched_sym, sym_date)
# {
# #sym_date <- index(matched_sym);
#
# sym_ret <- lapply(unlist(strsplit(matched_sym,',')),
# function(x) paste(round(TradeMat[sym_date][,x], digits=3), collapse=','));
#
# return(sym_ret);
# }
#f3 <- lapply(index(numTradePerDay$f2), function(x) get_stock_return(tradeMat, numTradePerDay$f2[x], x));
f3 <- vector();
for (i in 1:length(numTradePerDay[,1]))
{
sym_date <- index(numTradePerDay[i,]);
sym_ret <- sapply(unlist(strsplit(numTradePerDay[i,]$f2,',')),
function(x) round(tradeMat[as.character(sym_date)][,x] * 100, digits=1));
sym_ret <- paste(sym_ret, collapse=',');
f3 <- append(f3, sym_ret);
}
f3 <- as.data.frame(f3)
names(f3) <- 'Return';
f4 <- round(nStockTradeVec[,c(1:3)] * 100, digits=1);
f5 <- round(cumprod(nStockTradeVec[,c(1:3)] + 1), digits=2);
numTradePerDay <- data.frame(numTradePerDay,f3, f4, f5);
return(numTradePerDay)
}
sp400mid.components <- function()
{
library('XML');
# sp400 <- xmlToList('http://www.bowgett.com/Markets/SP400_Components.xml')
sp400 <- xmlToList('../data/finance/US/index/SP400_Components.xml', simplify =T)
sp400 <- unlist(sp400[1,])
sp400 <- gsub("/","-",sp400)
names(sp400) <- NULL
return(sp400)
}
sp500index.components <- function()
{
library('XML');
# sp500 <- xmlToList('http://www.bowgett.com/Markets/SP500_Components.xml')
sp500 <- xmlToList('../data/finance/US/index/SP500_Components.xml', simplify =T)
sp500 <- unlist(sp500[1,])
sp500 <- gsub("/","-",sp500)
# replace VIA-B with VIAB
sp500 <- gsub("VIA-B", "VIAB", sp500);
names(sp500) <- NULL
return(sp500)
}
sp600small.components <- function()
{
library('XML');
# sp600 <- xmlToList('http://www.bowgett.com/Markets/SP600_Components.xml')
sp600 <- xmlToList('../data/finance/US/index/SP600_Components.xml', simplify =T)
sp600 <- unlist(sp600[1,])
sp600 <- gsub("/","-",sp600)
names(sp600) <- NULL
return(sp600)
}
russell2000.components <- function()
{
r2k <- read.csv("../data/finance/US/index/russell2000_stock_list.csv",
blank.lines.skip=TRUE, header=FALSE, as.is=TRUE);
r2k <- unique(r2k[,1]);
return(r2k);
}
#############################################################################
# stock historical data selection and preparation.
#############################################################################
#############################################################################
# SP500 stock historical data
#############################################################################
make_sp500_stockData <- function()
{
set_local_symbol_lookup();
data <- new.env()
symbols = sp500index.components();
try(getSymbols(symbols, from = '1970-01-01', env = data, auto.assign = TRUE));
print(paste(symbols, collapse=' '))
print(paste('Number of stock : ', length(symbols), sep=''));
save(list = ls(data), file='../data/finance/stockData/SP500_stockData.Rdata', envir=data)
}
load_sp500_stockData <- function(stockData_envir)
{
load(file=paste0(cfg_stockData_path,'SP500_stockData.Rdata'), envir=stockData_envir)
}
#############################################################################
# Prepare SP400 MidCap stock historical data
#############################################################################
make_sp400_stockData <- function()
{
set_local_symbol_lookup();
data <- new.env()
symbols = sp400mid.components();
try(getSymbols(symbols, from = '1970-01-01', env = data, auto.assign = TRUE));
print(paste(symbols, collapse=' '))
print(paste('Number of stock : ', length(symbols), sep=''));
save(list = ls(data), file='../data/finance/stockData/SP400_stockData.Rdata', envir=data)
}
load_sp400_stockData <- function(stockData_envir)
{
load(file=paste0(cfg_stockData_path,'SP400_stockData.Rdata'), envir=stockData_envir)
}
#############################################################################
# Prepare SP600 SmallCap stock historical data
#############################################################################
make_sp600_stockData <- function()
{
set_local_symbol_lookup();
data <- new.env()
symbols = sp600small.components();
try(getSymbols(symbols, from = '1970-01-01', env = data, auto.assign = TRUE));
print(paste(symbols, collapse=' '))
print(paste('Number of stock : ', length(symbols), sep=''));
save(list = ls(data), file='../data/finance/stockData/SP600_stockData.Rdata', envir=data)
}
load_sp600_stockData <- function(stockData_envir)
{
load(file=paste0(cfg_stockData_path,'SP600_stockData.Rdata'), envir=stockData_envir)
}
#############################################################################
# Prepare Russell 2000 stock historical data
#############################################################################
make_russell2000_stockData <- function()
{
set_local_symbol_lookup();
data <- new.env()
sym = russell2000.components();
downloaded_sym <- list.files(path="../data/finance/US/price")
downloaded_sym <- toupper(gsub("\\.csv","",downloaded_sym))
# remove Symbol which not downloaded or failed to download
sym <- sym[sym %in% downloaded_sym]
try(getSymbols(sym, from = '1970-01-01', env = data, auto.assign = TRUE));
print(paste(sym, collapse=' '))
print(paste('Number of stock : ', length(sym), sep=''));
save(list = ls(data), file='../data/finance/stockData/Russell2000_stockData.Rdata', envir=data)
}
load_russell2000_stockData <- function(stockData_envir)
{
load(file=paste0(cfg_stockData_path,'Russell2000_stockData.Rdata'), envir=stockData_envir)
}
#############################################################################
# Prepare Russell 2000 stock historical data
#############################################################################
make_top100_etf_stockData <- function()
{
set_local_symbol_lookup();
data <- new.env()
sym = top100_etf.components();
downloaded_sym <- list.files(path="../data/finance/US/price")
downloaded_sym <- toupper(gsub("\\.csv","",downloaded_sym))
# remove Symbol which not downloaded or failed to download
sym <- sym[sym %in% downloaded_sym]
try(getSymbols(sym, from = '1970-01-01', env = data, auto.assign = TRUE));
print(paste(sym, collapse=' '))
print(paste('Number of stock : ', length(sym), sep=''));
save(list = ls(data), file='../data/finance/stockData/top100_etf_stockData.Rdata', envir=data)
}
load_top100_etf_stockData <- function(stockData_envir)
{
load(file=paste0(cfg_stockData_path,'top100_etf_stockData.Rdata'), envir=stockData_envir)
}
#############################################################################
# convert the time series back to Date class, after bt.prep
#############################################################################
convert_index_to_date <- function(data){
tmp <- sapply(ls(data), function(x) { if(is.xts(data[[x]])) { indexClass(data[[x]]) <- 'Date';}});
}
# opposite of adjustOHLC, adjust the price from "from" till the last date in the series
# back to the "unsplit" price as at "from" date. including dividend.
reverseAdj <-
function (x, from, ratio = NULL, symbol.name)
{
if(is.null(from))
{
from = as.Date(index(x[1,]));
}
if (is.null(ratio)) {
if (!has.Ad(x))
stop("no Adjusted column in 'x'")
ratio <- Ad(x)/Cl(x)
}
# get ratio on the last before from date
inverse_ratio = as.numeric(1/last(ratio[index(ratio) < as.Date(from),1]));
ratio <- ratio * inverse_ratio;
Adjusted <- Cl(x) * ratio
structure(cbind((ratio * (Op(x) - Cl(x)) + Adjusted),
(ratio * (Hi(x) - Cl(x)) + Adjusted),
(ratio * (Lo(x) - Cl(x)) + Adjusted),
Adjusted), .Dimnames = list(NULL, colnames(x)[1:4]))
}
##################################################################################
getNews_GoogleFinance <- function(symbol, number){
# Warn about length
if (number>300) {
warning("May only get 300 stories from google")
}
# load libraries
require(XML); require(plyr); require(stringr); require(lubridate);
require(xts);
# construct url to news feed rss and encode it correctly
url.b1 = 'http://www.google.com/finance/company_news?q='
url = paste(url.b1, symbol, '&output=rss', "&start=", 1,
"&num=", number, sep = '')
url = URLencode(url)
# parse xml tree, get item nodes, extract data and return data frame
doc = xmlTreeParse(url, useInternalNodes = TRUE)
nodes = getNodeSet(doc, "//item")
mydf = ldply(nodes, as.data.frame(xmlToList))
# clean up names of data frame
names(mydf) = str_replace_all(names(mydf), "value\\.", "")
# convert pubDate to date-time object and convert time zone
pubDate = strptime(mydf$pubDate,
format = '%a, %d %b %Y %H:%M:%S', tz = 'GMT')
pubDate = with_tz(pubDate, tz = 'America/New_york')
mydf$pubDate = NULL
#Parse the description field
mydf$description <- as.character(mydf$description)
parseDescription <- function(x) {
#out <- html2text(x)$text
doc2 = htmlParse(x, asText=TRUE)
plain.text <- xpathSApply(doc2, "//text()[not(ancestor::script)][not(ancestor::style)][not(ancestor::noscript)][not(ancestor::form)]", xmlValue)
out <- paste(plain.text, collapse = " ");
out <- strsplit(out,'\n|--')[[1]]
#Find Lead
TextLength <- sapply(out,nchar)
Lead <- out[TextLength==max(TextLength)]
#Find Site
Site <- out[3]
#Return cleaned fields
out <- c(Site,Lead)
names(out) <- c('Site','Lead')
out
}
description <- lapply(mydf$description,parseDescription)
description <- do.call(rbind,description)
mydf <- cbind(mydf,description)
#Format as XTS object
mydf = xts(mydf,order.by=pubDate)
# drop Extra attributes that we don't use yet
mydf$guid.text = mydf$guid..attrs = mydf$description = mydf$link = NULL
return(mydf)
}
getSymbols_par <- function(sym_list, stockEnv)
{
library(quantmod);
require(doMC);
registerDoMC(10);
from_date <- as.Date(trunc(Sys.time(),"days")) - 365; # 1 year
sym_data <- foreach(c_sym=sym_list) %dopar%
{
#try(Sys.sleep(abs(rnorm(1, mean = 0.5, sd =0.2))))
try(getSymbols(c_sym, from=from_date, src="yahoo", auto.assign=F))
}
for(i in 1:length(sym_data))
{
if(is.xts(sym_data[[i]]))
{
sym_name <- gsub(".Open","", names(sym_data[[i]])[1]);
eval(parse(text=paste("stockEnv$\'",sym_name,"\' <- sym_data[[i]]",sep="")));
}
}
registerDoMC();
}
# Most Popular ETFs: Top 100 ETFs By Trading Volume
# http://etfdb.com/compare/volume/
top100_etf.components <- function()
{
library(sit)
#url = 'http://etfdb.com/compare/volume/'
# download the page source from url above
url='../data/finance/US/index/top100_etf_volume.htm'
txt = join(readLines(url))
temp = extract.table.from.webpage(txt, 'Symbol', hasHeader = T)
tickers = temp[, 'Symbol']
return(tickers);
}
#############################################################################
# Function to calculate MTP (minimum total profit) for
# upperbound value, using AR(1) process to model spread
#############################################################################
pairs_perf_stat <- function(price.pair, signal)
{
p_daily_ret <- pairs_ret_rebalance(price.pair, signal)
p_tmp <- na.omit(p_daily_ret);
p_cum_ret <- (100* cumprod(1 + p_tmp));
if(NROW(p_daily_ret) > 1){
p_ret <- as.numeric(Return.annualized(p_daily_ret));
p_sharpe <- as.numeric(SharpeRatio.annualized(p_daily_ret));
} else {
p_ret <- NA; p_sharpe <- NA; }
res <- list(daily_ret = p_daily_ret, cum_ret=p_cum_ret, ret=p_ret,
sharpe = p_sharpe);
return(res);
}
# pairs_ret <- function(price.pair, signal, beta)
# {
# p_daily_ret <- lag(signal) *
# ( (1 / (1 + abs(beta)) * ROC(price.pair[,1])) - ( (beta / ( 1 + abs(beta))) * ROC(price.pair[,2]) ) );
#
# res <- as.numeric(Return.annualized(p_daily_ret));
# return(res);
# }
pairs_ret_rebalance <- function(price.pair, signal)
{
sig <- na.omit(lag(signal));
stock1_ret <- ROC(price.pair[,1], type='discrete');
stock2_ret <- ROC(price.pair[,2], type='discrete');
stock_ret <- merge(stock1_ret, -stock2_ret) * drop(sig);
weight <- sig;
weight[]<- NA;
for(i in 2:NROW(sig)){
if( (sig[i]!=0) &&
(as.numeric(sig[i-1]) != as.numeric(sig[i]))){
#rebalance at prev day
weight[i-1,] <- 0.5;
}
}
weight <- weight[(!is.na(weight[,1])),]
# # if the last row of weight is at the last 2 position of the stock_ret,
# # remove it. it will cause problem for Return.rebalancing.
# if(index(last(weight)) >= index(last(stock_ret, n=2)[1,]))
# {
# weight <- weight[1:(NROW(weight)-1),];
# }
if(NROW(weight)!=0){
weight <- merge(weight, weight)
colnames(weight) <- colnames(stock_ret);
ret <- Return.rebalancing_mod(stock_ret, weight, wealth.index=F, contribution = F);
return(ret$portfolio.returns);
} else {
return(stock_ret[,1]/2 + stock_ret[,2]/2);
}
}
# Return.portfolio and Return.rebalancing can't handle single row of return
Return.rebalancing_mod <- function (R, weights, ...)
{
if (is.vector(weights)) {
stop("Use Return.portfolio for single weighting vector. This function is for building portfolios over rebalancing periods.")
}
weights = checkData(weights, method = "xts")
R = checkData(R, method = "xts")
if (as.Date(first(index(R))) > (as.Date(index(weights[1,
])) + 1)) {
warning(paste("data series starts on", as.Date(first(index(R))),
", which is after the first rebalancing period",
as.Date(first(index(weights))) + 1))
}
if (as.Date(last(index(R))) < (as.Date(index(weights[1, ])) +
1)) {
stop(paste("last date in series", as.Date(last(index(R))),
"occurs before beginning of first rebalancing period",
as.Date(first(index(weights))) + 1))
}
for (row in 1:nrow(weights)) {
from = as.Date(index(weights[row, ])) + 1
if (row == nrow(weights)) {
to = as.Date(index(last(R)))
}
else {
to = as.Date(index(weights[(row + 1), ]))
}
if (row == 1) {
startingwealth = 1
}
tmpR <- R[paste(from, to, sep = "/"), ]
if (nrow(tmpR) >= 1) {
resultreturns = Return.portfolio_mod(tmpR, weights = weights[row,
], ... = ...)
if (row == 1) {
result = resultreturns
}
else {
result = rbind(result, resultreturns)
}
}
startingwealth = last(cumprod(1 + result) * startingwealth)
}
result <- reclass(result, R)
result
}
Return.portfolio_mod <- function (R, weights = NULL, wealth.index = FALSE, contribution = FALSE,
geometric = TRUE, ...)
{
R = checkData(R, method = "xts")
if (!nrow(R) >= 1) {
warning("no data passed for R(eturns)")
return(NULL)
}
if (hasArg(method) & !is.null(list(...)$method))
method = list(...)$method[1]
else if (!isTRUE(geometric))
method = "simple"
else method = FALSE
if (is.null(weights)) {
weights = t(rep(1/ncol(R), ncol(R)))
warning("weighting vector is null, calulating an equal weighted portfolio")
colnames(weights) <- colnames(R)
}
else {
weights = checkData(weights, method = "matrix")
}
if (nrow(weights) > 1) {
if ((nrow(weights) == ncol(R) | nrow(weights) == ncol(R[,
names(weights)])) & (ncol(weights) == 1)) {
weights = t(weights)
}
else {
stop("Use Return.rebalancing for multiple weighting periods. This function is for portfolios with a single set of weights.")
}
}
if (is.null(colnames(weights))) {
colnames(weights) <- colnames(R)
}
if (method == "simple") {
weightedreturns = R[, colnames(weights)] * as.vector(weights)
returns = R[, colnames(weights)] %*% as.vector(weights)
if (wealth.index) {
wealthindex = as.matrix(cumsum(returns), ncol = 1)
}
else {
result = returns
}
}
else {
wealthindex.assets = cumprod(1 + R[, colnames(weights)])
wealthindex.weighted = matrix(nrow = nrow(R), ncol = ncol(R[,
colnames(weights)]))
colnames(wealthindex.weighted) = colnames(wealthindex.assets)
rownames(wealthindex.weighted) = as.character(index(wealthindex.assets))
for (col in colnames(weights)) {
wealthindex.weighted[, col] = weights[, col] * wealthindex.assets[,
col]
}
wealthindex = as.xts(apply(wealthindex.weighted, 1, sum))
result = wealthindex
if(length(result) > 1){
result[2:length(result)] = result[2:length(result)]/lag(result)[2:length(result)] -
1 }
result[1] = result[1] - 1
w = matrix(rep(NA), ncol(wealthindex.assets) * nrow(wealthindex.assets),
ncol = ncol(wealthindex.assets), nrow = nrow(wealthindex.assets))
w[1, ] = weights
if(length(wealthindex) > 1){
w[2:length(wealthindex), ] = (wealthindex.weighted/rep(wealthindex,
ncol(wealthindex.weighted)))[1:(length(wealthindex) -
1), ] }
weightedreturns = R[, colnames(weights)] * w
}
if (!wealth.index) {
colnames(result) = "portfolio.returns"
}
else {
wealthindex = reclass(wealthindex, match.to = R)
result = wealthindex
colnames(result) = "portfolio.wealthindex"
}
if (contribution == TRUE) {
result = cbind(weightedreturns, coredata(result))
}
rownames(result) <- NULL
result <- reclass(result, R)
result
}
# The trade is open when the spread hit upperbound or lowerbound till
# spread crossing the zero. The spread is centered around mean.
gen_sig_trade_rule1 <- function(x , upperbound, lowerbound)
{