Q:

How to decrease the time needed for calculating Granger causality with high lag length?

Explanation of used function and data:

I am using function grangertest(x ~ y, order =k) , from package
lmtest
Each time series (x,y) has 1950 observations (first
difference for intraday 1 minute stock prices).

Problem:

When running grangertest(x ~ y, order =k) with very high k, such as
300, it takes a long time for calculation. For example for k = 300, it takes 17 seconds to calculate Granger causality.

Question:

Is there a way to decrease calculating time? This is important because I should run more than 8000 causality tests, meaning that duration of my calculations would be more than 37 hours.

Details about used platform:

I use R version 3.0.3
System Manufacturer  Dell Inc.
System Model Inspiron M5030
System Type  x64-based PC
Processor    AMD Athlon(tm) II P340 Dual-Core Processor, 2200 Mhz, 2
Core(s), 2 Logical Processor(s)
BIOS Version/Date    Dell Inc. A02, 8/5/2010
SMBIOS Version   2.6
Installed Physical Memory (RAM)  2.00 GB
Total Physical Memory    1.75 GB
Available Physical Memory    99.6 MB
Total Virtual Memory 3.49 GB
Available Virtual Memory 1.25 GB

A:

Here is a start for you with only necessary computations. It returns a p-value and F statistic only but you can easily modify it. 
grangerfast <- function(y, x, k) {
  l1 <- embed(y, k + 1)
  l2 <- embed(x, k + 1)
  X1 <- cbind(1, l1[, -1])
  X2 <- cbind(X1, l2[, -1])
  Y <- l1[, 1]
  d <- diag(length(Y))
  rss1 <- sum(((d - X1 %*% solve(crossprod(X1)) %*% t(X1)) %*% Y)^2)
  rss2 <- sum(((d - X2 %*% solve(crossprod(X2)) %*% t(X2)) %*% Y)^2)
  Fstat <- ((rss1 - rss2) / k) / (rss2 / (length(Y) - (2 * k + 1)))
  c(pf(Fstat, k, length(Y) - (2 * k + 1), lower.tail = FALSE), Fstat)
}
set.seed(123)
y <- rnorm(2000)
x <- rnorm(2000)
system.time(print(grangerfast(y, x, 300)))
# [1] 0.6529602 0.9627089
#    user  system elapsed 
#   3.527   0.051   3.576 
system.time(print(grangertest(y ~ x, order = 300)))
# Granger causality test
# 
# Model 1: y ~ Lags(y, 1:300) + Lags(x, 1:300)
# Model 2: y ~ Lags(y, 1:300)
#   Res.Df   Df      F Pr(>F)
# 1   1099                   
# 2   1399 -300 0.9627  0.653
#    user  system elapsed 
#   8.958   0.226   9.188 

It would be easy to check but probably matrix algebra takes most of the time. However, you might make it even faster. For example, in case you are performing this test for all pairs of stock prices, you could compute l1, l2 and crossproducts only once. You could also parallelize this process. If you are running the test for the same pair and different k, then again you can save some time.

