Portfolio Optimization
Chapter 4 - Financial Data: Time Series Modeling

R code

Published

October 1, 2024

R code examples for Chapter 4 of the book:

Daniel P. Palomar (2024). Portfolio Optimization: Theory and Application. Cambridge University Press.

Loading packages

The following packages are used in the examples:

# basic finance
library(xts)                    # to manipulate time series of stock data
library(pob)                    # book package with financial data
                                # install with: devtools::install_github("dppalomar/pob")

# data
library(RcppRoll)               # rolling methods
library(TTR)                    # exponentially moving average
library(rugarch)                # time series models
library(MARSS)                  # Kalman
library(stochvol)               # to compute volatility envelope

# plotting
library(ggplot2)                # for nice plots
library(patchwork)              # for combining plots
library(scales)

Temporal structure

Example of a synthetic Gaussian AR(1) time series:

library(rugarch)

# specify an AR(1) model with given coefficients and parameters
arma_fixed_spec <- arfimaspec(mean.model = list(armaOrder = c(1,0), include.mean = TRUE), 
                              fixed.pars = list(mu = 0.01, ar1 = -0.9, sigma = 0.2))

# simulate one path
T <- 300
set.seed(42)
path_arma <- arfimapath(arma_fixed_spec, n.sim = T)
x <- path_arma@path$seriesSim

data.frame(t = 1:T, x = x) |>
  ggplot(aes(x = t, y = x)) +
  geom_line(linewidth = 0.8, color = "blue", show.legend = FALSE) +
  xlab(element_blank()) + ylab(element_blank()) + ggtitle("AR(1) time series")