Time series in R: simulating an AR(1), then modelling Coca-Cola volatility with GARCH

02 Nov, 2026

By Denis Solís Salinas

In my financial econometrics course, I had to show with a final project that I could work with time series data from two directions: first building a process up from simulation to estimation, and then taking real financial data and modelling its volatility with GARCH models.

What I set out to do

The project had two halves that do not look related but are really the same skill in different scenarios. In the first half I simulated an AR(1) process, learned why the starter code was broken, and fitted the model back to verify the estimators recover the true parameters. In the second half I took four years of Coca-Cola daily prices, converted them to log returns, fitted a GARCH(1,1) and a GJR-GARCH model, and used them to forecast volatility. The thread joining them is that financial returns are roughly unpredictable in level but far from flat in variance, which is exactly what volatility models are for.

Part 1. Simulating and fitting an AR(1) process

Fixing the starter code

Every model I fit later rests on understanding the mechanism. The course gave us a short block of code to simulate an AR(1) process, deliberately containing four technical errors to find and fix:

set.seed(MatrNr)                    # 1) variable-name case mismatch (was matrnr)
n <- 500                            # number of observations
xt <- arima.sim(model = list(ar = 0.75), n = n, mean = 0.25)   # 2, 3, 4)

The four problems:

  1. Variable-name case mismatch. R is case sensitive, so MatrNr and matrnr are different objects. Referencing the wrong one inside set.seed() fails.
  2. Wrong function name. arima_sim is not an R function; the correct one is arima.sim.
  3. Misspelled argument. The function takes a model argument, not modell.
  4. Wrong way to fix the mean. The theoretical model is X(t) = 1 + 0.75 (X(t-1) - 1) + eps(t), with independent standard normal innovations. Rewriting, the AR(1) is X(t) = 0.75 X(t-1) + c + eps(t) with constant c = (1 - 0.75) x 1 = 0.25. So the mean is set through the mean argument (0.25), not by adding 1 after the fact.

Simulating and plotting

With the fixed code I generated the series and, rather than using the base graphics, I wrapped it in a data frame and drew it with ggplot2. I added a horizontal line at the true mean (1) so the plot makes it visually obvious whether the process is stationary:

library(forecast)
library(ggplot2)

df <- data.frame(Time = 1:length(xt), x_t = as.numeric(xt))

ggplot(df, aes(x = Time, y = x_t)) +
  geom_line() +
  geom_hline(yintercept = 1, color = "red", linetype = "dashed") +
  labs(title = "Simulated AR(1) Time Series", x = "Time", y = expression(x[t])) +
  theme_gray()
Figure: the simulated AR(1) series (fig 1 in the report).
Figure: the simulated AR(1) series (fig 1 in the report).

The series wandered around the mean of 1 and its amplitude stayed roughly constant over time, with no trend, no visible seasonality and no obvious clustering. That flatness of variance and constant mean is the signature of a stationary process, which is what the theory promises for an AR(1) when |beta| < 1.

Looking at the autocorrelation function

The companion diagnostic is the sample autocorrelation function (ACF). For a stationary AR(1) with coefficient 0.75 the ACF should decay roughly exponentially. ggAcf() from the forecast package gives the styled version:

ggAcf(xt) +
  ggtitle("ACF of Simulated AR(1) Series")
Figure: the sample ACF of the simulated AR(1) series
Figure: the sample ACF of the simulated AR(1) series

The plot showed one clearly significant bar at the first lag and then a gradual decay, with higher lags sitting inside the blue significance bounds. That exponential-looking decay with rate near 0.75 is exactly the textbook ACF of an AR(1), so the simulated data carried the expected autocorrelation structure.

Fitting the model back

I estimated the process from the data using the Yule-Walker estimator (ar.yw), forcing a single AR order:

fit <- ar.yw(xt, aic = FALSE, order.max = 1)
mu_hat    <- mean(xt)      # 0.9556
beta_hat  <- fit$ar         # 0.7201
sigma2_e_hat <- fit$var.pred

The fitted model was:

$$X_t = 0.9556 + 0.7201 \left( X_{t-1} - 0.9556 \right) + \varepsilon_t$$

The estimated beta of 0.7201 is close to the true 0.75 and the estimated mean 0.9556 is close to the true 1; the gap is just sampling variation from one simulated path. That is the sanity check I wanted: a correct estimator on correctly simulated data returns the parameters I put in.

The variance of the sample mean

Because AR(1) observations are correlated, the variance of the sample mean is not the usual sigma squared over n. Accounting for the autocorrelation, the asymptotic variance is:

$$\widehat{\mathrm{var}}(\bar{x}) = \frac{\hat{\sigma}^2_e}{n} \times \left( \frac{1}{1 - \hat{\beta}} \right)^2 $$

var_mean_hat <- (sigma2_e_hat / n) * (1 / (1 - beta_hat))^2   # 0.0268
se_mean_hat  <- sqrt(var_mean_hat)

Plugging in the estimates gave 0.0268 (standard error about 0.1637). Notice the correlation correction matters: ignoring the autocorrelation would understate the uncertainty.

A confidence interval for the true mean

With that standard error and the normal quantile $z_{0.975} = 1.96 $, a 95% confidence interval for the true mean is:

z <- 1.96
lower <- mu_hat - z * se_mean_hat
upper <- mu_hat + z * se_mean_hat
c(lower, upper)   # [0.6348, 1.276]

The interval came out to about [0.6348, 1.276], and the true mean of 1 sits comfortably inside it. That is a nice verification that the whole pipeline, from the corrected simulator through the Yule-Walker estimator to the autocorrelation-aware standard error, is behaving as the theory says it should.

Part 2. Modelling Coca-Cola return volatility with GARCH

The data

For the second half I worked with daily closing prices of Coca-Cola (ticker KO). I pulled the data with the yfR package (which reads Yahoo Finance), choosing a window from August 2020 to June 2025 because it contains no single dramatic crisis and the resulting return series is roughly stable, which is a clean setting for teaching GARCH. That gave 1225 daily points, which I saved to CSV and then reloaded:

data <- read.csv("KO_logreturns.csv")
data <- data[order(data$ref_date), ]
data$ref_date <- as.Date(data$ref_date)
data$log_ret <- c(NA, diff(log(data$price_close)))
data <- na.omit(data)

Working with log returns rather than raw prices is standard for financial data, because they are approximately additive over time and much closer to stationary than the price level itself.

Price level versus returns

Plotting the price series above the log returns immediately shows why returns, not prices, are the target of the analysis:

p11 <- ggplot(data, aes(x = ref_date, y = price_close)) + geom_line() +
  labs(title = "Coca-Cola (KO) Daily Closing Price", x = "Date", y = "Closing Price (USD)")

p12 <- ggplot(data, aes(x = ref_date, y = log_ret)) + geom_line() +
  geom_hline(yintercept = mean(data$log_ret), color = "red", linetype = "dashed") +
  labs(title = "Coca-Cola (KO) Daily Log-Returns", x = "Date", y = "Log-Return (rt)")

ggarrange(p11, p12, ncol = 1, nrow = 2)
Figure: Coca-Cola closing price (top) and daily log returns (bottom)
Figure: Coca-Cola closing price (top) and daily log returns (bottom)

The price drifts up over the four years with a clear trend, while the returns bounce around a mean close to zero with no trend. But the returns are not featureless: calm periods with small moves are followed by bursts of large moves, a pattern called volatility clustering. That clustering is the reason a model that allows the variance of returns to change over time is appropriate.

Autocorrelation of returns and of squared returns

The ACF tells us something subtle. Returns themselves should show little autocorrelation, because in an efficient market past moves should not predict future moves. But the ACF of the squared returns should show some dependence, because volatility clusters, and squared returns are a proxy for volatility:

acf_returns    <- ggAcf(data$log_ret)     + ylim(-0.2, 0.2) + ggtitle("Sample ACF of Log-Returns (KO)")
acf_sq_returns <- ggAcf(data$log_ret^2)   + ylim(-0.2, 0.2) + ggtitle("Sample ACF of Squared Log-Returns (KO)")
ggarrange(acf_returns, acf_sq_returns, ncol = 1, nrow = 2)
Figure: sample ACF of KO log returns (top) and of squared log returns (bottom)
Figure: sample ACF of KO log returns (top) and of squared log returns (bottom)

The returns ACF sits almost entirely inside the significance bounds, confirming the returns are essentially unpredictable at lag level order. The squared returns ACF shows a handful of bars crossing the bounds. That modest but real dependence in the squared series is the empirical fingerprint of volatility clustering, and it is precisely the motivation for a GARCH model.

Fitting GARCH(1,1)

I fitted a GARCH(1,1) with conditionally normal innovations using the fEGarch package:

library(fEGarch)
GARCH11 <- garch(data$log_ret, order = c(1, 1), cond_dist = "norm")
GARCH11
pars(GARCH11)

The fitted model was:

$$ Y_t = 2.86\times 10^{-4} + \varepsilon_t, \quad \varepsilon_t = \sqrt{h_t}\,\eta_t, \quad \eta_t \sim N(0, 1)$$

$$h_t = 3.08\times 10^{-6} + 0.0596\,\varepsilon_{t-1}^2 + 0.9145\,h_{t-1}$$

with estimated parameters mu = 2.86e-4, omega = 3.08e-6, alpha1 = 0.0596 and beta1 = 0.9145. The large beta (0.9145) means volatility is highly persistent, so today's variance carries heavily into tomorrow, and the sum alpha + beta is close to (but below) 1, which is what keeps the process stationary.

GJR-GARCH and the leverage effect

A standard GARCH(1,1) treats positive and negative shocks symmetrically. Finance suggests they are not symmetric: bad news tends to move volatility more than good news of the same size, the leverage effect. The GJR-GARCH model adds a term that lets the impact of a shock depend on its sign:

GJR_GARCH11 <- gjrgarch(data$log_ret, orders = c(1, 1), cond_dist = "norm")
GJR_GARCH11
pars(GJR_GARCH11)

The fitted GJR-GARCH variance equation is:

$$\sigma_t^2 = 1.9696\times 10^{-4} + 0.059\left(|\varepsilon_{t-1}| - 0.203\,\varepsilon_{t-1}\right)^2 + 0.9165\,\sigma_{t-1}^2$$

Because of the absolute value together with the sign term, the effective coefficient on the lagged squared shock depends on whether the previous return was negative or positive. Working it out by hand for the two cases gives approximately 0.0374 on a positive shock and 0.0853 on a negative shock. The negative-shock coefficient is more than twice the positive one, which is the leverage effect in the data: a drop in the stock feeds volatility about twice as hard as a rise of the same size.

Comparing the two volatility models

With both models estimated I extracted the conditional standard deviations and plotted them, first as three stacked panels (returns, GARCH volatility, GJR-GARCH volatility) and then overlaid on a single chart:

garch11_vol  <- sigt(GARCH11)       # GARCH(1,1) conditional std dev
gjr_vol      <- sigt(GJR_GARCH11)   # GJR-GARCH(1,1) conditional std dev
Figure: daily log returns and the conditional standard deviations from GARCH(1,1) and GJR-GARCH(1,1)
Figure: daily log returns and the conditional standard deviations from GARCH(1,1) and GJR-GARCH(1,1)
Figure: GARCH(1,1) and GJR-GARCH(1,1) conditional standard deviations overlaid
Figure: GARCH(1,1) and GJR-GARCH(1,1) conditional standard deviations overlaid

Both models moved in step with the returns, lifting during the volatile bursts and settling during calm patches, which confirms they capture the heteroscedasticity visible in the data. The GJR-GARCH series occasionally rose harder than GARCH(1,1) right after sharp drops, again the asymmetric response showing up in the fitted volatility rather than only in the algebra.

Forecasting volatility

The last step was forward-looking. I used the fitted GARCH(1,1) to forecast volatility out of sample, plotted the last 200 in-sample fitted values in black against the forecasts in blue:

n_forecast   <- 50                        # report figure shows 50 forecast steps
garch_pred   <- predict(GARCH11, n.ahead = n_forecast)
fitted_vol   <- as.numeric(sigt(GARCH11))
forecast_vol <- as.numeric(sigma(garch_pred))

The report's figure shows the last 200 fitted values together with the forecast. One note on the code: the course script I saved sets the forecast horizon to 500 steps, while the report figure and its caption display a shorter 50-step window; the conclusion is unchanged because the forecast converges to the same long-run level either way.

Figure: last 200 fitted and 50 forecasted GARCH(1,1) conditional standard deviations
Figure: last 200 fitted and 50 forecasted GARCH(1,1) conditional standard deviations

The forecast starts at the level where the fitted volatility ends and then converges quickly toward a constant. For a stationary GARCH(1,1), the multi-step forecast of conditional variance converges to the unconditional variance omega / (1 - alpha - beta) as the horizon grows, provided alpha + beta < 1. With the estimated parameters that long-run standard deviation is:

$$\sqrt{\frac{\omega}{1 - \alpha - \beta}} = 0.0109$$

So once the shocks stop feeding in, the model's best guess for volatility settles at that long-run level, which is a clean and interpretable end to the exercise.

The takeaway

The two halves of the project are the same discipline applied forward and backward. Simulating an AR(1), checking its ACF and fitting it back taught me to sanity-check an estimator against the parameters I put in. Taking real stock returns and fitting GARCH taught me to read a return series, justify a conditional-variance model from the data, and let a model quantify risk through volatility and forecast it. Together they cover the core toolkit of applied time series: generating data, describing dependence, estimating, and predicting. These are course exercises on simulated and historical data; the parameter values are what the models estimated on that data, not claims about the future.

Tools: R, forecast, ggplot2, fEGarch, yfR.

I wrote the analysis and the report text for the problems covered here as part of the summer 2025 course project. The reproducible pipeline lives in the R scripts. Repo Github

References Tsay, R. S. (2010). Analysis of financial time series (3rd ed.). John Wiley & Sons.