This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.
I used AI tools to assist in creating and recreating the original R Markdown (RMD) file for this project. AI was also used to help organize the code, improve documentation, and troubleshoot potential errors. The analysis, interpretation of results, and final review were conducted to ensure the accuracy and relevance of the project.
The objective of this project is to explore how major events, such as corporate announcements, earnings releases, economic indicators, product launches, and breaking news, influence stock market performance. Using R programming, we can collect and analyze historical stock market data, identify significant events, measure stock price reactions, and evaluate potential trading opportunities.
R and Plotly are used across industries, including by major organizations such as Amway and Pfizer and many others, to support data analytics, research, BI and visualization, app or API design and execution, and data-driven decision-making. These tools provide students with exposure to technologies relevant to real-world business analytics.
R is a powerful, open-source programming language and statistical computing environment widely used for data analysis, statistical modeling, and data visualization. It enables users to collect, clean, analyze, and visualize data while supporting a wide range of applications, including marketing analytics, financial analysis, and predictive modeling.
Plotly is an interactive data visualization library that allows users to create dynamic, web-based charts and dashboards using R. With Plotly, users can explore data through interactive features such as zooming, hovering over data points, filtering, and selecting specific observations.
Why use R and Plotly together?
library(quantmod)
## Loading required package: xts
## Loading required package: zoo
##
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
##
## as.Date, as.Date.numeric
## Loading required package: TTR
## Warning: package 'TTR' was built under R version 4.3.3
## Registered S3 method overwritten by 'quantmod':
## method from
## as.zoo.data.frame zoo
library(dplyr)
## Warning: package 'dplyr' was built under R version 4.3.3
##
## ######################### Warning from 'xts' package ##########################
## # #
## # The dplyr lag() function breaks how base R's lag() function is supposed to #
## # work, which breaks lag(my_xts). Calls to lag(my_xts) that you type or #
## # source() into this session won't work correctly. #
## # #
## # Use stats::lag() to make sure you're not using dplyr::lag(), or you can add #
## # conflictRules('dplyr', exclude = 'lag') to your .Rprofile to stop #
## # dplyr from breaking base R's lag() function. #
## # #
## # Code in packages is not affected. It's protected by R's namespace mechanism #
## # Set `options(xts.warn_dplyr_breaks_lag = FALSE)` to suppress this warning. #
## # #
## ###############################################################################
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:xts':
##
## first, last
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(tidyr)
library(purrr)
library(tibble)
library(lubridate)
##
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
##
## date, intersect, setdiff, union
library(plotly)
## Loading required package: ggplot2
##
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
##
## last_plot
## The following object is masked from 'package:stats':
##
## filter
## The following object is masked from 'package:graphics':
##
## layout
ticker_a <- "NFLX"
ticker_b <- "DIS"
tickers <- c(ticker_a, ticker_b)
event_date <- as.Date("2022-04-20")
event_desc <- "Netflix Q1 2022 earnings: first subscriber loss in a decade"
start_date <- event_date - 120 # about 4 months before
end_date <- event_date + 60 # about 2 months after
dir.create("cache", showWarnings = FALSE)
cache_file <- "cache/prices_event.rds"
get_prices <- function(symbol, from, to) {
xt <- getSymbols(symbol, src = "yahoo", from = from, to = to, auto.assign = FALSE)
tibble(
date = as.Date(index(xt)),
symbol = symbol,
open = as.numeric(Op(xt)),
high = as.numeric(Hi(xt)),
low = as.numeric(Lo(xt)),
close = as.numeric(Cl(xt)),
adjusted = as.numeric(Ad(xt)),
volume = as.numeric(Vo(xt))
)
}
if (file.exists(cache_file)) {
prices <- readRDS(cache_file)
} else {
prices <- map_dfr(tickers, get_prices, from = start_date, to = end_date)
saveRDS(prices, cache_file)
}
prices %>%
group_by(symbol) %>%
summarise(
first_date = min(date),
last_date = max(date),
n_days = n(),
n_missing = sum(is.na(adjusted)),
.groups = "drop"
)
## # A tibble: 2 × 5
## symbol first_date last_date n_days n_missing
## <chr> <date> <date> <int> <int>
## 1 DIS 2021-12-21 2022-06-17 124 0
## 2 NFLX 2021-12-21 2022-06-17 124 0
# Relative trading-day index: day 0 = first trading day on or after event_date
all_dates <- sort(unique(prices$date))
event_td <- all_dates[all_dates >= event_date][1]
event_idx <- match(event_td, all_dates)
rel_days <- tibble(date = all_dates, rel_day = seq_along(all_dates) - event_idx)
d <- prices %>%
arrange(symbol, date) %>%
group_by(symbol) %>%
mutate(
ret = adjusted / lag(adjusted) - 1,
index = adjusted / first(adjusted) * 100
) %>%
ungroup() %>%
left_join(rel_days, by = "date")
event_td
## [1] "2022-04-20"
y_max <- max(d$index, na.rm = TRUE)
plot_ly(d, x = ~date, y = ~index, color = ~symbol,
type = "scatter", mode = "lines",
hovertemplate = "%{x|%b %d, %Y}<br>Index: %{y:.1f}<extra>%{fullData.name}</extra>") %>%
layout(
title = paste0("Normalized performance (start = 100)<br><sup>", event_desc, "</sup>"),
xaxis = list(title = ""),
yaxis = list(title = "Index (start = 100)"),
legend = list(orientation = "h", y = -0.15),
hovermode = "x unified",
shapes = list(list(
type = "line", x0 = event_td, x1 = event_td, y0 = 0, y1 = 1, yref = "paper",
line = list(color = "black", dash = "dash", width = 1.5)
)),
annotations = list(list(
x = event_td, y = 1, yref = "paper", text = "Event",
showarrow = FALSE, xanchor = "left", yanchor = "top"
))
)
window_d <- d %>% filter(rel_day >= -5, rel_day <= 5)
plot_ly(window_d, x = ~rel_day, y = ~ret * 100, color = ~symbol, type = "bar",
hovertemplate = "Day %{x}<br>Return: %{y:.2f}%<extra>%{fullData.name}</extra>") %>%
layout(
barmode = "group",
title = "Daily returns around the event (day 0 = first trading day of reaction)",
xaxis = list(title = "Trading days relative to event", dtick = 1),
yaxis = list(title = "Daily return (%)"),
legend = list(orientation = "h", y = -0.2)
)
cum_ret <- function(df, from, to, label) {
df %>%
filter(rel_day >= from, rel_day <= to) %>%
group_by(symbol) %>%
summarise(cum_return = prod(1 + ret) - 1, .groups = "drop") %>%
mutate(window = label)
}
res <- bind_rows(
cum_ret(d, 0, 0, "Day 0"),
cum_ret(d, -1, 5, "Day -1 to +5")
)
res_wide <- res %>%
pivot_wider(names_from = symbol, values_from = cum_return) %>%
mutate(
difference = .data[[ticker_a]] - .data[[ticker_b]],
across(-window, ~ round(.x * 100, 2))
)
knitr::kable(res_wide,
caption = "Cumulative returns (%) and difference (A minus B)")
| window | DIS | NFLX | difference |
|---|---|---|---|
| Day 0 | -5.56 | -35.12 | -29.56 |
| Day -1 to +5 | -9.83 | -44.20 | -34.37 |
vol_check <- d %>%
group_by(symbol) %>%
summarise(
avg_vol_prior_30d = mean(volume[rel_day >= -30 & rel_day <= -1], na.rm = TRUE),
event_day_volume = volume[rel_day == 0],
ratio = event_day_volume / avg_vol_prior_30d,
.groups = "drop"
)
vol_check
## # A tibble: 2 × 4
## symbol avg_vol_prior_30d event_day_volume ratio
## <chr> <dbl> <dbl> <dbl>
## 1 DIS 9500160 36465700 3.84
## 2 NFLX 54710533. 1333875000 24.4
nv_tickers <- c("NVDA", "AMD")
nv_start <- as.Date("2026-09-01")
nv_end <- Sys.Date() + 1 # include today if available
# Event dates are the FIRST TRADING DAY on which the market could react.
nv_events <- tibble(
date = as.Date(c("2026-11-09", "2026-11-12", "2026-11-18")),
label = c("Board opens investigation",
"Huang resigns; Kress interim CEO",
"Q3 FY27 earnings reaction")
)
# Cache by date so the data refreshes daily but a single knit does not re-scrape repeatedly
nv_cache <- file.path("cache", paste0("nv_prices_", Sys.Date(), ".rds"))
if (file.exists(nv_cache)) {
nv_prices <- readRDS(nv_cache)
} else {
nv_prices <- map_dfr(nv_tickers, get_prices, from = nv_start, to = nv_end)
saveRDS(nv_prices, nv_cache)
}
nv_prices %>%
group_by(symbol) %>%
summarise(first_date = min(date), last_date = max(date), n_days = n(), .groups = "drop")
## # A tibble: 2 × 4
## symbol first_date last_date n_days
## <chr> <date> <date> <int>
## 1 AMD 2026-09-01 2026-11-19 57
## 2 NVDA 2026-09-01 2026-11-19 57
# Base date = last trading day BEFORE the first news date (so index = 100 means "before the story broke")
nv_base <- max(nv_prices$date[nv_prices$date < min(nv_events$date)])
nv <- nv_prices %>%
arrange(symbol, date) %>%
group_by(symbol) %>%
mutate(
prev_close = lag(close),
gap = open / prev_close - 1, # overnight gap (matters for pre-market news)
ret = adjusted / lag(adjusted) - 1, # close-to-close return
index = adjusted / adjusted[date == nv_base] * 100
) %>%
ungroup() %>%
filter(date >= nv_base - 10)
nv_base
## [1] "2026-11-06"
# One vertical line and label per event; labels are staggered so they do not overlap
nv_shapes <- lapply(seq_len(nrow(nv_events)), function(i) {
list(type = "line",
x0 = as.character(nv_events$date[i]), x1 = as.character(nv_events$date[i]),
y0 = 0, y1 = 1, yref = "paper",
line = list(color = "black", dash = "dash", width = 1.2))
})
nv_notes <- lapply(seq_len(nrow(nv_events)), function(i) {
list(x = as.character(nv_events$date[i]),
y = c(1.00, 0.90, 1.00)[i], yref = "paper",
text = nv_events$label[i], showarrow = FALSE,
xanchor = "left", yanchor = "top", font = list(size = 11))
})
plot_ly(nv, x = ~date, y = ~index, color = ~symbol,
colors = c(AMD = "#d62728", NVDA = "#2ca02c"),
type = "scatter", mode = "lines+markers",
hovertemplate = "%{x|%a %b %d, %Y}<br>Index: %{y:.1f}<extra>%{fullData.name}</extra>") %>%
layout(
title = paste0("Nvidia CEO departure: NVDA vs. AMD<br><sup>Indexed to 100 at the close on ",
format(nv_base, "%b %d, %Y"), " (last close before the news)</sup>"),
xaxis = list(title = "", rangebreaks = list(list(bounds = c("sat", "mon")))),
yaxis = list(title = "Index (pre-news close = 100)"),
legend = list(orientation = "h", y = -0.15),
hovermode = "x unified",
shapes = nv_shapes,
annotations = nv_notes
)
The rangebreaks setting removes weekend gaps so the
lines are not stretched across non-trading days.
nv_tbl <- nv %>%
filter(date %in% nv_events$date) %>%
left_join(nv_events, by = "date") %>%
transmute(
event = label, date, symbol,
`open gap (%)` = round(gap * 100, 1),
`close-to-close (%)` = round(ret * 100, 1)
) %>%
arrange(date, symbol)
knitr::kable(nv_tbl, caption = "Reaction on each event date: overnight gap vs. full-day return")
| event | date | symbol | open gap (%) | close-to-close (%) |
|---|---|---|---|---|
| Board opens investigation | 2026-11-09 | AMD | 5.4 | 13.3 |
| Board opens investigation | 2026-11-09 | NVDA | -7.3 | -4.3 |
| Huang resigns; Kress interim CEO | 2026-11-12 | AMD | 3.0 | 5.9 |
| Huang resigns; Kress interim CEO | 2026-11-12 | NVDA | -13.1 | -4.3 |
| Q3 FY27 earnings reaction | 2026-11-18 | AMD | 1.3 | 5.3 |
| Q3 FY27 earnings reaction | 2026-11-18 | NVDA | 2.4 | -2.9 |