Assets: Maruti Suzuki, Mahindra & Mahindra, Bajaj Auto, Hero MotoCorp, Eicher Motors and the NIFTY AUTO index.

0. Data Download and Preparation

# Short name = Yahoo Finance symbol
symbols <- c(MARUTI = "MARUTI.NS", MM = "M&M.NS", BAJAJ = "BAJAJ-AUTO.NS",
             HERO = "HEROMOTOCO.NS", EICHER = "EICHERMOT.NS", AUTO = "^CNXAUTO")

# Download each series once and save as CSV (skipped if the file already exists)
file_of <- function(s) paste0("Automobile_Data/", gsub("[^A-Za-z0-9]", "_", s), ".csv")
for (s in symbols) {
  if (!file.exists(file_of(s))) {
    d <- getSymbols(s, src = "yahoo", from = "2018-01-01", to = "2026-01-01",
                    auto.assign = FALSE)
    write.csv(data.frame(Date = index(d), coredata(d)), file_of(s), row.names = FALSE)
  }
}

# Read Close price and Volume of one asset
read_px <- function(s) {
  d <- read.csv(file_of(s))
  xts(data.frame(Close  = d[[grep("Close$",  names(d))[1]]],
                 Volume = d[[grep("Volume$", names(d))[1]]]),
      order.by = as.Date(d$Date))
}
raw <- lapply(symbols, read_px)

prices  <- do.call(merge, lapply(raw, function(x) x$Close))
volumes <- do.call(merge, lapply(raw, function(x) x$Volume))
colnames(prices) <- colnames(volumes) <- names(symbols)

prices  <- na.omit(na.locf(prices, na.rm = FALSE))
volumes <- na.locf(volumes, na.rm = FALSE)

# Daily log returns
returns <- na.omit(diff(log(prices)))
head(returns)
##                  MARUTI           MM
## 2018-01-02 -0.010189700 0.0110181072
## 2018-01-03 -0.014491080 0.0026528732
## 2018-01-04 -0.003228195 0.0014560537
## 2018-01-05  0.005058391 0.0004628235
## 2018-01-08  0.001599401 0.0046826781
## 2018-01-09 -0.006945509 0.0033500708
##                   BAJAJ         HERO
## 2018-01-02  0.001670717 -0.001401317
## 2018-01-03 -0.016432926  0.003027013
## 2018-01-04  0.007193914 -0.004350109
## 2018-01-05  0.004706439  0.001536704
## 2018-01-08 -0.001250869  0.011180003
## 2018-01-09 -0.009893857 -0.009898982
##                  EICHER         AUTO
## 2018-01-02 -0.041772863  0.003077585
## 2018-01-03  0.005017073 -0.005072778
## 2018-01-04 -0.008490097 -0.001986484
## 2018-01-05  0.023051564  0.007264589
## 2018-01-08 -0.001355353  0.003756715
## 2018-01-09 -0.020779568 -0.002696856
write.csv(data.frame(Date = index(prices), coredata(prices)),
          "Outputs/prices_clean.csv", row.names = FALSE)
write.csv(data.frame(Date = index(returns), coredata(returns)),
          "Outputs/returns_clean.csv", row.names = FALSE)

A. Descriptive Analytics

desc_stats <- t(apply(returns, 2, function(x) c(
  Mean = mean(x), Median = median(x), SD = sd(x),
  Skewness = skewness(x), Kurtosis = kurtosis(x),   # normal distribution = 3
  Min = min(x), Max = max(x))))
print(round(desc_stats, 5))
##           Mean   Median      SD Skewness
## MARUTI 0.00028 -0.00013 0.01794 -0.16997
## MM     0.00081  0.00098 0.02002  0.23550
## BAJAJ  0.00053  0.00050 0.01666 -0.41832
## HERO   0.00022  0.00021 0.01840  0.15465
## EICHER 0.00045  0.00012 0.01956  0.00498
## AUTO   0.00044  0.00042 0.01431 -0.50071
##        Kurtosis      Min     Max
## MARUTI 11.78919 -0.18524 0.12676
## MM      5.08970 -0.09756 0.15573
## BAJAJ   9.62047 -0.14711 0.11432
## HERO    4.62859 -0.11652 0.12273
## EICHER  4.07439 -0.13446 0.12558
## AUTO   11.02112 -0.14906 0.09900
write.csv(desc_stats, "Outputs/descriptive_statistics.csv")

# Jarque-Bera normality test (H0: returns are normal)
for (s in colnames(returns)) {
  cat(s, "JB p-value:", jarque.bera.test(as.numeric(returns[, s]))$p.value, "\n")
}
## MARUTI JB p-value: 0 
## MM JB p-value: 0 
## BAJAJ JB p-value: 0 
## HERO JB p-value: 0 
## EICHER JB p-value: 0 
## AUTO JB p-value: 0
plot(prices,  multi.panel = TRUE, main = "Price Series")

plot(returns, multi.panel = TRUE, main = "Daily Log Returns")

par(mfrow = c(2, 3))
for (s in colnames(returns)) {
  hist(as.numeric(returns[, s]), breaks = 50, main = s, xlab = "Log return")
}

par(mfrow = c(1, 1))
print(round(cor(returns), 3))
##        MARUTI    MM BAJAJ  HERO EICHER  AUTO
## MARUTI  1.000 0.499 0.478 0.511  0.532 0.803
## MM      0.499 1.000 0.410 0.449  0.453 0.762
## BAJAJ   0.478 0.410 1.000 0.590  0.427 0.653
## HERO    0.511 0.449 0.590 1.000  0.434 0.679
## EICHER  0.532 0.453 0.427 0.434  1.000 0.674
## AUTO    0.803 0.762 0.653 0.679  0.674 1.000
pairs(coredata(returns), main = "Return Correlations", pch = ".")

Interpretation: SD measures risk; skewness below 0 and kurtosis above 3 indicate a fat left tail (crash risk); high correlation with NIFTY AUTO means limited diversification. (Add your own observations here.)

B. Time Series and Causality (NIFTY AUTO vs MARUTI)

lp <- as.matrix(log(prices[, c("AUTO", "MARUTI")]))

# ADF and PP on levels and first differences (H0: unit root)
for (s in colnames(lp)) {
  cat("\n", s, "- LEVEL\n")
  print(adf.test(lp[, s])); print(pp.test(lp[, s]))
  cat("\n", s, "- FIRST DIFFERENCE\n")
  print(adf.test(diff(lp[, s]))); print(pp.test(diff(lp[, s])))
}
## 
##  AUTO - LEVEL
## 
##  Augmented Dickey-Fuller Test
## 
## data:  lp[, s]
## Dickey-Fuller = -2.535, Lag order = 12,
## p-value = 0.3518
## alternative hypothesis: stationary
## 
## 
##  Phillips-Perron Unit Root Test
## 
## data:  lp[, s]
## Dickey-Fuller Z(alpha) = -7.3279,
## Truncation lag parameter = 8, p-value =
## 0.701
## alternative hypothesis: stationary
## 
## 
##  AUTO - FIRST DIFFERENCE
## 
##  Augmented Dickey-Fuller Test
## 
## data:  diff(lp[, s])
## Dickey-Fuller = -11.677, Lag order = 12,
## p-value = 0.01
## alternative hypothesis: stationary
## 
##  Phillips-Perron Unit Root Test
## 
## data:  diff(lp[, s])
## Dickey-Fuller Z(alpha) = -2048.6,
## Truncation lag parameter = 8, p-value =
## 0.01
## alternative hypothesis: stationary
## 
## 
##  MARUTI - LEVEL
## 
##  Augmented Dickey-Fuller Test
## 
## data:  lp[, s]
## Dickey-Fuller = -2.4886, Lag order = 12,
## p-value = 0.3715
## alternative hypothesis: stationary
## 
## 
##  Phillips-Perron Unit Root Test
## 
## data:  lp[, s]
## Dickey-Fuller Z(alpha) = -11.714,
## Truncation lag parameter = 8, p-value =
## 0.4563
## alternative hypothesis: stationary
## 
## 
##  MARUTI - FIRST DIFFERENCE
## 
##  Augmented Dickey-Fuller Test
## 
## data:  diff(lp[, s])
## Dickey-Fuller = -12.699, Lag order = 12,
## p-value = 0.01
## alternative hypothesis: stationary
## 
##  Phillips-Perron Unit Root Test
## 
## data:  diff(lp[, s])
## Dickey-Fuller Z(alpha) = -1872.3,
## Truncation lag parameter = 8, p-value =
## 0.01
## alternative hypothesis: stationary
sel <- VARselect(lp, lag.max = 10, type = "const")
K <- max(2, as.numeric(sel$selection["AIC(n)"]))

# Johansen cointegration test (trace)
jo <- ca.jo(lp, type = "trace", ecdet = "const", K = K)
summary(jo)
## 
## ###################### 
## # Johansen-Procedure # 
## ###################### 
## 
## Test type: trace statistic , without linear trend and constant in cointegration 
## 
## Eigenvalues (lambda):
## [1]  4.876835e-03  8.500527e-04 -2.276825e-18
## 
## Values of teststatistic and critical values of test:
## 
##           test 10pct  5pct  1pct
## r <= 1 |  1.67  7.52  9.24 12.97
## r = 0  | 11.30 17.85 19.96 24.60
## 
## Eigenvectors, normalised to first column:
## (These are the cointegration relations)
## 
##             AUTO.l7 MARUTI.l7   constant
## AUTO.l7    1.000000  1.000000   1.000000
## MARUTI.l7 -1.614537 -1.951935   1.985734
## constant   5.219590  7.154253 -27.522170
## 
## Weights W:
## (This is the loading matrix)
## 
##              AUTO.l7     MARUTI.l7
## AUTO.d   0.005778834 -0.0002820931
## MARUTI.d 0.010884581 -0.0001056281
##               constant
## AUTO.d   -7.281382e-17
## MARUTI.d -1.254804e-16
cointegrated <- jo@teststat[2] > jo@cval[2, 2]
cat("Cointegrated at 5%:", cointegrated, "\n")
## Cointegrated at 5%: FALSE
if (cointegrated) {
  print(cajorls(jo, r = 1))
  cat("Long-run relation (normalised on first variable):\n")
  print(jo@V[, 1] / jo@V[1, 1])
}
# Granger causality on stationary returns (H0: no Granger causality)
rt <- coredata(returns[, c("AUTO", "MARUTI")])
p_r <- as.numeric(VARselect(rt, lag.max = 10, type = "const")$selection["AIC(n)"])
var_ret <- VAR(rt, p = p_r, type = "const")
summary(var_ret)
## 
## VAR Estimation Results:
## ========================= 
## Endogenous variables: AUTO, MARUTI 
## Deterministic variables: const 
## Sample size: 1969 
## Log Likelihood: 11736.072 
## Roots of the characteristic polynomial:
## 0.6421 0.6421 0.6274 0.6274 0.6027 0.6027  0.58  0.58 0.549 0.549 0.5193 0.2892
## Call:
## VAR(y = rt, p = p_r, type = "const")
## 
## 
## Estimation results for equation AUTO: 
## ===================================== 
## AUTO = AUTO.l1 + MARUTI.l1 + AUTO.l2 + MARUTI.l2 + AUTO.l3 + MARUTI.l3 + AUTO.l4 + MARUTI.l4 + AUTO.l5 + MARUTI.l5 + AUTO.l6 + MARUTI.l6 + const 
## 
##             Estimate Std. Error t value
## AUTO.l1    0.0301585  0.0380666   0.792
## MARUTI.l1 -0.0236698  0.0303362  -0.780
## AUTO.l2    0.0003751  0.0380632   0.010
## MARUTI.l2  0.0379935  0.0303439   1.252
## AUTO.l3    0.0434346  0.0379835   1.144
## MARUTI.l3 -0.0493950  0.0303269  -1.629
## AUTO.l4    0.0350657  0.0380203   0.922
## MARUTI.l4 -0.0057388  0.0303290  -0.189
## AUTO.l5    0.0874295  0.0378850   2.308
## MARUTI.l5 -0.0680251  0.0303012  -2.245
## AUTO.l6    0.0472710  0.0379084   1.247
## MARUTI.l6 -0.0796327  0.0303067  -2.628
## const      0.0003840  0.0003228   1.189
##           Pr(>|t|)   
## AUTO.l1    0.42831   
## MARUTI.l1  0.43534   
## AUTO.l2    0.99214   
## MARUTI.l2  0.21068   
## AUTO.l3    0.25297   
## MARUTI.l3  0.10353   
## AUTO.l4    0.35649   
## MARUTI.l4  0.84994   
## AUTO.l5    0.02112 * 
## MARUTI.l5  0.02488 * 
## AUTO.l6    0.21255   
## MARUTI.l6  0.00867 **
## const      0.23443   
## ---
## Signif. codes:  
## 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## 
## Residual standard error: 0.01428 on 1956 degrees of freedom
## Multiple R-Squared: 0.01255, Adjusted R-squared: 0.006492 
## F-statistic: 2.072 on 12 and 1956 DF,  p-value: 0.01597 
## 
## 
## Estimation results for equation MARUTI: 
## ======================================= 
## MARUTI = AUTO.l1 + MARUTI.l1 + AUTO.l2 + MARUTI.l2 + AUTO.l3 + MARUTI.l3 + AUTO.l4 + MARUTI.l4 + AUTO.l5 + MARUTI.l5 + AUTO.l6 + MARUTI.l6 + const 
## 
##             Estimate Std. Error t value
## AUTO.l1   -0.0233939  0.0477654  -0.490
## MARUTI.l1  0.0120754  0.0380653   0.317
## AUTO.l2    0.0314394  0.0477611   0.658
## MARUTI.l2 -0.0207286  0.0380750  -0.544
## AUTO.l3    0.1061404  0.0476611   2.227
## MARUTI.l3 -0.0828148  0.0380537  -2.176
## AUTO.l4    0.0708596  0.0477073   1.485
## MARUTI.l4 -0.0705104  0.0380563  -1.853
## AUTO.l5    0.0599163  0.0475375   1.260
## MARUTI.l5 -0.0651175  0.0380214  -1.713
## AUTO.l6    0.0724212  0.0475669   1.523
## MARUTI.l6 -0.1030110  0.0380284  -2.709
## const      0.0002492  0.0004051   0.615
##           Pr(>|t|)   
## AUTO.l1    0.62435   
## MARUTI.l1  0.75110   
## AUTO.l2    0.51045   
## MARUTI.l2  0.58622   
## AUTO.l3    0.02606 * 
## MARUTI.l3  0.02966 * 
## AUTO.l4    0.13763   
## MARUTI.l4  0.06406 . 
## AUTO.l5    0.20768   
## MARUTI.l5  0.08693 . 
## AUTO.l6    0.12804   
## MARUTI.l6  0.00681 **
## const      0.53849   
## ---
## Signif. codes:  
## 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## 
## Residual standard error: 0.01792 on 1956 degrees of freedom
## Multiple R-Squared: 0.01039, Adjusted R-squared: 0.004316 
## F-statistic: 1.711 on 12 and 1956 DF,  p-value: 0.05859 
## 
## 
## 
## Covariance matrix of residuals:
##             AUTO    MARUTI
## AUTO   0.0002040 0.0002059
## MARUTI 0.0002059 0.0003211
## 
## Correlation matrix of residuals:
##          AUTO MARUTI
## AUTO   1.0000 0.8046
## MARUTI 0.8046 1.0000
causality(var_ret, cause = "AUTO")$Granger
## 
##  Granger causality H0: AUTO do not
##  Granger-cause MARUTI
## 
## data:  VAR object var_ret
## F-Test = 2.0116, df1 = 6, df2 = 3912,
## p-value = 0.06071
causality(var_ret, cause = "MARUTI")$Granger
## 
##  Granger causality H0: MARUTI do not
##  Granger-cause AUTO
## 
## data:  VAR object var_ret
## F-Test = 2.7991, df1 = 6, df2 = 3912,
## p-value = 0.01018

C. ARCH / GARCH Volatility Modelling (NIFTY AUTO)

ret     <- returns$AUTO
ret_pct <- ret * 100   # percent returns help the optimiser

plot(ret, main = "NIFTY AUTO Returns (volatility clustering)")

acf(as.numeric(ret)^2, main = "ACF of squared returns")

# ARCH-LM test on AR(1) residuals (H0: no ARCH effect)
ar_fit <- arima(as.numeric(ret), order = c(1, 0, 0))
ArchTest(as.numeric(residuals(ar_fit)), lags = 12)
## 
##  ARCH LM-test; Null hypothesis: no ARCH
##  effects
## 
## data:  as.numeric(residuals(ar_fit))
## Chi-squared = 318.71, df = 12, p-value <
## 2.2e-16
# Chronological split: train = before 2025, test = 2025
split_date <- as.Date("2025-01-01")
n_test <- sum(index(ret) >= split_date)

make_spec <- function(g, ar) ugarchspec(
  variance.model = list(model = "sGARCH", garchOrder = g),
  mean.model = list(armaOrder = c(ar, 0), include.mean = TRUE),
  distribution.model = "norm")

fit_arch_full  <- ugarchfit(make_spec(c(1, 0), 1), data = ret_pct, solver = "hybrid")
fit_garch_full <- ugarchfit(make_spec(c(1, 1), 1), data = ret_pct, solver = "hybrid")
fit_arch_full
## 
## *---------------------------------*
## *          GARCH Model Fit        *
## *---------------------------------*
## 
## Conditional Variance Dynamics    
## -----------------------------------
## GARCH Model  : sGARCH(1,0)
## Mean Model   : ARFIMA(1,0,0)
## Distribution : norm 
## 
## Optimal Parameters
## ------------------------------------
##         Estimate  Std. Error  t value Pr(>|t|)
## mu      3.443140    0.000236  14570.9        0
## ar1    -0.521320    0.000076  -6871.3        0
## omega   0.011346    0.000001   7973.5        0
## alpha1  0.976423    0.000123   7954.0        0
## 
## Robust Standard Errors:
##         Estimate  Std. Error   t value
## mu      3.443140    65.26971  0.052752
## ar1    -0.521320     5.25295 -0.099243
## omega   0.011346     0.11016  0.103004
## alpha1  0.976423     9.48509  0.102943
##        Pr(>|t|)
## mu      0.95793
## ar1     0.92095
## omega   0.91796
## alpha1  0.91801
## 
## LogLikelihood : -6531.89 
## 
## Information Criteria
## ------------------------------------
##                    
## Akaike       6.6186
## Bayes        6.6299
## Shibata      6.6186
## Hannan-Quinn 6.6228
## 
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
##                         statistic  p-value
## Lag[1]                     0.6406 0.423502
## Lag[2*(p+q)+(p+q)-1][2]    3.6830 0.008574
## Lag[4*(p+q)+(p+q)-1][5]    7.4399 0.012908
## d.o.f=1
## H0 : No serial correlation
## 
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                   0.002034  0.9640
## Lag[2*(p+q)+(p+q)-1][2]  0.008529  0.9910
## Lag[4*(p+q)+(p+q)-1][5]  0.027337  0.9999
## d.o.f=1
## 
## Weighted ARCH LM Tests
## ------------------------------------
##             Statistic Shape Scale P-Value
## ARCH Lag[2]   0.01296 0.500 2.000  0.9094
## ARCH Lag[4]   0.03049 1.397 1.611  0.9969
## ARCH Lag[6]   0.03819 2.222 1.500  0.9999
## 
## Nyblom stability test
## ------------------------------------
## Joint Statistic:  22.0025
## Individual Statistics:             
## mu     0.8292
## ar1    0.8293
## omega  0.8294
## alpha1 0.8294
## 
## Asymptotic Critical Values (10% 5% 1%)
## Joint Statistic:          1.07 1.24 1.6
## Individual Statistic:     0.35 0.47 0.75
## 
## Sign Bias Test
## ------------------------------------
##                    t-value      prob sig
## Sign Bias           13.454 1.545e-39 ***
## Negative Sign Bias   3.507 4.637e-04 ***
## Positive Sign Bias  10.142 1.346e-23 ***
## Joint Effect       215.594 1.799e-46 ***
## 
## 
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
##   group statistic p-value(g-1)
## 1    20      6375            0
## 2    30      6560            0
## 3    40      6564            0
## 4    50      6546            0
## 
## 
## Elapsed time : 0.4621339
fit_garch_full
## 
## *---------------------------------*
## *          GARCH Model Fit        *
## *---------------------------------*
## 
## Conditional Variance Dynamics    
## -----------------------------------
## GARCH Model  : sGARCH(1,1)
## Mean Model   : ARFIMA(1,0,0)
## Distribution : norm 
## 
## Optimal Parameters
## ------------------------------------
##         Estimate  Std. Error  t value Pr(>|t|)
## mu      0.069180    0.027355   2.5289 0.011441
## ar1     0.065955    0.024436   2.6991 0.006953
## omega   0.039803    0.011776   3.3801 0.000725
## alpha1  0.092369    0.012636   7.3097 0.000000
## beta1   0.889645    0.014757  60.2855 0.000000
## 
## Robust Standard Errors:
##         Estimate  Std. Error  t value Pr(>|t|)
## mu      0.069180    0.027502   2.5154 0.011888
## ar1     0.065955    0.024147   2.7314 0.006307
## omega   0.039803    0.015587   2.5535 0.010663
## alpha1  0.092369    0.020440   4.5191 0.000006
## beta1   0.889645    0.020789  42.7947 0.000000
## 
## LogLikelihood : -3252.506 
## 
## Information Criteria
## ------------------------------------
##                    
## Akaike       3.2987
## Bayes        3.3129
## Shibata      3.2987
## Hannan-Quinn 3.3039
## 
## Weighted Ljung-Box Test on Standardized Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                    0.04099  0.8396
## Lag[2*(p+q)+(p+q)-1][2]   0.58763  0.9398
## Lag[4*(p+q)+(p+q)-1][5]   1.45739  0.8569
## d.o.f=1
## H0 : No serial correlation
## 
## Weighted Ljung-Box Test on Standardized Squared Residuals
## ------------------------------------
##                         statistic p-value
## Lag[1]                     0.2189  0.6399
## Lag[2*(p+q)+(p+q)-1][5]    1.1169  0.8327
## Lag[4*(p+q)+(p+q)-1][9]    2.4196  0.8495
## d.o.f=2
## 
## Weighted ARCH LM Tests
## ------------------------------------
##             Statistic Shape Scale P-Value
## ARCH Lag[3]    0.4232 0.500 2.000  0.5154
## ARCH Lag[5]    1.1406 1.440 1.667  0.6917
## ARCH Lag[7]    2.1404 2.315 1.543  0.6876
## 
## Nyblom stability test
## ------------------------------------
## Joint Statistic:  1.2857
## Individual Statistics:              
## mu     0.64684
## ar1    0.05215
## omega  0.34678
## alpha1 0.29470
## beta1  0.25862
## 
## Asymptotic Critical Values (10% 5% 1%)
## Joint Statistic:          1.28 1.47 1.88
## Individual Statistic:     0.35 0.47 0.75
## 
## Sign Bias Test
## ------------------------------------
##                    t-value     prob sig
## Sign Bias           2.8606 0.004273 ***
## Negative Sign Bias  0.1388 0.889627    
## Positive Sign Bias  0.5827 0.560194    
## Joint Effect       13.3114 0.004009 ***
## 
## 
## Adjusted Pearson Goodness-of-Fit Test:
## ------------------------------------
##   group statistic p-value(g-1)
## 1    20     85.38    2.157e-10
## 2    30    105.88    1.099e-10
## 3    40    109.23    1.419e-08
## 4    50    130.65    2.358e-09
## 
## 
## Elapsed time : 0.1456602
# Persistence = alpha1 + beta1 (close to 1 = shocks die out slowly)
persistence(fit_garch_full)
## [1] 0.9820141
plot(sigma(fit_garch_full), main = "GARCH(1,1) Conditional Volatility (%)")

fc_next <- ugarchforecast(fit_garch_full, n.ahead = 1)
cat("Next-day GARCH volatility forecast (%):", as.numeric(sigma(fc_next)), "\n")
## Next-day GARCH volatility forecast (%): 0.9005485
# Out-of-sample fits (training data only, no look-ahead)
fits <- list(
  arch  = ugarchfit(make_spec(c(1, 0), 1), data = ret_pct, out.sample = n_test, solver = "hybrid"),
  garch = ugarchfit(make_spec(c(1, 1), 1), data = ret_pct, out.sample = n_test, solver = "hybrid"))
if (convergence(fits$arch) != 0 || convergence(fits$garch) != 0) {
  cat("AR(1) did not converge -> using constant-mean models\n")
  fits <- list(
    arch  = ugarchfit(make_spec(c(1, 0), 0), data = ret_pct, out.sample = n_test, solver = "hybrid"),
    garch = ugarchfit(make_spec(c(1, 1), 0), data = ret_pct, out.sample = n_test, solver = "hybrid"))
}

# One-day-ahead rolling forecasts over the 2025 test period
fc_arch  <- ugarchforecast(fits$arch,  n.ahead = 1, n.roll = n_test - 1)
fc_garch <- ugarchforecast(fits$garch, n.ahead = 1, n.roll = n_test - 1)
sigma_arch  <- as.numeric(sigma(fc_arch))  / 100
sigma_garch <- as.numeric(sigma(fc_garch)) / 100

# Realised variance proxy = squared return
actual_var <- as.numeric(tail(ret, n_test))^2
rmse <- function(a, f) sqrt(mean((a - f)^2))
mae  <- function(a, f) mean(abs(a - f))

Features for Machine Learning

# All features lagged by 1 day: no look-ahead
lagv <- function(x, k) c(rep(NA, k), head(x, -k))

d <- data.frame(Date = index(ret), Ret = as.numeric(ret))
d$Sq      <- d$Ret^2
d$Lag1Ret <- lagv(d$Ret, 1);  d$Lag2Ret <- lagv(d$Ret, 2);  d$Lag3Ret <- lagv(d$Ret, 3)
d$Lag1Sq  <- lagv(d$Sq, 1);   d$Lag2Sq  <- lagv(d$Sq, 2)
d$Vol5    <- lagv(rollapply(d$Ret, 5,  sd,   fill = NA, align = "right"), 1)
d$Vol10   <- lagv(rollapply(d$Ret, 10, sd,   fill = NA, align = "right"), 1)
d$Vol22   <- lagv(rollapply(d$Ret, 22, sd,   fill = NA, align = "right"), 1)
d$Mean5   <- lagv(rollapply(d$Ret, 5,  mean, fill = NA, align = "right"), 1)
d$Direction <- factor(ifelse(d$Ret > 0, "UP", "DOWN"), levels = c("DOWN", "UP"))
d <- na.omit(d)

predictors <- c("Lag1Ret", "Lag2Ret", "Lag3Ret", "Lag1Sq", "Lag2Sq",
                "Vol5", "Vol10", "Vol22", "Mean5")
train <- d[d$Date <  split_date, ]
test  <- d[d$Date >= split_date, ]
stopifnot(nrow(test) == n_test)

D. Machine Learning: Predicting Market Direction (UP / DOWN)

dir_formula <- as.formula(paste("Direction ~", paste(predictors, collapse = " + ")))

set.seed(123)
rf_dir  <- randomForest(dir_formula, data = train[, c(predictors, "Direction")], ntree = 300)
svm_dir <- svm(dir_formula, data = train[, c(predictors, "Direction")], kernel = "radial")

pred_rf  <- predict(rf_dir,  newdata = test[, predictors])
pred_svm <- predict(svm_dir, newdata = test[, predictors])

cat("Random Forest accuracy:", mean(pred_rf  == test$Direction), "\n")
## Random Forest accuracy: 0.4939759
cat("SVM accuracy          :", mean(pred_svm == test$Direction), "\n")
## SVM accuracy          : 0.502008
cat("Share of UP days in test set:", mean(test$Direction == "UP"), "\n")
## Share of UP days in test set: 0.4939759
table(Predicted = pred_rf,  Actual = test$Direction)
##          Actual
## Predicted DOWN UP
##      DOWN   58 58
##      UP     68 65
table(Predicted = pred_svm, Actual = test$Direction)
##          Actual
## Predicted DOWN UP
##      DOWN   46 44
##      UP     80 79

E. Machine Learning: Volatility Forecasting vs ARCH / GARCH

train$Y <- train$Sq * 1e4   # target = squared return (scaled)
vol_formula <- as.formula(paste("Y ~", paste(predictors, collapse = " + ")))

set.seed(123)
rf_vol  <- randomForest(vol_formula, data = train[, c(predictors, "Y")],
                        ntree = 300, importance = TRUE)
svm_vol <- svm(vol_formula, data = train[, c(predictors, "Y")],
               kernel = "radial", type = "eps-regression")

var_rf  <- pmax(predict(rf_vol,  newdata = test[, predictors]) / 1e4, 1e-10)
var_svm <- pmax(predict(svm_vol, newdata = test[, predictors]) / 1e4, 1e-10)

# Comparison table (lower = better)
vol_results <- data.frame(
  Model = c("ARCH(1)", "GARCH(1,1)", "Random Forest", "SVM"),
  RMSE  = c(rmse(actual_var, sigma_arch^2), rmse(actual_var, sigma_garch^2),
            rmse(actual_var, as.numeric(var_rf)), rmse(actual_var, as.numeric(var_svm))),
  MAE   = c(mae(actual_var, sigma_arch^2), mae(actual_var, sigma_garch^2),
            mae(actual_var, as.numeric(var_rf)), mae(actual_var, as.numeric(var_svm))))
print(vol_results)
##           Model         RMSE          MAE
## 1       ARCH(1) 0.0003123196 0.0001928623
## 2    GARCH(1,1) 0.0002861883 0.0001537822
## 3 Random Forest 0.0002880447 0.0001614539
## 4           SVM 0.0002873595 0.0001349588
write.csv(vol_results, "Outputs/volatility_forecast_comparison.csv", row.names = FALSE)

write.csv(data.frame(Date = test$Date, Actual_Sq_Return = actual_var,
                     ARCH = sigma_arch^2, GARCH = sigma_garch^2,
                     RF = as.numeric(var_rf), SVM = as.numeric(var_svm)),
          "Outputs/volatility_forecasts.csv", row.names = FALSE)
plot(test$Date, abs(test$Ret), type = "l", col = "grey70", xlab = "Date",
     ylab = "Volatility", main = "Out-of-sample Volatility Forecasts (2025)")
lines(test$Date, sigma_arch,    col = "orange")
lines(test$Date, sigma_garch,   col = "blue")
lines(test$Date, sqrt(var_rf),  col = "darkgreen")
lines(test$Date, sqrt(var_svm), col = "red")
legend("topright", c("|Return|", "ARCH", "GARCH", "RF", "SVM"),
       col = c("grey70", "orange", "blue", "darkgreen", "red"), lty = 1, cex = 0.8)

varImpPlot(rf_vol, main = "RF Variable Importance (Volatility)")

F. Panel Data Analysis (5 stocks x months)

stocks <- c("MARUTI", "MM", "BAJAJ", "HERO", "EICHER")
month  <- format(index(returns), "%Y-%m")
mkt_vol <- tapply(as.numeric(returns$AUTO), month, sd)   # NIFTY AUTO monthly volatility

panel <- do.call(rbind, lapply(stocks, function(s) {
  r  <- as.numeric(returns[, s])
  lv <- log(as.numeric(volumes[index(returns), s]) + 1)
  data.frame(Stock     = s,
             Month     = names(mkt_vol),
             RV        = as.numeric(tapply(r,  month, sd)),    # realised volatility
             Ret       = as.numeric(tapply(r,  month, sum)),   # monthly return
             LogVolume = as.numeric(tapply(lv, month, mean)),  # trading activity
             MktVol    = as.numeric(mkt_vol),                  # sector-wide volatility
             stringsAsFactors = FALSE)
}))
panel <- na.omit(panel)
head(panel)
##    Stock   Month          RV          Ret
## 1 MARUTI 2018-01 0.011416741 -0.014842477
## 2 MARUTI 2018-02 0.017183771 -0.071787531
## 3 MARUTI 2018-03 0.011968556  0.001146046
## 4 MARUTI 2018-04 0.009108751 -0.005221700
## 5 MARUTI 2018-05 0.010026713 -0.032016058
## 6 MARUTI 2018-06 0.010411842  0.033223437
##   LogVolume      MktVol
## 1  13.17099 0.006599270
## 2  13.20585 0.012831952
## 3  13.12570 0.009158171
## 4  12.88967 0.006646528
## 5  12.98424 0.010625967
## 6  12.80910 0.007790824
write.csv(panel, "Outputs/panel_data.csv", row.names = FALSE)
pdata <- pdata.frame(panel, index = c("Stock", "Month"))
panel_formula <- RV ~ Ret + LogVolume + MktVol

pooled <- plm(panel_formula, data = pdata, model = "pooling")
fe     <- plm(panel_formula, data = pdata, model = "within")
re     <- plm(panel_formula, data = pdata, model = "random")
summary(pooled)
## Pooling Model
## 
## Call:
## plm(formula = panel_formula, data = pdata, model = "pooling")
## 
## Balanced Panel: n = 5, T = 96, N = 480
## 
## Residuals:
##        Min.     1st Qu.      Median 
## -0.00972592 -0.00240376 -0.00039311 
##     3rd Qu.        Max. 
##  0.00236545  0.01684985 
## 
## Coefficients:
##                Estimate  Std. Error t-value
## (Intercept) -0.02097275  0.00301054 -6.9664
## Ret          0.00003507  0.00203024  0.0173
## LogVolume    0.00196325  0.00022771  8.6218
## MktVol       0.88568187  0.02881447 30.7374
##              Pr(>|t|)    
## (Intercept) 1.087e-11 ***
## Ret            0.9862    
## LogVolume   < 2.2e-16 ***
## MktVol      < 2.2e-16 ***
## ---
## Signif. codes:  
## 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Total Sum of Squares:    0.02643
## Residual Sum of Squares: 0.007024
## R-Squared:      0.73425
## Adj. R-Squared: 0.73257
## F-statistic: 438.376 on 3 and 476 DF, p-value: < 2.22e-16
summary(fe)
## Oneway (individual) effect Within Model
## 
## Call:
## plm(formula = panel_formula, data = pdata, model = "within")
## 
## Balanced Panel: n = 5, T = 96, N = 480
## 
## Residuals:
##        Min.     1st Qu.      Median 
## -0.00990734 -0.00233856 -0.00025764 
##     3rd Qu.        Max. 
##  0.00228243  0.01716723 
## 
## Coefficients:
##              Estimate  Std. Error t-value
## Ret       -0.00086923  0.00196341 -0.4427
## LogVolume  0.00377960  0.00045647  8.2800
## MktVol     0.81640502  0.03163104 25.8102
##            Pr(>|t|)    
## Ret          0.6582    
## LogVolume 1.278e-15 ***
## MktVol    < 2.2e-16 ***
## ---
## Signif. codes:  
## 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Total Sum of Squares:    0.025665
## Residual Sum of Squares: 0.0064264
## R-Squared:      0.74961
## Adj. R-Squared: 0.74589
## F-statistic: 471.014 on 3 and 472 DF, p-value: < 2.22e-16
summary(re)
## Oneway (individual) effect Random Effect Model 
##    (Swamy-Arora's transformation)
## 
## Call:
## plm(formula = panel_formula, data = pdata, model = "random")
## 
## Balanced Panel: n = 5, T = 96, N = 480
## 
## Effects:
##                     var   std.dev share
## idiosyncratic 1.361e-05 3.690e-03 0.907
## individual    1.392e-06 1.180e-03 0.093
## theta: 0.6959
## 
## Residuals:
##        Min.     1st Qu.      Median 
## -0.00942127 -0.00228890 -0.00023109 
##     3rd Qu.        Max. 
##  0.00223880  0.01694160 
## 
## Coefficients:
##                Estimate  Std. Error z-value
## (Intercept) -0.03746960  0.00529403 -7.0777
## Ret         -0.00057274  0.00196879 -0.2909
## LogVolume    0.00322063  0.00040059  8.0397
## MktVol       0.83775394  0.03061263 27.3663
##              Pr(>|z|)    
## (Intercept) 1.466e-12 ***
## Ret            0.7711    
## LogVolume   9.003e-16 ***
## MktVol      < 2.2e-16 ***
## ---
## Signif. codes:  
## 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Total Sum of Squares:    0.025736
## Residual Sum of Squares: 0.0065419
## R-Squared:      0.74581
## Adj. R-Squared: 0.74421
## Chisq: 1396.6 on 3 DF, p-value: < 2.22e-16
pFtest(fe, pooled)            # H0: pooled OLS is adequate
## 
##  F test for individual effects
## 
## data:  panel_formula
## F = 10.972, df1 = 4, df2 = 472, p-value =
## 1.625e-08
## alternative hypothesis: significant effects
plmtest(pooled, type = "bp")  # Breusch-Pagan LM: H0 = no panel effects
## 
##  Lagrange Multiplier Test -
##  (Breusch-Pagan)
## 
## data:  panel_formula
## chisq = 44.947, df = 1, p-value =
## 2.025e-11
## alternative hypothesis: significant effects
phtest(fe, re)                # Hausman: reject H0 -> use fixed effects
## 
##  Hausman Test
## 
## data:  panel_formula
## chisq = 6.5227, df = 3, p-value = 0.08877
## alternative hypothesis: one model is inconsistent

G. NLP: News Sentiment

Files needed in the same folder as this .Rmd: auto_news.csv (columns: Date, Headline), positive.txt and negative.txt.

needed <- c("auto_news.csv", "positive.txt", "negative.txt")
if (!all(file.exists(needed))) {
  stop("Missing file(s) in ", getwd(), ": ", paste(needed[!file.exists(needed)], collapse = ", "))
}

news <- read.csv("auto_news.csv", stringsAsFactors = FALSE, fileEncoding = "UTF-8-BOM")
news$Date <- as.Date(news$Date, tryFormats = c("%Y-%m-%d", "%d-%m-%Y", "%d/%m/%Y", "%m/%d/%Y"))

# Load a word list: handles BOM, Windows line endings and ';' comment headers
read_words <- function(f) {
  w <- readLines(f, warn = FALSE, encoding = "UTF-8")
  w <- tolower(trimws(gsub("\ufeff|\r", "", w)))
  w[grepl("^[a-z]+$", w)]
}
positive <- read_words("positive.txt")
negative <- read_words("negative.txt")

if (length(positive) == 0 || length(negative) == 0) {
  stop("positive or negative list contains no words. Check the files.")
}
cat("Rows in news:", nrow(news), "\n")
## Rows in news: 16
cat("Positive words:", length(positive), "| Negative words:", length(negative), "\n")
## Positive words: 1904 | Negative words: 4658
clean_text <- function(txt) {
  txt <- iconv(as.character(txt), from = "", to = "ASCII", sub = " ")
  txt <- tolower(txt)
  txt <- gsub("\\W", " ", txt)
  txt <- gsub("\\d", " ", txt)
  txt <- removeWords(txt, stopwords())
  txt <- gsub("\\b[a-z]\\b", " ", txt)
  txt <- stripWhitespace(txt)
  trimws(txt)
}

news$Clean  <- clean_text(news$Headline)
tokens_list <- strsplit(news$Clean, " ")
all_words   <- unlist(tokens_list)
all_words   <- all_words[all_words != ""]

word_freq <- sort(table(all_words), decreasing = TRUE)
head(word_freq, 20)
## all_words
##       auto     stocks     motors      nifty 
##         20          8          6          6 
##       tata        gst     maruti      rally 
##          5          4          4          4 
##     shares     tariff        car     demand 
##          4          4          3          3 
##      trump         us      ashok brokerages 
##          3          3          2          2 
##     expect    exports       fall       gain 
##          2          2          2          2
write.csv(as.data.frame(word_freq), "Outputs/word_frequency.csv", row.names = FALSE)
barplot(head(word_freq, 15), las = 2, main = "Top 15 Words in Auto-Sector News")

wordcloud(all_words, min.freq = 2, random.order = FALSE,
          colors = brewer.pal(5, "Dark2"))

# Sentiment score = positive words - negative words
pscore <- sum(all_words %in% positive)
nscore <- sum(all_words %in% negative)
cat("Positive:", pscore, " Negative:", nscore, " Net sentiment:", pscore - nscore, "\n")
## Positive: 19  Negative: 6  Net sentiment: 13
news$Sentiment <- sapply(tokens_list, function(w) sum(w %in% positive) - sum(w %in% negative))

# Relate daily sentiment to NIFTY AUTO return and volatility (|return|)
daily_sent <- aggregate(Sentiment ~ Date, data = news, FUN = mean)
sent_xts   <- xts(daily_sent$Sentiment, order.by = daily_sent$Date)

nlp_data <- na.omit(merge(sent_xts, ret, join = "inner"))
colnames(nlp_data) <- c("Sentiment", "Return")
nlp_data$AbsReturn <- abs(nlp_data$Return)

cor.test(as.numeric(nlp_data$Sentiment), as.numeric(nlp_data$Return))
## 
##  Pearson's product-moment correlation
## 
## data:  as.numeric(nlp_data$Sentiment) and as.numeric(nlp_data$Return)
## t = 3.4179, df = 14, p-value = 0.004162
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
##  0.2685097 0.8769600
## sample estimates:
##       cor 
## 0.6744452
cor.test(as.numeric(nlp_data$Sentiment), as.numeric(nlp_data$AbsReturn))
## 
##  Pearson's product-moment correlation
## 
## data:  as.numeric(nlp_data$Sentiment) and as.numeric(nlp_data$AbsReturn)
## t = 0.68522, df = 14, p-value = 0.5044
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
##  -0.3465089  0.6204409
## sample estimates:
##       cor 
## 0.1801381
plot(as.numeric(nlp_data$Sentiment), as.numeric(nlp_data$Return),
     xlab = "News sentiment score", ylab = "NIFTY AUTO return",
     main = "Sentiment vs Return", pch = 19)
abline(lm(as.numeric(nlp_data$Return) ~ as.numeric(nlp_data$Sentiment)), col = "red")

Conclusion

(Write your overall findings here: which model forecast volatility best, whether NIFTY AUTO Granger-causes MARUTI, whether news sentiment relates to returns, etc.)