# Load packages
library(tidyverse)
library(tidyquant)
library(timetk)
library(PerformanceAnalytics)

Goal

Visualize and examine changes in the underlying trend in the performance of your portfolio in terms of Sharpe Ratio.

1. Import stock prices

symbols <- c("AAPL", "MSFT", "GOOG", "AMZN", "TSLA", "NFLX")

prices <- tq_get(
  x = symbols,
  get = "stock.prices",
  from = "2012-12-31",
  to   = "2022-12-31"
)

2. Convert to monthly log returns

asset_returns_tbl <- prices %>%
  group_by(symbol) %>%
  tq_transmute(
    select = adjusted,
    mutate_fun = periodReturn,
    period = "monthly",
    type = "log"
  ) %>%
  ungroup()

3. Assign weights

weights <- c(0.20, 0.15, 0.20, 0.15, 0.15, 0.15)

4. Build portfolio

portfolio_returns_tbl <- asset_returns_tbl %>%
  tq_portfolio(
    assets_col = symbol,
    returns_col = monthly.returns,
    weights = weights,
    col_rename = "returns"
  )

5. Compute Rolling Sharpe Ratio

window <- 24
risk_free_rate <- 0.0003

calculate_rolling_sharpe <- function(data) {
  SharpeRatio(
    R  = data,
    Rf = risk_free_rate,
    FUN = "StdDev"
  )
}

portfolio_xts <- portfolio_returns_tbl %>%
  mutate(date = as.Date(date)) %>%
  tk_xts(select = returns, date_var = date)

rolling_sharpe_xts <- rollapply(
  data = portfolio_xts,
  width = window,
  FUN = calculate_rolling_sharpe,
  by.column = FALSE,
  align = "right"
)

rolling_sharpe_tbl <- tk_tbl(rolling_sharpe_xts, rename_index = "date") %>%
  rename(rolling_sharpe = value) %>%
  drop_na()

6. Plot Rolling Sharpe Ratio

rolling_sharpe_tbl %>%
  ggplot(aes(x = date, y = rolling_sharpe)) +
  geom_line(color = "cornflowerblue") +
  labs(
    x = NULL,
    y = "Rolling Sharpe Ratio",
    title = paste0("Rolling ", window, "-Month Sharpe Ratio")
  ) +
  annotate(
    "text",
    x = as.Date("2016-06-01"),
    y = 0.5,
    label = "This portfolio has done quite well since early 2016",
    color = "red",
    size = 5
  ) +
  theme_minimal()

Reflection

The portfolio’s performance improved around 2016 and shown by a rise in the sharpe ratio plot. Before that returns adjusted for risk were low or negative. This change may show broad market recovery or tech growth at the time.