Markets

Introduction

In this chapter, we will import daily stock market price data via an R package and then wrangle that daily price data into various return series, including future returns. We will also cover some exploratory visualizations that make use of the ggplot2 tools covered in the previous chapter. We also explore a more advanced use case, where we color returns by whether they occurred in a bear market or a bull market. That bear and bull encoding will probably be new material even for experienced R and finance users and it has broad applicability to visualizing returns in different time periods. If you are new to R, the bear market section might be too involved but for the brave it offers a programmatic way to identify market regimes.

Let’s load our packages and get to work importing market data.

library(tidyverse)
library(tidyquant)
library(timetk)
library(readxl)
library(scales)
library(fredr)
library(janitor)

Importing Market Data

Prices to Returns

Alternate Method for Adding Date Features

Future Calendar-Based Returns

More Advanced Use Case: Bear Markets

Manual Process for Identifying Bear Markets

Programmatic Process for Identifying Bear Markets

Conclusion