-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathalphaScripts_legacy.R
More file actions
executable file
·2355 lines (2061 loc) · 107 KB
/
Copy pathalphaScripts_legacy.R
File metadata and controls
executable file
·2355 lines (2061 loc) · 107 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
# Load generic libraries
library(xts)
library(xtsExtra)
library(TTR)
library(PerformanceAnalytics)
library(quantmod)
library(MASS)
library(quantstrat)
library(dynlm)
library(fArma)
library(caTools)
library(RTisean)
# Set the time-zone to GMT (UTC)
Sys.setenv(TZ="UTC")
# Show time-zone
Sys.timezone()
# Load ROneTick
library(ROneTick)
oneTickLib()
example(oneTickQueryOTQ)
setwd("c:/Devel/Models/trunk/R/alphaLib")
source("C:/Devel/Models/trunk/R/alphaLib/defaults.R")
# RobFilter
source("C:/Devel/Models/trunk/R/BetaFilters/Filt.Rob.Signal.R")
# Get object info
class(ts.data)
sapply(ts.data, class)
attributes(ts.data)
attributes(ts.data)$names
attributes(ts.data)$class
str(ts.data)
# Show all the methods associated with function 'mean'
methods("mean")
# Get sessionInfo
sessionInfo()
# Display installed packages
.packages(all=TRUE)
# Display currently loaded objects
objects()
# Display packages that have been loaded by library() or require()
search()
# Get info on all packages (produces a lot of stuff)
installed.packages()
# Another way to display installed packages
packinfo <- installed.packages(fields=c("Package", "Version"))
packinfo[,c("Package", "Version")]
packinfo["xts",c("Package", "Version")]
# Get package description
packageDescription('xts')
# Get timezone info
Sys.timezone()
Sys.setenv(TZ="GMT")
Sys.getenv("TZ")
#########################
### Load Lists of Symbols #
#########################
# Load using OTQ query
otq.get.symbols <- "S:/Software/Develop/OneTick/Get_symbols.otq"
field <- "SYMBOL_NAME"
symbols.top <- oneTickQueryOTQ(otq.get.symbols, FIELD=field, context='REMOTE')
# Load from .CSV file
file.symbols <- "S:/Data/R_Data/HY_Basket.csv"
file.symbols <- "S:/Data/R_Data/TOPTRND_Symbols_Short.csv"
file.symbols <- "S:/Data/R_Data/TOPTRND_Symbols.csv"
# Most liquid symbols less tranches
file.symbols <- "S:/Data/R_Data/TOPLTLQD_Symbols.csv"
# Most liquid less indices less tranches
file.symbols <- "S:/Data/R_Data/TOPLTLILQD_Symbols.csv"
file.symbols <- "S:/Data/R_Data/TRNCH_Symbols.csv"
# Read symbols as list
symbols.top <- read.csv(file.symbols, stringsAsFactors=FALSE)[,1]
# Read symbols as table
symbols.top <- read.table(file.symbols, header=TRUE, sep=",", as.is=TRUE)$CMATicker
names(symbols.top) <- symbols.top
symbols.some <- head(symbols.top)
file.symbols <- "S:/Data/R_Data/TOPNA_Symbols.csv"
symbols.na <- read.csv("S:/Data/R_Data/TOPNA_Symbols.csv", stringsAsFactors=FALSE)
# symbols.na <- read.table("S:/Data/R_Data/TOPNA_Symbols.csv", header=TRUE, sep=",", as.is=TRUE)
# symbols.top <- unlist(read.csv(file.symbols), use.names=FALSE)
# symbols.top <- as.vector(read.csv(file.symbols))
# Load symbols and aggnumbers from .CSV file
file.symbols <- "S:/Data/R_Data/TOPNAIG_Symbols.csv"
symbols.data <- read.csv(file.symbols, stringsAsFactors=FALSE)
symbols.top <- symbols.data$TICKER
agg.windows <- symbols.data$AGGWIN
##############################
### Load Single CDS Data ###
##############################
# OT query for loading regular ticks
otq.get.ticks <- "S:/Software/Develop/OneTick/Get_scrub_ticks.otq::Get_scrub_ticks"
symbol.cds <- "BZH"
# SPREAD_MID, CLEAN_UF_MID, DIRTY_UF_MID
field <- "CLEAN_UF_MID" # For TOPLT symbols
field <- "VALID_MID" # For TRNCH symbols
# Load prices from SCRUB database
ts.prices <- oneTickQueryOTQ(otq.get.ticks, SYMBOL=symbol.cds, FIELD=field, context='REMOTE')
colnames(ts.prices) <- symbol.cds
# Remove duplicate time stamps
ts.prices <- ts.prices[!duplicated(.index(ts.prices))]
#######################################
### Load Time Series Data From CSV ###
#######################################
raw.data <- read.table("C:/TEMP/XO17.csv", header=TRUE, sep=",", as.is=TRUE)
ts.prices <- xts(raw.data[,2], order.by=as.POSIXlt(raw.data[,1]))
# Load prices from CSV and remove NA's
ts.prices <- read.csv('C:/jerzy/Develop/Data/Stock ETFs.csv', stringsAsFactors=FALSE)
ts.prices <- xts(sapply(ts.prices[,-1], as.numeric), order.by=as.POSIXlt(ts.prices[,1]) )
ts.prices <- na.locf(ts.prices)
ts.prices <- na.locf(ts.prices,fromLast=TRUE)
dev.off()
plot.zoo(ts.prices, main=paste(c('Stock ETFs ', format(Sys.time(),'%m-%d-%y', tz="GMT"))))
### Load CDS price ticks using function call
# Load prices from ENRICHED database
ts.prices <- loadCDS(symbol.cds)
field <- "SPREAD_BID,SPREAD_OFFER"
ts.prices <- loadCDS(symbol.cds, field=field)
# Load prices within date-time period
ts.prices <- loadCDS(symbol.cds, start=20111001000000, end=20120901000000)
# Load aggregated prices within date-time period
ts.prices <- loadCDS(symbol.cds, bucket.interval="1", bucket.interval.units="DAYS", start=20110520093000, end=20120527163000)
# Load prices from ENRICHED database - change scrubbing parameter
ts.prices <- loadCDS(symbol.cds, bandWidth=0.7)
plot.xts(ts.prices, main=paste("Price ", symbol.cds), major.format="%b %y")
# Plotting using chart_Series() from package:quantmod
theme <- chart_theme()
theme$col$up.col <- 'lightgreen'
theme$col$up.border <- 'lightgreen'
theme$col$dn.col <- 'pink'
theme$col$dn.border <- 'pink'
# chart_Series(ts.prices, theme=theme, name=colnames(ts.prices))
chartPrice(ts.prices, theme)
# This doesn't work
plot(add_SMA(n=10, col=4, lwd=2))
# Load data and fix NAs
ts.prices.ig <- loadBbgIdx("CDX18", start=20120322110000, end=20120810210000) # Time is GMT
na.rows <- is.na(ts.prices.ig[,3])
ts.prices.ig[na.rows,3] <- (ts.prices.ig[na.rows,5] + ts.prices.ig[na.rows,6])/2
# Calculate overlapping rolling mean prices
agg.window <- 10
# ts.prices.mean <- na.omit(.Call("runSum", ts.prices, n=agg.window))/agg.window
ts.prices.mean <- runMean(ts.prices, n=agg.window)
ts.prices.mean[1:agg.window,] <- ts.prices.mean[agg.window,]
# Calculate non-overlapping rolling mean price (by=agg.window)
ts.prices.mean <- na.omit(apply.rolling(ts.prices, width=agg.window, by=agg.window, FUN="mean"))
# Set print area to two rows and one column
par(mfrow=c(2,1))
plot.xts(ts.prices, main=paste("Price ", symbol.cds), major.format="%b %y")
plot.xts(ts.prices.mean, main=paste("Price ", symbol.cds, " rolling mean"), major.format="%b %y")
# Calculate tick returns
# ts.rets <- na.omit(log(ts.prices/lag(ts.prices)))
ts.rets <- diff(ts.prices)
ts.rets[1,] <- ts.rets[2,]
plot.xts(cumsum(ts.rets), main=paste("Price ", symbol.cds), major.format="%b %y")
###################################
### Load Single Aggregated CDS Data #
###################################
# OT query for loading aggregated ticks
otq.get.ticks <- "S:/Software/Develop/OneTick/Get_scrub_ticks.otq::Agg_Median_Ticks"
# Load prices directly from OT server
ts.prices <- oneTickQueryOTQ(otq.get.ticks, SYMBOL=symbol.cds, BUCKET_INTERVAL="3600", BUCKET_INTERVAL_UNITS="SECONDS", FIELD=field, context='REMOTE')
# Load aggregated prices using function call
ts.prices <- loadCDS(symbol.cds, bucket.interval="3600", bucket.interval.units="SECONDS")
####################################
### Load and Join CDS and Index Data #
####################################
### Load the Index data
symbol.index <- "CDXHY17"
ts.prices.index <- oneTickQueryOTQ(otq.get.ticks, SYMBOL=symbol.index, FIELD=field, context='REMOTE')
colnames(ts.prices.index) <- symbol.index
plot.xts(ts.prices.index, main=paste("Price ",symbol.index), major.format="%b %y")
### Perform the join in two steps
# First perform outer join, apply locf, and return only second index column
ts.prices.join <- merge.xts(ts.prices, ts.prices.index, join='outer', retside=c(FALSE,TRUE), fill=na.locf)
# Second perform left join of expanded index onto CDS column
ts.prices.join <- na.omit(merge.xts(ts.prices, ts.prices.join, join='left'))
plot.zoo(ts.prices.join, main=paste("Price ", symbol.cds, " joined with ", symbol.index), major.format="%b %y")
grid(nx=30)
# Perform the join another way - almost the same
ts.prices.join <- na.locf(merge.xts(ts.prices, ts.prices.index, join='outer'))
ts.prices.join <- na.omit(ts.prices.join[index(ts.prices),])
ts.rets.join <- diff(ts.prices.join)
ts.rets.join[1,] <- na.omit(ts.rets.join)[1,]
### Load aggregated index price data from ENRICHED database (aggregation in OTQ)
ts.prices <- loadCDS(symbol="ITXXO17", bucket.interval="60", bucket.interval.units="SECONDS", start=20120401070000, end=20120901160000, field="SPREAD_MID", apply_times_daily=TRUE, context="412", tz='GMT')
### Load chained HY index price data
ts.prices.index <- loadIndex(symbol="CDXHY")
# Load aggregated Index prices
ts.prices.index <- loadIndex(symbol="CDXHY", bucket.interval="1", bucket.interval.units="DAYS")
ts.prices.index <- loadIndex(symbol="ITXXO", roll.current=17, bucket.interval="1", bucket.interval.units="DAYS")
plot.xts(ts.prices.index, main=paste(colnames(ts.prices.index), " chained"), major.format="%b %y")
### Load chained IG index price data
ts.prices.ig.index <- loadIndex(symbol="CDX")
ts.rets.index <- diff(ts.prices.index)
ts.rets.index[1,] <- na.omit(ts.rets.index)[1,]
### Outer join HY with IG index price data
ts.index <- na.omit(merge.xts(ts.prices.index, ts.prices.ig.index, join='outer', fill=na.locf))
plot.zoo(ts.index)
### Load CDS price ticks and join them with Index price ticks (join is performed in R)
ts.prices.join <- loadCDSIndexJoin(symbol.cds, ts.index, otq.get.ticks=otq.get.ticks, field=field)
# Join CDS price data with index
ts.prices.join <- joinCDSIndex(ts.prices, ts.index)
### Load multiple CDS data joined in OT
otq.get.join.ticks <- "S:/Software/Develop/OneTick/Get_scrub_ticks.otq::Get_Joined_Median_Ticks"
ts.prices.index <- oneTickQueryOTQ(otq.get.join.ticks, SYMBOLCDS=symbol.cds, SYMBOLINDEX=symbol.index, FIELD=field, context='REMOTE')
### Load aggregated CDS price ticks joined with Index (join is performed in OT)
# No aggregation
ts.prices.join <- loadCDSIndex(symbol.cds, symbol.index)
ts.prices.join <- loadCDSIndex(symbol=symbols.cds, symbol.index="CDXHY18", field="VALID_MID,VALID_BID_OFFER")
# With aggregation
ts.prices.join <- loadCDSIndex(symbol.cds, symbol.index, bucket.interval="3600", bucket.interval.units="SECONDS")
# Chained index
ts.prices.join <- loadCDSIndexChained(symbol.cds, symbol.index="CDXHY")
ts.prices.join <- loadCDSIndexChained(symbol.cds, symbol.index="CDXHY", bucket.interval="3600", bucket.interval.units="SECONDS")
ts.rets.join <- diff(ts.prices.join)
ts.rets.join[1,] <- na.omit(ts.rets.join)[1,]
###############################################################
### Load Aggregated Tranche Prices and Join with REF Index ###
###############################################################
symbol.cds <- "CDXHY10-15-25"
symbol.cds <- paste('CDX9-', c('0-3','3-7','7-10','10-15','15-30','30-100'), sep='')
ts.tranche <- loadCDS(symbol.cds, TERM=7, bucket.interval="1", bucket.interval.units="DAYS")
symbol.cds <- "CDX9"
ts.spread <- loadCDS(symbol.cds, field="SPREAD_MID", TERM=7, bucket.interval="1", bucket.interval.units="DAYS")
ts.join <- na.locf(cbind(ts.tranche, 2.0*ts.spread/100))
ts.join <- ts.join[,1] - 3.4*ts.join[,3]
plot(ts.join["2012-02-01/"])
# Insert term.string into colnamev
colnames(ts.tranche.prices)) <- apply(matrix(colnames(ts.tranche.prices)), 1, function(col.name, term.string) {
col.string <- strsplit(col.name, '.', fixed=TRUE)[[1]]
paste(c(col.string[1], term.string, col.string[-1]), collapse=".")
}, term.string='7yr')
#####################################################################
### Load HY index replicating basket and regress against HY index ###
#####################################################################
file.symbols <- "S:/Data/R_Data/HY_Basket_Feb2012.csv"
ts.prices <- loadTickers(file.symbols, bucket.interval="1", bucket.interval.units="DAYS", field="VALID_MID", start=20111001000000, end=20120901000000)
plot.zoo(ts.prices)
grid(nx=30)
ts.prices <- xts(rowMeans(ts.prices),order.by=index(ts.prices))
plot.xts(ts.prices, main=paste("Price basket.hy"), major.format="%b %y")
ts.rets <- diff(ts.prices)
ts.rets[1,] <- na.omit(ts.rets)[1,]
pacf(ts.rets, lag=30, xlab="Lag ticks", main=paste("PACF basket.hy"))
Box.test(ts.rets, type="Ljung")
ts.prices.index <- loadIndex(symbol="CDXHY", bucket.interval="1", bucket.interval.units="DAYS")
ts.rets.index <- diff(ts.prices.index)
ts.rets.index[1,] <- na.omit(ts.rets.index)[1,]
ts.prices <- cbind.xts(ts.prices,ts.prices.index)
ts.prices <- na.omit(ts.prices)
colnames(ts.prices) <- c("basket.hy","CDXHY")
plot.zoo(ts.prices)
ts.rets <- diff(ts.prices)
ts.rets[1,] <- na.omit(ts.rets)[1,]
lmBetas <- lm(ts.rets[,1] ~ ts.rets[,2])
plot.xts(cumsum(lmBetas$residuals), main=paste("Price basket.hy"), major.format="%b %y")
pacf(lmBetas$residuals, lag=30, xlab="Lag ticks", main=paste("PACF basket.hy"))
####################
### Data Loading #
####################
sink("S:/Data/R_Data/Beta_analysis.csv")
# Define query parameters
OTQDir <- "../../OneTick/"
init.query <- paste(OTQDir, "Scrub_Ticks.otq::Get_Sane_Ticks_Priming",sep='')
main.query <- paste(OTQDir, "Join_Agg_Ticks.otq::Single_Median",sep='')
start.date <- '20121110000000'
# end.date <- '20130304000000'
end.date <- paste(format(Sys.time(),'%Y%m%d', tz="GMT"),'000000',sep='')
start.time <- '073000000'
end.time <- '163000000'
end.morning.time <- '103000000'
symbol.date <- '20130101'
term.query <- 5
bid.query <- 'PAR_SPREAD_BID'
offer.query <- 'PAR_SPREAD_OFFER'
# bid.query <- 'UPF_BID'
# offer.query <- 'UPF_OFFER'
# bid.query <- 'SPREAD_BID'
# offer.query <- 'SPREAD_OFFER'
context.query <- '412'
symbology.query <- 'CMATICKER'
# symbology.query <- 'CMAID'
db.query <- 'CDS_CMA_INTRADAY_E'
time.zone <- 'America/New_York'
# time.zone <- 'Europe/London'
calendar.query <- 'US_FED'
# calendar.query <- 'GB_CAL'
deal.type <- 'Senior'
# deal.type <- 'Subordinated' # for ITXSUBF
symbols.table <- symbols.data
### Load Median CDS quotes for a list of symbols
list.prices <- lapply(1:nrow(symbols.table), function(n.row)
{
# Load median ticks for initializing scrubber
symbol <- symbols.table$CMATicker[n.row]
time.zone <- symbols.table$TimeZone[n.row]
calendar.query <- symbols.table$Calendar[n.row]
symbology.query <- symbols.table$Symbology[n.row]
deal.type <- symbols.table$DealType[n.row]
write(symbol, stdout())
init.ticks <- tryCatch(oneTickQueryOTQ(init.query,
start=start.date, end=end.date,
DELAY_TIMESTAMP=30000,
SYMBOL=symbol,
PRIME_TICKS=10,
DAYS=100,
START_TIME=start.time,
END_TIME=end.time,
BID_SCRUB=bid.query,
OFFER_SCRUB=offer.query,
SYMBOLOGY=symbology.query,
DEALTYPE=deal.type,
CALENDAR=calendar.query,
SDATE=symbol.date,
TERM=term.query,
MAX=10000,
MIN=-10000,
DB=db.query,
TZ=time.zone,
running_query=FALSE,
apply_times_daily=FALSE,
context=context.query),
error=function(e) writeMessage(paste(symbol, e)), warning=function(w) writeMessage(w))
# Extract init.ticks
if(is.null(init.ticks)){
write('Query to retrieive init values failed. Using default.', stdout())
}else{
init.mid <<- as.numeric(first(init.ticks$MID))
init.bo <<- as.numeric(first(init.ticks$BO))
write(paste('Priming MID value', init.mid, sep=' '), stdout())
write(paste('Priming BO value', init.bo, sep=' '), stdout())
}
# Load median ticks
ts.ticks <- tryCatch(oneTickQueryOTQ(main.query,
start=start.date, end=end.date,
START_TIME=start.time,
END_TIME=end.morning.time,
BUCKET_INTERVAL_UNITS='DAYS',
BUCKET_INTERVAL=1,
SYMBOL=symbol,
OFFER_SCRUB=offer.query,
BID_SCRUB=bid.query,
SYMBOLOGY=symbology.query,
DEALTYPE=deal.type,
DB=db.query,
INIT_MID=init.mid,
INIT_BO=init.bo,
CALENDAR=calendar.query,
SDATE=symbol.date,
TERM=term.query,
TZ=time.zone,
context=context.query),
error=function(e) writeMessage(paste(symbol, e)), warning=function(w) writeMessage(w))
ts.ticks <- ts.ticks[,'MEDIAN']
colnames(ts.ticks) <- symbol
ts.ticks
}
)
# End lapply
### Load CMA DATAVISION CDS quotes
query.datavision <- paste(OTQDir, "Join_Agg_Ticks.otq::EOD_History",sep='')
list.prices <- apply(matrix(1:nrow(symbols.data)), 1, function(n.row)
{
ts.ticks <- oneTickQueryOTQ(query.datavision,
start=start.date, end=end.date,
SYMBOLOGY='CMAID',
DB='CDS_CMA_HISTORY',
SYMBOL=symbols.data[n.row,'CMAID'],
TENOR=term.query,
context=context.query)
ts.ticks <- ts.ticks[,c(-2,-3)]
colnames(ts.ticks) <- symbols.data[n.row,'CMATicker']
ts.ticks <- xts(coredata(ts.ticks), order.by=as.Date(trunc(index(ts.ticks), units='days')))
ts.ticks
}
)
# End lapply
# cbind into a single xts
ts.prices <- do.call('cbind', list.prices)
# Remove duplicate dates (produced by cbind)
# indeks <- c(1,diff(.index(ts.prices)))
# indeks <- which(indeks>0)
# ts.prices <- ts.prices[indeks,]
# Scrub the data
ts.prices <- xts(apply(ts.prices, 2, function(ts.tmp)
{
# Get rid of zero prices
ts.tmp[which(ts.tmp==0)] <- NA
# Get rid of NAs created by cbind
ts.tmp[1] <- na.omit(ts.tmp)[1]
ts.tmp <- na.locf(ts.tmp)
# Get rid of price spikes
diff.tmp.1 <- abs(c(ts.tmp[1],diff(ts.tmp)))
diff.tmp.2 <- abs(c(ts.tmp[1:2],diff(ts.tmp,2)))
diff.tmp.2 <- c(head(diff.tmp.2,1),head(diff.tmp.2,-1))
l.spikes <- which(diff.tmp.1>5*diff.tmp.2)
ts.tmp[l.spikes] <- (c(head(ts.tmp,1),head(ts.tmp,-1))[l.spikes]+c(tail(ts.tmp,-1),tail(ts.tmp,1))[l.spikes])/2
ts.tmp
}
), order.by=index(ts.prices))
# Daily aggregation will cause timestamp to be shifted one day ahead - shift back one day, and truncate dates to midnight
index(ts.prices) <- as.Date(index(ts.prices)-1)
index(ts.prices) <- as.Date(trunc(index(ts.prices), units='days'))
# Check for duplicate dates
which(diff(.index(ts.prices))==0)
# Check for NAs
sum(is.na((ts.prices)))
# Explore and manipulate
# Plot
plot.zoo(ts.prices[,symbols.some$CMATicker], main='CDS')
chart_Series(ts.prices[,'MS'], name="MS")
# str.headers <- paste(symbols.some,'MEDIAN',sep=".")
deal.type <- 'Senior'
deal.type <- 'Subordinated' # for ITXSUBF
time.zone <- 'Europe/London'
calendar.query <- 'GB_CAL'
### Load Index quotes
main.query <- paste(OTQDir, "Join_Agg_Ticks.otq::Single_Median",sep='')
ts.prices.ig <- oneTickQueryOTQ(main.query,
start=start.date, end=end.date,
START_TIME=start.time,
END_TIME=end.morning.time,
BUCKET_INTERVAL_UNITS='DAYS',
BUCKET_INTERVAL=1,
SYMBOL='IG',
BID_SCRUB=bid.query,
OFFER_SCRUB=offer.query,
DEALTYPE=deal.type,
SYMBOLOGY='CMAID',
DB=db.query,
CALENDAR=calendar.query,
SDATE=symbol.date,
TERM=term.query,
TZ=time.zone,
context=context.query)
# Daily aggregation will cause timestamp to be shifted one day ahead - shift back one day
index(ts.prices.ig) <- as.Date(index(ts.prices.ig)-86400) # 86400 is seconds in a single day
# Alternative way to do the same
index(ts.prices.ig) <- as.Date(index(ts.prices.ig)-1)
index(ts.prices.ig) <- as.Date(trunc(index(ts.prices.ig), units='days'))
# Rename columns and combine IG and CDS data
# colnames(ts.prices.ig) <- paste("IG",colnames(ts.prices.ig),sep=".")
index(ts.prices.ig) <- index(ts.prices.ig)
index(ts.prices) <- index(ts.prices)
ts.prices <- cbind(ts.prices.ig[,'MEDIAN'],ts.prices)
colnames(ts.prices)[1] <- 'IG'
# Check for NAs
sum(is.na(ts.prices))
which(is.na(ts.prices))
ts.prices[,1] <- na.locf(ts.prices[,1])
save(ts.prices, file="S:/Data/R_Data/data_topglob.RData")
symbols.comb <- c("IG",symbols.top)
str.headers <- paste(symbols.comb,'MEDIAN',sep=".")
ts.prices.med <- ts.prices[,str.headers]
colnames(ts.prices.med) <- sub('.MEDIAN','',colnames(ts.prices.med))
chart_Series(ts.prices.med[,'JCP'], name="JCP")
ts.rets.med <- diff(ts.prices.med)
ts.rets.med[1,] <- ts.rets.med[2,]
# Calculate percentage returns
ts.lrets <- diff(log(ts.prices))
ts.lrets[1,] <- ts.lrets[2,]
index(ts.lrets) <- index(ts.lrets)
# Calculate rolling mean returns
agg.param <- 2
ts.rets.mean <- apply(ts.lrets[,symbols.some], 2, runMean, n=agg.param)
ts.rets.mean <- xts(ts.rets.mean, order.by=index(ts.lrets))
ts.rets.mean[1:agg.param,] <- ts.rets.mean[agg.param,]
index(ts.rets.mean) <- index(ts.rets.mean)
# Combine IG and Top NA CDS data
ts.rets.top <- cbind(ts.rets.ig[,'IG'],ts.rets[,symbols.na$CMATicker[1:165]])
colnames(ts.rets.top)[1] <- 'IG'
# Remove NAs from IG data
ts.rets.top[which(is.na(ts.rets.top[,1])),] <- 0.0
# Reformat the xts of ts.rets.top
names.top <- colnames(ts.rets.top)
ts.rets.top <- xts(matrix(as.vector(ts.rets.top), ncol=ncol(ts.rets.top)), order.by=index(ts.rets.top))
colnames(ts.rets.top) <- names.top
# A simpler way to do the same
index(ts.rets.top) <- index(ts.rets.top)
########################
### Generate Random xts #
########################
ts.random <- cumsum(sign(runif(nrow(ts.prices))-0.5))
ts.random <- cumsum(rnorm(nrow(ts.prices)))
ts.random <- xts(ts.random, order.by=index(ts.prices))
colnames(ts.random) <- "ts.random"
# Univariate random walk time series
ts.random <- cumsum(xts(rnorm(nrow(ts.prices)), order.by=index(ts.prices)))
colnames(ts.random) <- 'rand'
# Bivariate independent random walk time series
ts.random <- cumsum(xts(cbind(rnorm(nrow(ts.prices)),rnorm(nrow(ts.prices))), order.by=index(ts.prices)))
# Bivariate cointegrated random walk with random residual
ts.random <- cumsum(rnorm(nrow(ts.prices)))
ts.random <- xts(cbind(ts.random,ts.random+rnorm(nrow(ts.prices))), order.by=index(ts.prices))
# Bivariate cointegrated random walk with ARIMA residual
ts.random <- cumsum(rnorm(nrow(ts.prices)))
ts.random <- xts(cbind(ts.random,ts.random+arima.sim(n=nrow(ts.prices), model=list(ar=0.05*(1:4)))), order.by=index(ts.prices))
colnames(ts.random) <- c('rand1','rand2')
plot.xts(ts.random, main=paste("Price", colnames(ts.random)), major.format="%b %y")
ts.random.ret <- diff(ts.random)
ts.random.ret[1,] <- na.omit(ts.random.ret)[1,]
#########################
### Data Exploration ###
#########################
ts.rets <- diff(ts.ighyes.10min[,'IG'])
ts.rets[1,] <- ts.rets[2,]
hist(ts.rets, prob=T, ylim=c(0,2.3), xlim=c(-3,3), col="red")
lines(density(ts.rets),lwd=2)
plot(density(ts.rets),lwd=2,xlim=c(-2,2))
qqnorm(ts.rets,main=paste("Q-Q plot of ",colnames(ts.rets)))
ks.test(ts.rets,"pnorm",mean(ts.rets),sd(ts.rets))
shapiro.test(coredata(last(ts.rets,4999)))
### Plot in loop over a list of symbols, and prompt before plotting
# Get symbols with biggest differences
f.sums <- colSums(ts.prices-ts.prices.old, na.rm=TRUE)
f.sums <- f.sums[order(abs(f.sums), decreasing=TRUE)]
symbols.top <- names(head(f.sums,22))
par(ask=TRUE)
apply(matrix(head(symbols.top,22)), 1, function(n.symbol)
{
## f.diff <- sum(ts.prices[,n.symbol]-ts.prices.old[,n.symbol])
## plot.zoo(cbind(ts.prices[,n.symbol], ts.prices.old[,n.symbol]), main=paste(n.symbol, '=', f.diff))
# Filter the returns first
ts.data <- ts.lrets['2013-02-03/',n.symbol]
filter.kalman <- dlmFilter(y=ts.data, mod=dlm.poly)
ts.filter.lrets <- xts(filter.kalman$m[-1,1], order.by=index(ts.data))
colnames(ts.filter.lrets) <- paste(n.symbol, 'filtered.rets')
# Filter the prices
ts.data <- ts.prices['2013-02-03/',n.symbol]
filter.kalman <- dlmFilter(y=ts.data, mod=dlm.poly)
ts.filter.prices <- xts(filter.kalman$m[-1,1], order.by=index(ts.data))
colnames(ts.filter.prices) <- paste(n.symbol, 'filtered.prices')
# Plot
chart.TimeSeries(cbind(ts.data,ts.filter.prices), main=paste(n.symbol, 'Prices and Kalman filtered prices'), colorset=c(1,2), lty=c(1,1), ylab="", xlab="", legend.loc='topright')
plot.zoo(cbind(ts.data,ts.filter.prices,ts.filter.lrets), main=paste(n.symbol, 'Prices and Kalman filtered prices'), colorset=c(1,2,3), lty=c(1,1,1), ylab="", xlab="", legend.loc='topright')
# chart.TimeSeries(ts.prices['2012-11-03/',n.symbol], main=n.symbol, colorset=1, lty=1, ylab="", xlab="")
n.symbol
}
)
# End lapply
par(ask=FALSE)
######################
### Statistical Tests #
######################
# Shapiro-Wilk Normality test
shapiro.test(as.vector(head(ts.rets,4999)))
qqnorm(ts.rets,main=paste("Q-Q plot of ",symbol.cds))
# Scatterplots of lagged returns
lag.plot(ts.rets,4,main=paste("Lag plots of ",symbol.cds))
### Autocorrelation tests
### Ljung-Box to test for autocorrelations different from zero
# 'lag' is the number of autocorrelation coefficients
LjBox <- Box.test(ts.rets, lag=10, type="Ljung")
LjBox$statistic
LjBox$p.value
### Durbin-Watson test for first order autocorrelations of regression residuals
lmBetas <- lm(ts.rets[,1] ~ ts.rets[,2] + ts.rets[,3])
# From package lmtest
library(lmtest)
dwtest(lmBetas)
# From package car
library(car)
durbinWatsonTest(lmBetas)
### Augmented Dickey-Fuller test (null is that ts has a unit root)
# 'k' is the number of autocorrelation terms
library(tseries)
adf.test(rnorm(1000),k=5)
adf.test(cumsum(rnorm(1000)))
adf.test(as.vector(ts.random))
# Calculate spectral density using AR fit
spec.ar(ts.retsPair,log='no')
spec.pgram(ts.retsPair,log='no')
# Calculate multi-variate lagged cross-correlations
ccf(as.vector(ts.rets[,1]),as.vector(ts.rets[,2]), lag.max=10, type="correlation", plot=TRUE)
####################
### Data Analysis #
####################
# Plot IG prices time series and filtered data points
ig.filtered <- xts(filter(as.vector(ts.prices[,'IG']), rep(0.05,20)), order.by=index(ts.prices))
ig.filtered[1] <- na.omit(ig.filtered)[1]
ig.filtered <- na.locf(ig.filtered)
# ig.filtered[which(is.na(ig.filtered))] <- 0.0
colnames(ig.filtered) <- 'IG.FILTERED'
plot.xts(ts.prices[,'IG'], xlab='', ylab='', main='IG', type='l')
par(new=TRUE)
lines(ig.filtered, col='red', lwd=3)
### Calculate variance ratios for a list of time scales
time.scales <- matrix(10:200)
var.ratios <- cbind(time.scales, matrix(apply(time.scales, 1, var.ratio, ts.rets=ts.rets, agg.min=2)))
colnames(var.ratios) <- c('time.scales','var.ratios')
### Calculate variance ratios for a list of symbols
var.ratios <- as.matrix(apply(ts.rets, 2, var.ratio, agg.min=1, agg.max=5) )
# Sort the symbols by highest variance ratios
var.ratios <- as.matrix(var.ratios[order(var.ratios, decreasing=TRUE),1])
colnames(var.ratios) <- 'Var.Ratios'
write.csv(var.ratios, "S:/Data/R_Data/data.var.ratios.csv")
barplot(as.vector(var.ratios[1:22,]), names.arg=rownames(var.ratios)[1:22], las=3, ylab="Var.ratios", xlab="TS", main="Var.ratio scores")
# Select the top symbols
length.ratios <- length(var.ratios)
var.ratios.top <- var.ratios[trunc(0.75*length.ratios):length.ratios]
# Select prices for the top symbols with highest var.ratios
ts.prices.top <- ts.prices[,names(var.ratios.top)]
# Remove RESCAP from top symbols
ts.prices.top <- ts.prices.top[,colnames(ts.prices.top)!='RESCAP']
### Calculate spectrum scores for a list of symbols
data.spec <- as.matrix(apply(ts.rets, 2, function(ts.ret) tryCatch(spectral.frac(ts.ret), error=function(e) writeMessage(e)) ))
# Sort
data.spec <- as.matrix(data.spec[order(data.spec, decreasing=TRUE),1])
colnames(data.spec) <- 'Spectrum.Scores'
#colnames(data.spec) <- c('CMATicker','Spectrum.Energyfrac')
barplot(as.vector(data.spec[1:22,]), names.arg=rownames(data.spec)[1:22], las=3, ylab="Spec.ratios", xlab="TS", main="Spec.ratio scores")
write.csv(data.spec, "S:/Data/R_Data/data.spec.csv")
# Plot scatterplot
plot(x=var.ratios, y=data.spec, xlab=colnames(var.ratios), ylab=colnames(data.spec), main='Scores')
# Add reg line
data.lm <- lm(data.spec ~ var.ratios)
abline(data.lm)
summary(data.lm)
# Add labels
text(x=var.ratios, y=data.spec, labels=rownames(var.ratios), cex= 0.7, pos=2)
# Add labels by clicking
identify(var.ratios, data.spec, labels=rownames(var.ratios), cex = 0.7)
# Plot scatterplot with wordcloud labels to prevent label overlaps
library(wordcloud)
library(tm)
wordcloud::textplot(x=var.ratios, y=data.spec, words=rownames(var.ratios), xlab=colnames(var.ratios), ylab=colnames(data.spec), main='Scores', cex= 0.7, xlim=c(min(var.ratios),max(var.ratios)), ylim=c(min(data.spec),max(data.spec)))
# Calculate spectrum scores for a list of ARIMA processes (autocorrelation parameters)
length.ar <- nrow(ts.rets)
coeffs.ar <- as.matrix(0.1*(1:9))
data.ar <- apply(coeffs.ar, 1, function(coeff.ar) spectral.frac(arima.sim(n=length.ar, model=list(ar=coeff.ar))) )
data.ar <- cbind(coeffs.ar,data.ar)
colnames(data.ar) <- c('AR coeffs','Spectrum.Scores')
### Calculate Omega scores for some symbols
# Omega score of zero means not forecastable (white noise); 100 score means perfectly forecastable (a sinusoid).
library(ForeCA)
Omega(ts.rets[,'NOKIA'])
data.omega <- t(as.matrix(Omega(ts.rets, spectrum_method="wosa")))
colnames(data.omega) <- 'Omega.Scores'
# Calculate omega scores for a list of symbols
data.omega <- apply(ts.rets, 2, function(ts.ret,...) tryCatch(Omega(ts.ret,...), error=function(e) writeMessage(e)), spectrum_method="multitaper")
data.omega <- as.matrix(data.omega)
data.omega <- data.omega[order(data.omega, decreasing=TRUE),1]
data.omega <- as.matrix(data.omega)
colnames(data.omega) <- 'Omega.Scores'
write.csv(data.omega, "C:/Data/data.omega.csv")
barplot(as.vector(data.omega[1:22,]), names.arg=rownames(data.omega)[1:22], las=3, ylab="Omega", xlab="TS", main="Omega scores")
plot.zoo(ts.prices[,rownames(head(data.omega,11))])
# Scatterplot omega scores for a list of ts
plot(omega.wosa, omega.multitaper, ylab="multitaper", xlab="wosa", main='Omega scores')
# Calculate omega scores for sine wave plus random ts
data.omega <- as.matrix(apply(matrix(0.1*(1:10)), 1, function(rand.param,...) tryCatch(Omega(rand.param*sin(20*(1:nrow(ts.prices))/nrow(ts.prices)) + rnorm(nrow(ts.prices)),...), error=function(e) writeMessage(e)), spectrum_method="wosa"))
colnames(data.omega) <- 'Omega.Scores'
# Calculate rolling variance scores for multiple ts
agg.min <- 2
agg.max <- 10
ts.var.ratios <- as.matrix(apply(ts.rets, 2, function(ts.ret) {
ts.ratios <- apply.rolling(ts.ret, width=look.back, FUN="var.ratio", agg.min=agg.min, agg.max=agg.max)
ts.ratios[1:(look.back-1),] <- ts.ratios[look.back,]
ts.ratios
} ))
ts.var.ratios <- xts(ts.var.ratios, order.by=index(ts.rets))
colnames(ts.var.ratios) <- colnames(ts.rets)
plot.zoo(ts.var.ratios, main=paste(c('var.ratios ',format(Sys.time(),'%m-%d-%y',tz="UTC"))), xlab="")
# Calculate efficiently rolling variance scores for multiple ts
# This actually gives slightly different result - as it should
ts.var.ratios <- as.matrix(apply(ts.rets, 2, function(ts.ret) {
var.agg.min <- runMean(ts.ret,n=agg.min)
var.agg.min[1:(agg.min-1)] <- var.agg.min[agg.min]
var.agg.min <- runSD(var.agg.min,n=look.back)
var.agg.max <- runMean(ts.ret,n=agg.max)
var.agg.max[1:(agg.max-1)] <- var.agg.max[agg.max]
var.agg.max <- runSD(var.agg.max,n=look.back)
ts.ratios <- (var.agg.max/var.agg.min)*(agg.min/agg.max)/2
ts.ratios[1:(look.back-1)] <- ts.ratios[look.back]
ts.ratios
} ))
ts.var.ratios <- xts(ts.var.ratios, order.by=index(ts.rets))
colnames(ts.var.ratios) <- colnames(ts.rets)
plot.zoo(ts.var.ratios, main=paste(c('var.ratios ',format(Sys.time(),'%m-%d-%y',tz="UTC"))), xlab="")
### Calculate regression credit betas for a list of symbols
# Prepare cumulated returns data
cum.rets <- apply(ts.rets, 2, function(rets)
{
rets <- .Call("runSum", rets, 2)
rets[1] <- na.omit(rets)[1]
rets <- na.locf(rets)
}
)
cum.rets <- xts(cum.rets, order.by=index(ts.rets))
profile.beta <- sapply(colnames(ts.rets)[-1],
function(colname)
{
# formula.lm <- as.formula(paste(colname,"~",'IG',sep=" "))
formula.lm <- as.formula(paste('IG',"~",colname,sep=" "))
lm.ig <- lm(formula.lm, data=cum.rets)
c(lm.beta=summary(lm.ig)$coefficients[2,1],lm.error=summary(lm.ig)$coefficients[2,2],lm.t.value=summary(lm.ig)$coefficients[2,3],lm.r.squared=summary(lm.ig)$r.squared)
}
)
# End sapply
profile.beta <- t(profile.beta)
# Sort the list according to highest regression r.squared
profile.beta <- profile.beta[order(profile.beta[,'lm.r.squared'], decreasing=TRUE),]
# Sort the list according to highest regression t.value
profile.beta <- profile.beta[order(profile.beta[,'lm.t.value'], decreasing=TRUE),]
# Create scatterplot of t.value versus r.squared
plot(lm.t.value~lm.r.squared, data=profile.beta)
### Perform pair-wise correlation analysis
# Calculate correlation matrix
corr.matrix <- cor(ts.rets)
colnames(corr.matrix) <- colnames(ts.rets)
rownames(corr.matrix) <- colnames(ts.rets)
# Reorder the correlation matrix based on clusters
# Calculate permutation vector
library(corrplot)
corr.order <- corrMatOrder(corr.matrix, order="hclust", hclust.method="complete")
# Apply permutation vector
corr.matrix.ordered <- corr.matrix[corr.order,corr.order]
# Plot the correlation matrix
col3 <- colorRampPalette(c("red", "white", "blue"))
corrplot(corr.matrix.ordered, tl.col="black", tl.cex=0.8, method="square", col=col3(8), cl.offset=0.75, cl.cex=0.7, cl.align.text="l", cl.ratio=0.25)
# Draw rectangles on the correlation matrix plot
corrRect.hclust(corr.matrix.ordered, k=13, method="complete", col="red")
# Perform hierarchical clustering analysis
data.dist <- as.dist(1-corr.matrix.ordered)
data.cluster <- hclust(data.dist)
plot(data.cluster, main="Dissimilarity = 1-Correlation", xlab="")
### Perform principal component analysis PCA
data.pca <- prcomp(ts.rets, center=TRUE, scale=TRUE)
data.pca <- prcomp(ts.rets[,symbols.data$CMATicker], center=TRUE, scale=TRUE)
plot(data.pca)
barplot(data.pca$sdev[1:10], names.arg=colnames(data.pca$rotation)[1:10], las=3, ylab="STDEV", xlab="PCVec", main="PCA Explain VAR")
var.pca <- sum(data.pca$sdev^2)
barplot(data.pca$sdev^2/var.pca, names.arg=colnames(data.pca$rotation), las=3, ylab="VAR", xlab="PCVec", main="PCA Explain VAR")
# Show first three principal component loadings
data.pca$rotation[,1:3]
# Permute second principal component loadings by size
loadings.pca2 <- as.matrix(data.pca$rotation[order(data.pca$rotation[,2], decreasing=TRUE),2])
colnames(loadings.pca2) <- "PCA2"
loadings.pca2
# The option las=3 rotates the names.arg labels
barplot(as.vector(loadings.pca2), names.arg=rownames(loadings.pca2), las=3, ylab="Loadings", xlab="Symbol", main="Loadings PCA2")
# Convert time series of returns of principal components to xts
rets.pca <- xts(data.pca$x, order.by=index(ts.rets))
index(rets.pca) <- index(rets.pca)
plot.zoo(cumsum(rets.pca[,1:10]))
chart_Series(cumsum(rets.pca[,1]), name=colnames(rets.pca[,1]))
pacf(as.vector(rets.pca[,1]), lag=10, xlab="Lag ticks", main=paste("PACF of PC1"))
# Calculate time series of prices of principal components - not same as cumsum(rets.pca) !!!
ts.pca <- xts(ts.prices[,symbols.data$CMATicker] %*% data.pca$rotation, index(ts.prices))
# cbind IG index with PC's, and calculate statistics
rets.pca <- cbind(ts.rets[,'IG'],rets.pca[,1:10])
# colnames(rets.pca)[1] <- 'IG'
index(rets.pca) <- index(rets.pca)
var.ratios <- as.matrix(apply(rets.pca, 2, var.ratio, agg.min=1, agg.max=5))
colnames(var.ratios) <- 'Var.Ratios'
# Calculate cumsum(rets.pca)
ts.pca <- cumsum(rets.pca)
# Combine all the top CDS, and perform cluster analysis,
names.pca <- apply(as.matrix(1:10), 1, function(n.pc)
{
loadings.pca <- as.matrix(data.pca$rotation[order(abs(data.pca$rotation[,n.pc]), decreasing=TRUE),n.pc])
rownames(head(loadings.pca,20))
}
)
### Calculate returns for sector portfolios
symbols.top <- read.csv('S:/Data/R_Data/TOPNAIG_Symbols_ordered.csv', stringsAsFactors=FALSE)
# rets.portfolios <- NULL
rets.portfolios <- apply(as.matrix(unique(symbols.top$Portfolio)), 1, function(n.portfolio)
{
write(n.portfolio, stdout())
n.rows <- which(symbols.top$Portfolio==n.portfolio)
n.notionals <- symbols.top$Notional[n.rows]
ts.portfolio <- (ts.rets[,symbols.top$CMAEntityId[n.rows]] %*% n.notionals)/sum(n.notionals)
# colnames(ts.portfolio) <- n.portfolio
# rets.portfolios <<- cbind(rets.portfolios,ts.portfolio)
ts.portfolio
}
)
rets.portfolios <- xts(rets.portfolios, index(ts.rets))
colnames(rets.portfolios) <- unique(symbols.top$Portfolio)
plot.zoo(cumsum(rets.portfolios['2013-01-03/',]), main=paste('Sector portfolios', '/', format(Sys.time(),'%y-%m-%d', tz="GMT")))
n.portfolio <- 'Mtg Ins'
plot.zoo(ts.prices['2013-01-03/',symbols.top$CMAEntityId[which(symbols.top$Portfolio==n.portfolio)]], main=paste(n.portfolio, '/', format(Sys.time(),'%y-%m-%d', tz="GMT")))
as.matrix(apply(rets.portfolios, 2, var.ratio, agg.min=1, agg.max=5))
# Plot portfolios in loop
par(ask=TRUE)
apply(as.matrix(unique(symbols.top$Portfolio)), 1, function(n.portfolio)
{
plot.zoo(ts.prices['2013-01-03/',symbols.top$CMAEntityId[which(symbols.top$Portfolio==n.portfolio)]], main=paste(n.portfolio, '/', format(Sys.time(),'%y-%m-%d', tz="GMT")))
n.portfolio
}
)
par(ask=FALSE)
# Get last prices
last.prices <- t(coredata(tail(ts.prices,1)))
last.prices <- as.matrix(last.prices[order(last.prices, decreasing=TRUE),1])
colnames(last.prices) <- 'last.prices'
head(last.prices)
write.csv(last.prices, "S:/Data/R_Data/data.last.prices.2013.csv")
# Write last prices for only the top symbols
rows.top <- match(symbols.top$CMAEntityId, rownames(last.prices))
write.csv(cbind(rownames(last.prices)[rows.top], last.prices[rows.top]), "S:/Data/R_Data/data.last.prices.2013.csv")
# write.csv(last.prices[match(symbols.top$CMAEntityId, rownames(last.prices))], "S:/Data/R_Data/data.last.prices.2013.csv")
# write.csv(last.prices[which(rownames(last.prices) %in% symbols.top$CMAEntityId)], "S:/Data/R_Data/data.last.prices.2013.csv")
# apply(matrix(symbols.top$CMAEntityId), 1, match, table=colnames(ts.prices))
# apply(matrix(symbols.top$CMAEntityId), 1, function(n.name) which(n.name==colnames(ts.prices)))
### Calculate rate of change for a list of symbols
look.back <- 2
ts.lrets <- diff(log(ts.prices),lag=look.back)
ts.lrets[1:look.back,] <- ts.lrets[look.back+1,]
# Calculate variance for a list of symbols
profile.var <- sapply(ts.lrets, function(ts.lret) sqrt(var(ts.lret)))
# Sort symbol positions by lowest to highest rate of change
# symbols.top <- t(sapply(1:length(ts.lrets[,1]), function(row.num) order(coredata(ts.lrets[row.num,]))))
# Sort symbols by highest to lowest absolute rate of change
row.num <- nrow(ts.lrets)
sd.lrets <- sqrt(apply(na.omit(diff(log(ts.prices))), 2, var))
norm.lrets <- as.vector(ts.lrets[row.num,])/sd.lrets
symbols.top <- colnames(ts.lrets)[order(abs(norm.lrets), decreasing=TRUE)]
plot.zoo(ts.prices['2012-01-03/', symbols.top[11:22]], main=paste('Top CDS/', format(Sys.time(),'%y-%m-%d', tz="GMT")))
# For each date, sort symbols by highest to lowest rate of change
symbols.top <- t(sapply(1:nrow(ts.lrets), function(row.num) colnames(ts.lrets)[order(coredata(ts.lrets[row.num,]), decreasing=TRUE)]))
symbols.top <- xts(symbols.top,order.by=index(ts.lrets))
# Show symbols with highest to lowest rate of change
cut.off <- 10
tail(symbols.top[,1:cut.off],22)
tail(symbols.top[,(length(symbols.top[1,])-cut.off+1):length(symbols.top[1,])],22)
# Perform regression of IG versus PC's
formula.lm <- IG ~ PC1
data.lm <- lm(formula.lm, data=rets.pca)
summary(data.lm)
# Plot regression scatterplot
plot(IG ~ PC1, data=rets.pca, ylab="IG", xlab="PC1", main='Regression of IG versus PC1')
abline(data.lm)
# Plot IG and PC1 in out plot
plot.xts(cumsum(rets.pca[,'IG']), xlab='', ylab='', main='IG', type='l')
par(new=TRUE)
lines(cumsum(data.lm$coefficients[2]*rets.pca[,'PC1']), col='red', lwd=3)
# Calculate residuals
data.lm$residuals <- xts(data.lm$residuals, order.by=index(rets.pca))
colnames(data.lm$residuals) <- 'resid.lm'
plot.zoo(cumsum(cbind(rets.pca[,'IG'],-rets.pca[,'PC1'],rets.pca[,'PC2'],data.lm$residuals)))
pacf(data.lm$residuals, lag=10, xlab="Lag ticks", main=paste("PACF of lm"))
# Perform prediction from lm model (this isn't forecasting!)
predict.ig <- as.xts(predict(data.lm))
colnames(predict.ig) <- 'predict.ig'
# Calculate fitted IG values from regression (same as predicted)
fitted.ig <- as.xts(fitted(data.lm))
colnames(fitted.ig) <- 'fitted.ig'
plot.zoo(cumsum(cbind(rets.pca[,'IG'],predict.ig,fitted.ig)))
plot.xts(cumsum(rets.pca[,'IG']), xlab='', ylab='', main='IG', type='l')
par(new=TRUE)
lines(cumsum(fitted.ig), col='red', lwd=3)
# Fit ARIMA model to PC1 spreads (not returns)
library(forecast)
arima.pc1 <- auto.arima(x=as.vector(ts.pca[,'PC1']))
summary(arima.pc1)
# Plot fitted PC1 values
fitted.pc1 <- xts(fitted(arima.pc1), order.by=index(ts.pca))
plot.xts(ts.pca[,'PC1'], xlab='', ylab='', main='PC1 fit in RED', type='l')
par(new=TRUE)
lines(fitted.pc1, col='red', lwd=1)
# Forecast next few PC1 ticks
forecast.pc1 <- forecast(arima.pc1)
plot(forecast.pc1)
# Fit ARIMA model to IG spreads versus PC1 spreads (not returns)
# Fit ARIMA(2,0,0) model to IG versus PC1
arima.ig <- Arima(x=as.vector(ts.pca[,'IG']), xreg=as.vector(ts.pca[,'PC1']), order=c(2,0,0))
# Choose best ARIMA model for IG index using auto.arima and PC1 as external regressor
arima.ig <- auto.arima(x=as.vector(ts.pca[,'IG']), xreg=as.vector(ts.pca[,'PC1']), max.P=5, max.Q=5, max.order=10)
summary(arima.ig)
# Plot fitted PC1 values
fitted.ig <- xts(fitted(arima.ig), order.by=index(ts.pca))
plot.xts(ts.pca[,'IG'], xlab='', ylab='', main='IG fit in RED', type='l')
par(new=TRUE)
lines(fitted.ig, col='red', lwd=1)
# Forecast next few IG ticks
forecast.ig <- forecast.Arima(arima.ig)
plot(forecast.ig)
### Run simple trading strategy based on signal from medians
# Prepare data
bid.offer <- 0.125
ts.data <- ts.1min.ig['2013-01-03/','MEDIAN']
ts.rets <- diff(ts.data)