# analyse pair 

library("IBrokers")
#library("urca") # for johansen

#library("zoo") installed by hand
library(tseries)
library(timeSeries)
library("TTR")



tws <- twsConnect()
reqCurrentTime(tws)

#sym1 <- 'GC'
#sym2 <- 'PA'
#mkt1 <- 'NYMEX'
#mkt2 <- 'NYMEX'

sym1 <- 'KC'
sym2 <- 'ZW'
mkt1 <- 'NYBOT'
mkt2 <- 'ECBOT'

#sym1 <- 'SI'
#sym2 <- 'PA'
#mkt1 <- 'NYMEX'
#mkt2 <- 'NYMEX'


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(nrow(one))

print(nrow(two))

if (nrow(one) > nrow(two)){
  	
	trim <- nrow(one) - nrow(two) + 1
	one <- one[trim:nrow(one)-1,]

} else if (nrow(one) < nrow(two)){

	trim <- nrow(two) - nrow(one) + 1
	two <- two[trim:nrow(two)-1,]  	

}


print(nrow(one))

print(nrow(two))

#only use first 30 days to avoid look ahead
m <- lm(one$Close[1:30] ~ two$Close[1:30] + 0)
		
beta <- coef(m)[1]
		
cat("Assumed hedge ratio is", beta, "\n")

spread <- one$Close - (beta * two$Close)

# I need mean plus SD

lookback <- 5
width <- 1

average <- SMA(spread, lookback)
thirty_day_mean <- mean(spread[1:30])
thirty_day_stanDev <- sd(spread[1:30])
thirty_day_upper <- thirty_day_mean + (width * thirty_day_stanDev)
thirty_day_lower <- thirty_day_mean - (width * thirty_day_stanDev)


stanDev <- rollapply(spread, lookback, sd)

upper <- average + (width * stanDev)
lower <- average - (width * stanDev)

#long_position <- if(spread$Close > upper) -1 else if (spread$Close < lower) 1


#print(spread)

plot.new()


plot(spread, main=paste(sym1, " - ", sym2, "\n", "lookback ", lookback, "\n", "width ", width), type="l")

lines(average,col="blue")
lines(upper,col="red")
lines(lower,col="red")


#abline(h=thirty_day_mean, col="blue", lwd = 3)
#abline(h=thirty_day_upper, col="red", lwd = 2)
#abline(h=thirty_day_lower, col="red", lwd = 2)




























  	