Created
December 10, 2013 02:53
-
-
Save mbusigin/7885054 to your computer and use it in GitHub Desktop.
Lead/Lag Cross Correlation between XTS objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
llxc = function( a, ll=-12:12, legend.loc="topleft", displayLegend=T, legend.cex=1.0, overplot=F ) | |
{ | |
if ( ncol(a) < 2 ) | |
{ | |
print( "Not enough columns") | |
return; | |
} | |
a = na.omit(a) | |
b = a[,1] | |
firstplot = T | |
colours = RColorBrewer::brewer.pal(length(names(a)), "Dark2") | |
colours[1] = "black" | |
count = 1 | |
s = {} | |
ylim = c(0, 0) | |
d = c() | |
for ( x in names(a)[2:length(names(a))] ) | |
{ | |
print(x) | |
c = a[,x] | |
for ( y in ll ) | |
{ | |
z = na.omit(merge(lag(b, k=y), c)) | |
r = cor(z)[2] | |
d = c( d, r ) | |
} | |
} | |
ylim = c(min(d), max(d)) | |
for ( x in names(a)[2:length(names(a))] ) | |
{ | |
print(x) | |
c = a[,x] | |
d = c() | |
for ( y in ll ) | |
{ | |
z = na.omit(merge(lag(b, k=y), c)) | |
r = cor(z)[2] | |
d = c( d, r ) | |
} | |
s[x] = d | |
print(paste("Max correlation:", max(abs(d)))) | |
if ( firstplot == T ) | |
{ | |
if ( overplot == T ) | |
{ | |
par(yaxt="n") | |
} | |
periodicityOfData = cat( periodicity(a)$label, "s", sep="" ) | |
print(periodicityOfData) | |
plot(ll, d, type="l", col=colours[count], ylim=ylim, xlab=periodicityOfData, ylab="Correlation Coefficient") | |
firstplot = F | |
} | |
else | |
{ | |
if ( overplot == T ) | |
{ | |
par(new=T, xaxt="n", yaxt="n") | |
plot(ll, d, col=colours[count], type="l") | |
} | |
else | |
{ | |
lines(ll, d, col=colours[count], type="l") | |
} | |
} | |
count = count + 1 | |
} | |
print (s) | |
if ( displayLegend == T ) | |
{ | |
legend(legend.loc, names(a)[2:length(names(a))], col=colours, lty=1, cex=legend.cex) | |
} | |
grid() | |
par(xaxt="s", yaxt="s") | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment