[R-SIG-Finance] Finding price difference of a time series
veepsirtt
veepsirtt at gmail.com
Fri Aug 2 10:33:19 CEST 2013
Hi,
I couldnot find cointegration coefficient while using
adf.test.
Error in ht$p - value : non-numeric argument to binary operator
In addition: Warning message:
sd(<matrix>) is deprecated.
Use apply(*, 2, sd) instead.
--------------------------------------------- The
code----------------------------------------------
if (!require(quantmod)) {
stop("This app requires the quantmod package. To install it, run
'install.packages(\"quantmod\")'.\n")
}
# Download data for a stock if needed, and return the data
require_symbol <- function(symbol, envir = parent.frame()) {
if (is.null(envir[[symbol]])) {
envir[[symbol]] <- getSymbols(symbol, auto.assign = FALSE)
}
envir[[symbol]]
}
# Create an environment for storing data
symbol_env <- new.env()
#Utilize quantmod to load the security symbols
require(quantmod)
library(zoo)
library(tseries)
s1="SPY"
s2="GOOG"
a <- require_symbol(s1, symbol_env)
b <- require_symbol(s2, symbol_env)
#remove NAs
c=cbind(a,b)
final=na.omit(c)
row.has.na <- apply(final, 1, function(x){any(is.na(x))})
sum(row.has.na)
A<- c[, c(1,2,3,4,5,6)]
B<- c[, c(7,8,9,10,11,12)]
#define training set
startT <- "2007-01-02"
endT <- "2009-01-01"
rangeT <- paste(startT,"::",endT,sep ="")
tA <- A[,6][rangeT]
tB <- B[,6][rangeT]
#define out of sample set
startO <- "2013-02-01"
endO <-Sys.Date()
rangeO <- paste(startO,"::",endO,sep ="")
oA <- A[,6][rangeO]
oB <- B[,6][rangeO]
#compute price differences on in-sample data
pdtA <- diff(tA)[-1]
pdtB <- diff(tB)[-1]
#build the model
model <- lm(pdtA ~ pdtB - 1)
#extract the hedge ratio
hr <- as.numeric(model$coefficients[1])
#spread price (in-sample)
spreadT <- oA - hr * oB
days=length(spreadT)
#compute statistics of the spread
meanT <- as.numeric(mean(spreadT,na.rm=TRUE))
sdT <- as.numeric(sd(spreadT,na.rm=TRUE))
#find correlation coefficient
cr= cor(oA, oB, method="spearman")
#find cointegration coefficient
ht <- adf.test(spreadT, alternative="stationary", k=0)
cat("ADF p-value is", ht$p-value, "\n")
-----------------------------------------------the
code--------------------------------------------------------
Thanks
veepsirtt
--
View this message in context: http://r.789695.n4.nabble.com/Finding-price-difference-of-a-time-series-tp4672099p4672880.html
Sent from the Rmetrics mailing list archive at Nabble.com.
More information about the R-SIG-Finance
mailing list