library(tidyverse)
library(readxl)
library(xts)
library(lubridate)
tej_data <- read_excel("C:/Users/DELL/Downloads/tej-data.xlsx.xlsx")
# Extract raw dates from the first column
raw_dates <- tej_data[[1]]
# Parse dates safely from string or numeric format
parsed_dates <- parse_date_time(as.character(raw_dates), orders = c("Ymd", "Y-m-d", "Y/m/d"))
clean_dates <- as.Date(parsed_dates)
# Filter out rows with invalid dates
valid_rows <- !is.na(clean_dates)
clean_data <- tej_data[valid_rows, 2:4]
final_dates <- clean_dates[valid_rows]
# Set required column names
colnames(clean_data) <- c("0050 元大台灣50", "0052 富邦科技", "0056 元大高股息")
# Create xts time series object
ts_data <- xts(clean_data, order.by = final_dates)
# Display first few rows of the time series data
head(ts_data)
## 0050 元大台灣50 0052 富邦科技 0056 元大高股息
## 2025-08-18 51.8973 28.8530 31.7759
## 2025-08-19 52.2403 29.1040 31.8394
## 2025-08-20 51.5052 28.5254 31.7124
## 2025-08-21 50.7211 28.0583 31.3496
## 2025-08-22 51.0152 28.3093 31.4857
## 2025-08-25 51.4072 28.6439 31.7487