Anomaly Detection of the S&P 500

R-bloggers 2025-01-29

[This article was first published on DataGeeek, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Since the date the Bank of Japan (BoJ) increased the interest rate, there seems to have yet been tested an anomaly for the S&P 500 despite the strategists saying it is overvalued.

Source code:

library(tidyverse)
library(tidyquant)
library(timetk)

#S&P 500 (^GSPC)
df_sp500 <- 
  tq_get("^GSPC")


#Anomaly Plot
df_sp500 %>% 
  filter(date >= as.Date("2024-01-22")) %>% 
  anomalize(date, close) %>% 
  plot_anomalies(date, 
                 .line_size = 1,
                 .interactive = FALSE,
                 .title = "<span style= 'color:red;'>Anomaly</span> Chart of the S&P 500") + 
  scale_x_date(breaks = seq(make_date(2024,1,22), 
                            make_date(2025,1,22), 
                            by = "month"),
               labels = scales::label_date("%b'%y")) +
  scale_y_continuous(labels = scales::label_currency()) +
  geom_vline(xintercept = as.Date("2024-07-31"), 
             size = 1, 
             linetype= "dashed", 
             color = "orange") +
  labs(subtitle = "<span style ='color:orange;'>The BoJ increased the interest rate</span>") +
  theme_minimal(base_family = "Roboto Slab") +
  theme(legend.position = "none",
        panel.grid = element_blank(),
        axis.text = element_text(face = "bold", size = 16),
        axis.text.x = element_text(angle = 60, hjust = 1, vjust = 1),
        plot.background = element_rect(fill = "snow", color = "snow"),
        panel.grid.major.x = element_line(linetype = "dashed", color = "gray"),
        panel.grid.major.y = element_line(linetype = "dashed", color = "gray"),
        plot.subtitle = ggtext::element_markdown(size = 18),
        plot.title = ggtext::element_markdown(size = 20, face = "bold"))

To leave a comment for the author, please follow the link and comment on their blog: DataGeeek.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Continue reading: Anomaly Detection of the S&P 500