# 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)
Portfolio Optimization
Chapter 4 - Financial Data: Time Series Modeling
R code
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:
Temporal structure
Example of a synthetic Gaussian AR(1) time series:
library(rugarch)
# specify an AR(1) model with given coefficients and parameters
<- arfimaspec(mean.model = list(armaOrder = c(1,0), include.mean = TRUE),
arma_fixed_spec fixed.pars = list(mu = 0.01, ar1 = -0.9, sigma = 0.2))
# simulate one path
<- 300
T set.seed(42)
<- arfimapath(arma_fixed_spec, n.sim = T)
path_arma <- path_arma@path$seriesSim
x
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")