# this is code to check the commodities for cointegration and produce a hedge ratio # need to create a loop to apply the function to each pair in the file # IBrokersRef() library("IBrokers") library("urca") # for johansen library(zoo) library(tseries) tws <- twsConnect() reqCurrentTime(tws) checkPairFromIB <- function(sym1, mkt1, sym2, mkt2) { contract1 <- twsContract(0,sym1, "CONTFUT", mkt1,"","","0.0","USD","","","",NULL,NULL,"0") contract2 <- twsContract(0,sym2, "CONTFUT", mkt2,"","","0.0","USD","","","",NULL,NULL,"0") #http://www.sthda.com/english/wiki/subsetting-data-frame-rows-in-r #print(contract1) one <- reqHistoricalData(tws, contract1, endDateTime = format(Sys.Date(), "%Y%m%d 24:00:00"), duration = "3 M") two <- reqHistoricalData(tws, contract2, endDateTime = format(Sys.Date(), "%Y%m%d 24:00:00"), duration = "3 M") one <- one[,1:5] two <- two[,1:5] # Give columns more usable names colnames(one) <- c('Open', 'High', 'Low', 'Close', 'Volume') colnames(two) <- c('Open', 'High', 'Low', 'Close', 'Volume') #print(one) print(length(one)) #print(one) print(length(two)) #print(two) # trim the longer one if (length(one) > length(two)){ trim <- one - two one <- one[trim:length(two),] } else if (length(one) < length(two)){ trim <- two - one two <- two[trim:length(one),] } #print(one) print(length(one)) #print(one) print(length(two)) #print(two) # failsafe if some market has closed if (length(one) == length(two)){ jotest=ca.jo(data.frame(one$Close,two$Close), type="trace", K=2, ecdet="none", spec="longrun") #print(summary(jotest)) #print("10pc") #print(jotest@cval[2,1]) #print("test") #print(jotest@teststat[2]) #print("hedge ratio") #print(jotest@V[2,1]) if (jotest@V[2] > jotest@cval[2,1]){ print(c(sym1, sym2, "cointegrated", "hedge", jotest@V[2,1] )) } else { print(c(sym1, sym2, "not cointegrated")) } } else { print("data of different lengths") } #https://stackoverflow.com/questions/42741633/extract-information-from-rs-johansen-procedure-ca-jo-summary #http://r.789695.n4.nabble.com/How-to-automatically-extract-test-result-from-Johansen-test-td4519468.html #https://cran.r-project.org/web/packages/urca/urca.pdf } #lets get the symbols symbols <- read.csv("C:\\Users\\Stephen\\Documents\\R\\2018 June\\metals.csv", stringsAsFactors=F) print(symbols) print ('##################') #print(nrow(symbols)) seq(1, nrow(symbols), by = 2) for (i in seq(1, nrow(symbols) - 1, by = 1)) { for (j in seq(i + 1, nrow(symbols), by = 1)) { print(c(i, j)) checkPairFromIB(symbols[i,1], symbols[i,2],symbols[j,1],symbols[j,2]) print("###################") #print(symbols[i,1]) #print(symbols[i,2]) #print(symbols[j,1]) #print(symbols[j,2]) print("pacing limit 10 seconds") Sys.sleep(10) } } #gold, silver #checkPairFromIB("GC", "NYMEX","SI","NYMEX") twsDisconnect(tws) #head(one) #head(two) #pacing limit #Sys.sleep(10)