# basic finance
library(xts) # to manipulate time series of stock data
library(quantmod) # to download stock data
library(pob) # book package with financial data
# install with: devtools::install_github("dppalomar/pob")
library(stochvol) # to compute volatility envelope
# plotting
library(ggplot2) # for nice plots
library(patchwork) # for combining plots
library(viridisLite) # for nice colors
library(reshape2) # to reshape data
Portfolio Optimization
Chapter 2 - Financial Data: Stylized Facts
R code
R code examples for Chapter 2 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:
Prices and returns
Price time series of S&P 500:
# get data from Yahoo!Finance
library(quantmod)
<- Ad(getSymbols("^GSPC", from = "2007-01-01", to = "2022-11-04", auto.assign = FALSE))
sp500_prices
ggplot(fortify(sp500_prices, melt = TRUE), aes(x = Index, y = Value)) +
geom_line(linewidth = 0.8, color = "blue", show.legend = FALSE) +
scale_x_date(date_breaks = "1 year", date_labels = "%Y", date_minor_breaks = "1 month") +
scale_y_log10() +
xlab(element_blank()) + ylab(element_blank()) + ggtitle("S&P 500 price")