Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ################################################################################
- ### Compare the relative performance of assets from a given start date
- ### Use the Yahoo ticker for the assets you wish to graph
- ################################################################################
- library(tidyverse)
- library(RColorBrewer)
- # Start/end dates
- date_start <- as.Date("2025-01-20")
- date_end <- as.Date(Sys.Date())
- # Tickers of the assets to graph
- tickers <-
- tibble::tribble(
- ~symbol, ~label,
- "FSAGX", "Fidelity Select Gold Fund",
- "GC=F", "Price of Gold",
- "BRK-B", "Berkshire Hathaway",
- "FUAMX", "Fidelity Intermediate Treasury Fund",
- "DX-Y.NYB", "US Dollar Index",
- "^SPX", "S&P 500"
- ) %>%
- mutate(label = paste("[", symbol, "] - ", label, sep = ""))
- # Fetch prices for the chosen tickers
- prices <-
- tidyquant::tq_get(tickers$symbol, get = "stock.prices", from = date_start, to = date_end) %>%
- select(symbol, date, close) %>%
- pivot_wider(id_cols = "date", names_from = "symbol", values_from = "close") %>%
- arrange(date) %>%
- tsibble::as_tsibble() %>%
- tsibble::fill_gaps() %>%
- mutate(across(!starts_with("date"), forecast::na.interp))
- # Normalize stock price changes relative to date_start
- rel <-
- prices %>%
- mutate_if(is.numeric, ~ . / first(., order_by = date), na.rm = TRUE) %>%
- pivot_longer(-date, names_to = "symbol", values_to = "price")
- # Make a tibble of final values to help us label them
- labels <-
- rel %>%
- pivot_wider(id_cols = "date", names_from = "symbol", values_from = "price") %>%
- filter(!if_all(-date, is.na)) %>%
- tail(n = 1) %>%
- pivot_longer(-date, names_to = "symbol", values_to = "price") %>%
- left_join(tickers, by = "symbol") %>%
- mutate(
- price_txt = ifelse(price > 1, paste("(+", round(100 * (price - 1), 1), "%)", sep = ""),
- paste("(-", round(100 * (1 - price), 1), "%)", sep = "")))
- # Make shiny graph...
- ggplot() +
- theme_bw() +
- theme(legend.position = "none") +
- geom_line(data = rel, aes(x = date, y = price, color = symbol)) +
- geom_hline(yintercept = 1, linetype = "dotted") +
- scale_x_date(breaks = scales::pretty_breaks(10), limits = c(date_start, date_end + days(60))) +
- scale_y_continuous(breaks = scales::pretty_breaks(10), labels = scales::label_number(suffix = "x")) +
- scale_color_brewer(palette = "Dark2") +
- geom_label(data = labels, hjust = 0, aes(x = date + 0.03 * (date_end - date_start), y = price, label = paste(label, " ", price_txt, sep = ""), color = symbol)) +
- labs(x = "", y = "Performance", title = paste("Asset performance relative to", date_start))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement