# Exercises correction

# Load the necessary financial analysis packages
library(quantmod)
library(PerformanceAnalytics)

# ==============================================================================
# EXERCISE 1: Basic data retrieval and price visualization (RACE)
# ==============================================================================

# 1. Download the last 5 years of daily market data for Ferrari (RACE)
# We dynamically calculate the date range to ensure it remains accurate over time
getSymbols("RACE", from = Sys.Date() - (5 * 365), to = Sys.Date())

# 2. Display the first 5 and last 5 rows to verify data integrity
head(RACE, 5)
tail(RACE, 5)

# 3. Extract the closing price and generate a line chart
race_close <- Cl(RACE)
chartSeries(race_close, 
            name = "Ferrari N.V. (RACE) - 5-Year Closing Price", 
            theme = chartTheme("white"), 
            type = "line")

# ==============================================================================
# EXERCISE 2: Time-series extraction and volume analysis on Tesla (TSLA)
# ==============================================================================

# 1. Extract the market data for the precise calendar period (2022 to 2024)
getSymbols("TSLA", from = "2022-01-01", to = "2024-12-31")

# 2. Identify the peak and trough closing prices during this volatile period
tsla_close <- Cl(TSLA)
tsla_peak <- max(tsla_close, na.rm = TRUE)
tsla_trough <- min(tsla_close, na.rm = TRUE)

cat("Tesla Peak Close (2022-2024): $", tsla_peak, "\n")
cat("Tesla Trough Close (2022-2024): $", tsla_trough, "\n")

# 3. Extract the Volume column and calculate average daily trading volume
tsla_volume <- Vo(TSLA)
avg_daily_volume <- mean(tsla_volume, na.rm = TRUE)
cat("Tesla Average Daily Trading Volume (2022-2024): ", round(avg_daily_volume), "shares\n")

# ==============================================================================
# EXERCISE 3: Comparative performance and risk profiling (BABA, BIDU, PDD)
# ==============================================================================

# 1. Download data for Alibaba, Baidu, and PDD Holdings (Last 3 years for context)
start_date <- Sys.Date() - (3 * 365)
getSymbols(c("BABA", "BIDU", "PDD"), from = start_date, to = Sys.Date())

# 2. Calculate daily returns based on Adjusted Closing Prices
baba_ret <- dailyReturn(Ad(BABA))
bidu_ret <- dailyReturn(Ad(BIDU))
pdd_ret <- dailyReturn(Ad(PDD))

# Merge the returns into a single time-series matrix for comparative analysis
tech_returns <- merge(baba_ret, bidu_ret, pdd_ret)
colnames(tech_returns) <- c("BABA", "BIDU", "PDD")

# Q1: Which stock achieved the highest total cumulative return?
cumulative_returns <- Return.cumulative(tech_returns)
print("Cumulative Returns:")
print(cumulative_returns)

# Q2: Which stock was most volatile (highest standard deviation of daily returns)?
volatility <- StdDev(tech_returns)
print("Volatility (Standard Deviation):")
print(volatility)

# Q3: Which one offered the best risk-adjusted profile? (Sharpe Ratio)
# Using a risk-free rate (Rf) of 0 for simplicity in this baseline comparison
sharpe_ratios <- SharpeRatio(tech_returns, Rf = 0, p = 0.95, FUN = "StdDev")
print("Sharpe Ratios (Risk-Adjusted Profile):")
print(sharpe_ratios)