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
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()
)
