# Install necessary packages (if not already installed)
install.packages("quantmod")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.4'
## (as 'lib' is unspecified)
install.packages("ggplot2")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.4'
## (as 'lib' is unspecified)
install.packages("PerformanceAnalytics")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.4'
## (as 'lib' is unspecified)
install.packages("TTR")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.4'
## (as 'lib' is unspecified)
# Load required libraries
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
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
library(ggplot2)
library(PerformanceAnalytics)
## 
## Attaching package: 'PerformanceAnalytics'
## The following object is masked from 'package:graphics':
## 
##     legend
library(TTR)

# Define the date range for 2022
start_date <- as.Date("2022-01-01")
end_date <- as.Date("2022-12-31")

# Retrieve Tesla stock data from Yahoo Finance
getSymbols("TSLA", src = "yahoo", from = start_date, to = end_date)
## [1] "TSLA"
# Convert to dataframe for visualization
tsla_data <- data.frame(Date = index(TSLA), coredata(TSLA))

# ---- 1️⃣ Tesla Stock Closing Price Over Time ----
ggplot(tsla_data, aes(x = Date, y = TSLA.Close)) +
  geom_line(color = "blue") +
  labs(title = "Tesla Closing Stock Prices in 2022",
       x = "Date",
       y = "Closing Price (USD)") +
  theme_minimal()

# ---- 2️⃣ Tesla Daily Returns ----
tsla_data$Daily_Returns <- dailyReturn(TSLA$TSLA.Adjusted)

ggplot(tsla_data, aes(x = Date, y = Daily_Returns)) +
  geom_line(color = "red") +
  labs(title = "Tesla Daily Returns in 2022",
       x = "Date",
       y = "Daily Returns") +
  theme_minimal()
## Don't know how to automatically pick scale for object of type <xts/zoo>.
## Defaulting to continuous.

# ---- 3️⃣ Histogram of Tesla Daily Returns ----
ggplot(tsla_data, aes(x = Daily_Returns)) +
  geom_histogram(binwidth = 0.01, fill = "steelblue", color = "black") +
  labs(title = "Histogram of Tesla Daily Returns (2022)",
       x = "Daily Returns",
       y = "Frequency") +
  theme_minimal()
## Don't know how to automatically pick scale for object of type <xts/zoo>.
## Defaulting to continuous.

# ---- 4️⃣ Moving Averages (50-day & 200-day) ----
tsla_data$MA50 <- SMA(tsla_data$TSLA.Close, n = 50)
tsla_data$MA200 <- SMA(tsla_data$TSLA.Close, n = 200)

ggplot(tsla_data, aes(x = Date)) +
  geom_line(aes(y = TSLA.Close, color = "Closing Price")) +
  geom_line(aes(y = MA50, color = "50-day MA")) +
  geom_line(aes(y = MA200, color = "200-day MA")) +
  labs(title = "Tesla Stock with Moving Averages (2022)",
       x = "Date",
       y = "Price (USD)") +
  scale_color_manual(values = c("Closing Price" = "black", "50-day MA" = "blue", "200-day MA" = "red")) +
  theme_minimal()
## Warning: Removed 49 rows containing missing values or values outside the scale range
## (`geom_line()`).
## Warning: Removed 199 rows containing missing values or values outside the scale range
## (`geom_line()`).

# ---- 5️⃣ Tesla Stock Volatility (Bollinger Bands) ----
bollinger <- BBands(TSLA[, "TSLA.Close"], n = 20, sd = 2)

tsla_data$BB_Upper <- bollinger[, "up"]
tsla_data$BB_Lower <- bollinger[, "dn"]
tsla_data$BB_Mid <- bollinger[, "mavg"]

ggplot(tsla_data, aes(x = Date)) +
  geom_line(aes(y = TSLA.Close, color = "Closing Price")) +
  geom_line(aes(y = BB_Upper, color = "Upper Band"), linetype = "dashed") +
  geom_line(aes(y = BB_Lower, color = "Lower Band"), linetype = "dashed") +
  geom_line(aes(y = BB_Mid, color = "Moving Average"), color = "blue") +
  labs(title = "Tesla Stock with Bollinger Bands (2022)",
       x = "Date",
       y = "Price (USD)") +
  scale_color_manual(values = c("Closing Price" = "black", "Upper Band" = "red", "Lower Band" = "red", "Moving Average" = "blue")) +
  theme_minimal()
## Warning: Removed 19 rows containing missing values or values outside the scale range
## (`geom_line()`).
## Warning: Removed 19 rows containing missing values or values outside the scale range
## (`geom_line()`).
## Removed 19 rows containing missing values or values outside the scale range
## (`geom_line()`).

# ---- Save Data as CSV (Optional) ----
write.csv(tsla_data, "Tesla_Stock_Analysis_2022.csv", row.names = FALSE)