# 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()
Portfolio Optimization
Chapter 3 - Financial Data: IID Modeling
R code
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:
IID model
Example of a synthetic Gaussian i.i.d. time series:
library(mvtnorm)
# get realistic mu and variance
<- SP500_2015to2020$index
sp500_prices <- diff(log(sp500_prices))[-1]
sp500_returns <- mean(sp500_returns)
mu <- var(sp500_returns)
var
# generate synthetic data
set.seed(42)
<- 500
T <- rmvnorm(n = T, mean = mu, sigma = var)
x
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)