This guide outlines the process for calculating and evaluating the Sharpe ratio of selected firms using RStudio. We will retrieve stock price data, calculate holding period returns (HPR), summarize statistics, and compute Sharpe ratios using a monthly risk-free rate.

Getting Started

Before we can calculate the Sharpe ratio of a firm, we must import pricing data into our environment.

First, load the tidyquant and dplyr packages in R using library()

The tq_get function can retrieve stock prices, and economic data published from FRED

library(tidyquant)
library(dplyr)

tech_tickers <- c("AAPL", "NVDA", "MSFT", "AMZN", "META")

tech_prices <- tq_get(tech_tickers, get = "stock.prices" , from = "YYYY-MM-DD", to = "YYYY-MM-DD")

Now that pricing data has been loaded into our environment, we are ready to manipulate the data in order to perform the necessary calculations to find the Sharpe Ratio.

Calculate Holding Period Returns

Mutate the data in order to calculate monthly holding period returns.

Be sure to filter out any missing observations as this could make


tech_prices <- tech_prices %>%
  group_by(symbol) %>%
  mutate(lag_adjusted = lag(adjusted)) %>%
  mutate(HPR = (adjusted - lag_adjusted)/lag_adjusted) %>%
  ungroup()

Once the data is imported, we calculate monthly holding period returns (HPR) for each ticker. This involves lagging the adjusted closing price to compute returns:

tech_prices <- tech_prices %>%
  group_by(symbol) %>%
  mutate(lag_adjusted = lag(adjusted),
         HPR = (adjusted - lag_adjusted) / lag_adjusted) %>%
  ungroup()

Next, we remove any rows containing missing HPR values:

tech_prices <- tech_prices %>%
  filter(!is.na(HPR))

Summary Statistics

We can now compute summary statistics for each company, including the mean, standard deviation, maximum, and minimum of HPR:

summary_stats <- tech_prices %>%
  group_by(symbol) %>%
  summarize(
    mean_HPR = mean(HPR),
    stdev_HPR = sd(HPR),
    max_HPR = max(HPR),
    min_HPR = min(HPR)
  ) %>%
  ungroup()

Calculating the Sharpe

The Sharpe ratio is calculated as the excess return over the risk-free rate, divided by the standard deviation of returns.