Portfolio Optimization
Chapter 15: Pairs Trading Portfolios

R code

Published

November 17, 2024

R code examples for Chapter 15 of the book:

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

Loading packages

First load the packages used in the examples:

# basic finance
library(xts)                    # to manipulate time series of stock data
library(portfolioBacktest)      # to conduct backtests
library(pob)                    # book package with financial data
library(quantmod)               # to download market data from the Internet
library(TTR)                    # generation of signals

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

# cointegration
library(egcm)
library(urca)

# modeling
library(MARSS)                  # state space modeling and Kalman

Introduction

Stationarity

Stationarity refers to the property that the statistics of a time series remain fixed over time. In that sense, a stationary time series can be considered mean-reverting.

Example of a random walk (nonstationary time series with unit root):

Code
# generate synthetic data
T <- 200
set.seed(421)
y <- rep(0, T)
for (i in 2:T)
  y[i] <- y[i-1] + rnorm(1)

data.frame("t" = 1:T, "y" = y) |>
  ggplot(aes(x = t, y = y)) +
  geom_line(linewidth = 1, color = "blue") +
  labs(title = "Random walk", y = NULL)