Portfolio Optimization
Chapter 3 - Financial Data: IID Modeling

R code

Published

October 12, 2024

R code examples for Chapter 3 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(mvtnorm)                # to generate heavy-tailed data
library(fitHeavyTail)           # to fit heavy-tailed distributions
library(ICSNP)                  # to calculate spatial mean
library(covFactorModel)         # factor model estimation
                                # devtools::install_github("dppalomar/covFactorModel")

# plotting
library(ggplot2)                # for nice plots
library(patchwork)              # for combining plots
library(reshape2)               # to reshape data
library(dplyr); conflictRules('dplyr', exclude = 'lag'); options(xts.warn_dplyr_breaks_lag = FALSE)
library(scales)
library(latex2exp)              # for latex symbols with TeX()

IID model

Example of a synthetic Gaussian i.i.d. time series:

library(mvtnorm)

# get realistic mu and variance
sp500_prices <- SP500_2015to2020$index
sp500_returns <- diff(log(sp500_prices))[-1]
mu <- mean(sp500_returns)
var <- var(sp500_returns)

# generate synthetic data 
set.seed(42)
T <- 500
x <- rmvnorm(n = T, mean = mu, sigma = var)

data.frame(t = 1:T, x = x) |>
  ggplot(aes(x = t, y = x)) +
  geom_line(linewidth = 0.8, color = "blue", show.legend = FALSE) +
  labs(title = "i.i.d. time series", x = NULL, y = NULL)