So sánh giá cổ phiếu META, AAPL và VFS

1. Thư viện sử dụng

library(ggplot2)
library(dplyr)
library(quantmod)
library(scales)

2. Mã cổ phiếu và thời gian phân tích

tickers <- c("META", "AAPL", "VFS")

start_date <- as.Date("2023-01-01")
end_date   <- Sys.Date()

3. Tải dữ liệu giá cổ phiếu (Adjusted Close)

fetch_prices <- function(ticker, from, to){
  x <- getSymbols(
    ticker,
    src = "yahoo",
    from = from,
    to = to,
    auto.assign = FALSE
  )

  data.frame(
    Ticker = ticker,
    Date = as.Date(index(x)),
    Price = as.numeric(Ad(x))
  )
}

prices <- do.call(
  rbind,
  lapply(tickers, fetch_prices, from = start_date, to = end_date)
)

head(prices)
##   Ticker       Date    Price
## 1   META 2023-01-03 123.8747
## 2   META 2023-01-04 126.4865
## 3   META 2023-01-05 126.0594
## 4   META 2023-01-06 129.1181
## 5   META 2023-01-09 128.5719
## 6   META 2023-01-10 132.0675

4. Chuẩn hoá giá về mốc 100 (ngày đầu)

prices_indexed <- prices %>%
  group_by(Ticker) %>%
  arrange(Date) %>%
  mutate(
    Base = first(Price),
    Index_100 = Price / Base * 100
  ) %>%
  ungroup()

5. Biểu đồ so sánh hiệu suất (mốc 100)

ggplot(prices_indexed, aes(Date, Index_100, color = Ticker)) +
  geom_line(linewidth = 0.9) +
  geom_hline(yintercept = 100, linetype = "dashed", linewidth = 0.5) +
  scale_x_date(
    date_breaks = "3 months",
    labels = date_format("%Y-%m")
  ) +
  labs(
    title = "So sánh hiệu suất cổ phiếu (ngày đầu = 100)",
    x = "Thời gian",
    y = "Chỉ số giá",
    color = "Mã cổ phiếu",
    caption = "Nguồn dữ liệu: Yahoo Finance"
  ) +
  theme_minimal(base_size = 12) +
  theme(
    plot.title = element_text(face = "bold"),
    axis.title  = element_text(face = "bold"),
    legend.position = "top",
    panel.grid.minor = element_blank()
  )