LA1 – Course Project

Author

1NT23IS065 - Chirantana R. Gowda | 1NT23IS080 - Harsh Deep B Nair

Team 4

Create an animated time-series plot for stock price changes over time for 5 companies.

Step 1: Load the required libraries

library(data.table)  # For fast reading of large CSV files
library(dplyr)       # For filtering and transforming data

Attaching package: 'dplyr'
The following objects are masked from 'package:data.table':

    between, 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(ggplot2)     # For creating the base plots
library(gganimate)   # For animating ggplot2 visualizations
library(gifski)      # For rendering and saving the animation as a GIF
library(transformr)  # Required for smooth transitions in gganimate

Step 2: Load and explore the dataset

# Load the stock prices dataset from CSV file
# Make sure the file is in the working directory
stocks_data <- fread("World-Stock-Prices-Dataset.csv")
head(stocks_data)   # Displays the first 6 rows
                  Date    Open    High     Low   Close   Volume Dividends
                <POSc>   <num>   <num>   <num>   <num>    <num>     <num>
1: 2025-05-05 04:00:00   6.730   7.140   6.590   6.890 16916400         0
2: 2025-05-05 04:00:00  99.000 102.050  98.760 100.590 41181000         0
3: 2025-05-05 04:00:00 118.390 118.540 116.650 117.200    47600         0
4: 2025-05-05 04:00:00 275.460 281.590 274.080 278.030  2416300         0
5: 2025-05-05 04:00:00  27.278  27.278  27.278  27.278      100         0
6: 2025-05-05 04:00:00 347.000 351.050 346.120 348.640  3864500         0
   Stock Splits       Brand_Name Ticker Industry_Tag Country Capital Gains
          <num>           <char> <char>       <char>  <char>         <num>
1:            0          peloton   PTON      fitness     usa            NA
2:            0              amd    AMD   technology     usa            NA
3:            0           adidas  ADDYY      apparel germany            NA
4:            0 american express    AXP      finance     usa            NA
5:            0             puma  PMMAF      apparel germany            NA
6:            0             visa      V      finance     usa            NA
str(stocks_data)    # Shows the structure of the dataset
Classes 'data.table' and 'data.frame':  307435 obs. of  13 variables:
 $ Date         : POSIXct, format: "2025-05-05 04:00:00" "2025-05-05 04:00:00" ...
 $ Open         : num  6.73 99 118.39 275.46 27.28 ...
 $ High         : num  7.14 102.05 118.54 281.59 27.28 ...
 $ Low          : num  6.59 98.76 116.65 274.08 27.28 ...
 $ Close        : num  6.89 100.59 117.2 278.03 27.28 ...
 $ Volume       : num  16916400 41181000 47600 2416300 100 ...
 $ Dividends    : num  0 0 0 0 0 0 0 0 0 0 ...
 $ Stock Splits : num  0 0 0 0 0 0 0 0 0 0 ...
 $ Brand_Name   : chr  "peloton" "amd" "adidas" "american express" ...
 $ Ticker       : chr  "PTON" "AMD" "ADDYY" "AXP" ...
 $ Industry_Tag : chr  "fitness" "technology" "apparel" "finance" ...
 $ Country      : chr  "usa" "usa" "germany" "usa" ...
 $ Capital Gains: num  NA NA NA NA NA NA NA NA NA NA ...
 - attr(*, ".internal.selfref")=<externalptr> 
names(stocks_data)  # Lists the names of all columns
 [1] "Date"          "Open"          "High"          "Low"          
 [5] "Close"         "Volume"        "Dividends"     "Stock Splits" 
 [9] "Brand_Name"    "Ticker"        "Industry_Tag"  "Country"      
[13] "Capital Gains"

Step 3: Filter and mutate the data

# Convert the 'Date' column to Date format (from character or factor)
stocks_data$Date <- as.Date(stocks_data$Date)

# Define the list of selected company tickers
selected_tickers <- c("AAPL", "GOOGL", "MSFT", "AMZN", "TSLA")

# Filter the dataset for those companies and create a combined label
stocks_subset <- stocks_data %>%
  filter(Ticker %in% selected_tickers) %>%
  mutate(Label = paste0(Brand_Name, " (", Ticker, ")"))

Step 4: Create animated time-series plot

# Create the animated plot
gif_path <- "stock_animation.gif"

if (!file.exists(gif_path)) {
p <- ggplot(stocks_subset, aes(x = Date, y = Close, color = Label)) +
  geom_line(size = 1.2) +                                             
  labs(
    title = "Stock Price Over Time",    # Main title of the plot               
    subtitle = "Date: {frame_along}",   # Subtitle updates dynamically
    x = "Date",                         # X-axis label
    y = "Closing Price (USD)",          # Y-axis label
    color = "Company"                   # Legend title
  ) +
  theme_minimal(base_size = 14) +       # Clean and modern minimal theme
  transition_reveal(along = Date)       # Animate the line drawing along the 'Date' variable

# Animate and save
animate(
  p,                        # The plot object to animate
  width = 900,              # Width of the output GIF in pixels
  height = 550,             # Height of the output GIF in pixels
  duration = 20,            # Total duration of the animation in seconds
  fps = 25,                 # Frames per second
  renderer = gifski_renderer("stock_animation.gif")
)
}

Below is the stock price animation:

knitr::include_graphics("stock_animation.gif")