This report builds on hw7 (Fama-French 3 factor model for the 50 largest Taiwan stocks, TEJ data).
data_dir in the first chunk).TEJ Pro exports UTF-16 text, so the bytes are read and converted first. The two files are found by their column names, so the file names do not matter.
unpack <- function(path) {
if (grepl("\\.zip$", path, ignore.case = TRUE)) {
exdir <- tempfile("tej_"); dir.create(exdir)
unzip(path, exdir = exdir)
path <- list.files(exdir, pattern = "\\.csv$", full.names = TRUE)[1]
}
path
}
read_tej_text <- function(path, n = file.size(path)) {
raw <- readBin(path, "raw", n)
if (length(raw) >= 2 && identical(raw[1:2], as.raw(c(0xff, 0xfe)))) {
txt <- iconv(list(raw), from = "UTF-16LE", to = "UTF-8")
} else {
txt <- rawToChar(raw)
}
gsub("\r", "", txt, fixed = TRUE)
}
read_tej <- function(path) {
out <- read.delim(text = read_tej_text(path), sep = "\t", quote = "",
comment.char = "", check.names = FALSE,
stringsAsFactors = FALSE, colClasses = "character",
na.strings = c("N.A.", "NA", ""))
names(out)[1] <- "CO_ID"
out
}
files <- list.files(data_dir, pattern = "\\.(csv|zip)$",
full.names = TRUE, ignore.case = TRUE)
files <- files[order(file.mtime(files), decreasing = TRUE)]
stock_path <- NULL
factor_path <- NULL
for (f in files) {
p <- tryCatch(unpack(f), error = function(e) NA_character_)
if (is.na(p)) next
n <- min(600, file.size(p) - file.size(p) %% 2)
head_txt <- tryCatch(read_tej_text(p, n), error = function(e) "")
if (is.null(stock_path) && grepl("ROI_Month", head_txt, fixed = TRUE))
stock_path <- p
if (is.null(factor_path) && grepl("Market Risk Premium", head_txt, fixed = TRUE))
factor_path <- p
}
if (is.null(stock_path) || is.null(factor_path))
stop("Could not find the TEJ files in: ", data_dir,
"\nFiles seen: ", paste(basename(files), collapse = ", "))
stocks <- read_tej(stock_path) %>%
transmute(
code = sub(" .*", "", trimws(CO_ID)),
name = sub("^[^ ]+ +", "", trimws(CO_ID)),
month = as.Date(paste0(trimws(Date), "01"), format = "%Y%m%d"),
ret = as.numeric(ROI_Month), # monthly return, %
mktcap = as.numeric(`Market Cap.`) # market cap, NTD million
) %>%
filter(grepl("^[1-9][0-9]{3}$", code)) %>% # normal stocks only (drops TDRs and ETFs)
arrange(month, code)
ff <- read_tej(factor_path) %>%
transmute(
month = as.Date(paste0(trimws(Date), "01"), format = "%Y%m%d"),
mkt = as.numeric(`Market Risk Premium`),
rf = as.numeric(`Risk-free Interest Rate`) / 12, # annual % -> monthly %
smb = as.numeric(`Size Factor (3 Factor)`),
hml = as.numeric(`Book to Market Factor`)
) %>%
arrange(month)
cat("Stocks:", n_distinct(stocks$code), "| Months:", n_distinct(stocks$month),
"| Factor months:", nrow(ff), "\n")
## Stocks: 1091 | Months: 98 | Factor months: 98
Monthly adjusted close (Close_Month) of 0050 from the
TEJ table TSE/OTC Adjusted_Price(Monthly)-Ex_R+D, 2017/10 to 2025/12.
The return is computed from the adjusted price and checked against TEJ’s
ROI_Month.
etf_csv <- "Date,Close_Month,ROI_Month\n2017/10,16.11,4.9262\n2017/11,15.55,-3.4625\n2017/12,15.53,-0.1215\n2018/01,16.42,5.6934\n2018/02,15.97,-2.7171\n2018/03,16.09,0.7287\n2018/04,15.52,-3.5565\n2018/05,15.66,0.9375\n2018/06,15.8,0.8669\n2018/07,16.73,5.9034\n2018/08,17.0,1.6362\n2018/09,16.99,-0.0576\n2018/10,15.17,-10.7596\n2018/11,15.01,-1.0313\n2018/12,14.77,-1.6288\n2019/01,14.99,1.5355\n2019/02,15.66,4.4383\n2019/03,15.96,1.9316\n2019/04,16.7,4.6114\n2019/05,15.82,-5.2536\n2019/06,16.31,3.1228\n2019/07,16.84,3.2117\n2019/08,16.64,-1.1474\n2019/09,17.2,3.3599\n2019/10,18.32,6.5013\n2019/11,18.61,1.554\n2019/12,19.71,5.9564\n2020/01,18.89,-4.2293\n2020/02,18.61,-1.4454\n2020/03,15.99,-14.1003\n2020/04,17.95,12.2784\n2020/05,17.73,-1.228\n2020/06,18.88,6.4537\n2020/07,21.95,16.2803\n2020/08,21.53,-1.9268\n2020/09,21.78,1.1786\n2020/10,21.78,0.0001\n2020/11,23.96,9.9998\n2020/12,25.85,7.8992\n2021/01,27.7,7.194\n2021/02,28.83,4.0562\n2021/03,29.12,1.012\n2021/04,30.38,4.3412\n2021/05,29.63,-2.4893\n2021/06,30.03,1.3493\n2021/07,29.47,-1.8364\n2021/08,30.41,3.1604\n2021/09,29.69,-2.3512\n2021/10,29.42,-0.912\n2021/11,29.9,1.6202\n2021/12,31.52,5.435\n2022/01,31.34,-0.5322\n2022/02,30.66,-2.1548\n2022/03,30.58,-0.2888\n2022/04,28.51,-6.7705\n2022/05,28.74,0.8155\n2022/06,25.64,-10.786\n2022/07,26.54,3.5063\n2022/08,26.45,-0.3389\n2022/09,23.27,-12.0322\n2022/10,22.28,-4.2533\n2022/11,26.17,17.466\n2022/12,24.78,-5.2857\n2023/01,27.2,9.6627\n2023/02,27.32,0.4227\n2023/03,27.96,2.3569\n2023/04,27.0,-3.4539\n2023/05,29.01,7.4532\n2023/06,29.69,2.3385\n2023/07,30.05,1.2274\n2023/08,29.33,-2.4068\n2023/09,28.62,-2.4264\n2023/10,28.27,-1.223\n2023/11,30.65,8.4193\n2023/12,31.6,3.1217\n2024/01,32.08,1.5225\n2024/02,34.22,6.6617\n2024/03,37.7,10.1882\n2024/04,37.78,0.2218\n2024/05,39.64,4.8973\n2024/06,44.52,12.3193\n2024/07,43.4,-2.5107\n2024/08,43.52,0.2765\n2024/09,44.15,1.4338\n2024/10,46.03,4.2677\n2024/11,44.94,-2.3721\n2024/12,46.98,4.5393\n2025/01,48.98,4.2495\n2025/02,46.84,-4.3714\n2025/03,42.03,-10.2597\n2025/04,41.02,-2.4025\n2025/05,43.73,6.6136\n2025/06,47.07,7.616\n2025/07,50.53,7.3503\n2025/08,51.46,1.8428\n2025/09,56.65,10.0954\n2025/10,63.46,12.0245\n2025/11,61.11,-3.7066\n2025/12,64.3,5.2124"
etf <- read.csv(text = etf_csv, stringsAsFactors = FALSE) %>%
transmute(
month = as.Date(paste0(Date, "/01"), format = "%Y/%m/%d"),
close = Close_Month,
roi = ROI_Month
) %>%
arrange(month) %>%
mutate(ret = (close / dplyr::lag(close) - 1) * 100) # 0050 monthly return, %
cat("0050 months:", nrow(etf), "| from", format(min(etf$month)),
"to", format(max(etf$month)), "\n")
## 0050 months: 99 | from 2017-10-01 to 2025-12-01
cat("Max |my return - TEJ ROI| (percentage points):",
round(max(abs(etf$ret - etf$roi), na.rm = TRUE), 3), "\n")
## Max |my return - TEJ ROI| (percentage points): 0.103
Same first window as hw7. For each stock:
(stock return - rf) = alpha + b * MKT + s * SMB + h * HML
Stocks with fewer than 36 months in the window are excluded.
formation <- as.Date("2020-12-01")
win_start <- as.Date("2018-01-01")
win_end <- as.Date("2020-12-01")
n_months <- length(seq(win_start, win_end, by = "month")) # 36
members <- stocks %>%
filter(month == formation, !is.na(mktcap)) %>%
arrange(desc(mktcap)) %>%
slice(1:50) %>%
mutate(rank = row_number()) %>%
select(rank, code, name, mktcap)
win <- stocks %>%
filter(code %in% members$code, month >= win_start, month <= win_end) %>%
inner_join(ff, by = "month") %>%
mutate(ex_ret = ret - rf)
full_codes <- win %>% filter(!is.na(ret)) %>% count(code) %>%
filter(n == n_months) %>% pull(code)
fmean <- ff %>%
filter(month >= win_start, month <= win_end) %>%
summarise(mkt = mean(mkt), smb = mean(smb), hml = mean(hml))
fit_one <- function(d) {
m <- lm(ex_ret ~ mkt + smb + hml, data = d)
b <- coef(m)
data.frame(code = d$code[1],
alpha = unname(b[1]),
b_mkt = unname(b[2]),
b_smb = unname(b[3]),
b_hml = unname(b[4]),
ff3_exp = unname(b[2] * fmean$mkt + b[3] * fmean$smb + b[4] * fmean$hml))
}
win_full <- win %>% filter(code %in% full_codes)
res <- bind_rows(lapply(split(win_full, win_full$code), fit_one)) %>%
left_join(members, by = "code") %>%
arrange(rank)
cat("Stocks used (full 36 months):", nrow(res), "of 50\n")
## Stocks used (full 36 months): 48 of 50
Top 10 by alpha:
top_alpha <- res %>% arrange(desc(alpha)) %>% slice(1:10)
top_alpha %>%
select(Rank = rank, Code = code, Name = name, Alpha = alpha, FF3_exp = ff3_exp) %>%
kable(digits = 3)
| Rank | Code | Name | Alpha | FF3_exp |
|---|---|---|---|---|
| 36 | 2379 | RT | 3.213 | 0.981 |
| 34 | 6415 | Silergy | 3.141 | 1.386 |
| 33 | 3034 | Novatek | 3.049 | 1.112 |
| 43 | 2345 | Accton | 2.995 | 1.157 |
| 8 | 2303 | UMC | 2.555 | 1.882 |
| 3 | 2454 | MediaTek | 2.314 | 0.980 |
| 1 | 2330 | TSMC | 1.506 | 1.421 |
| 28 | 2327 | Yageo | 1.383 | 2.875 |
| 45 | 1590 | Airtac | 1.001 | 1.211 |
| 26 | 2395 | Advantech | 0.891 | 1.176 |
Top 10 by FF3_exp:
top_exp <- res %>% arrange(desc(ff3_exp)) %>% slice(1:10)
top_exp %>%
select(Rank = rank, Code = code, Name = name, Alpha = alpha, FF3_exp = ff3_exp) %>%
kable(digits = 3)
| Rank | Code | Name | Alpha | FF3_exp |
|---|---|---|---|---|
| 35 | 2603 | EMC | 0.382 | 3.479 |
| 28 | 2327 | Yageo | 1.383 | 2.875 |
| 32 | 5871 | Chailease | 0.554 | 2.185 |
| 27 | 2408 | NTC | -0.515 | 2.118 |
| 8 | 2303 | UMC | 2.555 | 1.882 |
| 44 | 9910 | FT | 0.741 | 1.735 |
| 19 | 2207 | Hotai Motor | 0.803 | 1.655 |
| 2 | 2317 | Hon Hai | -1.656 | 1.592 |
| 6 | 2308 | DELTA | 0.779 | 1.590 |
| 48 | 1402 | FENC | -0.725 | 1.517 |
The stocks are picked with the 2018-2020 window and held out of sample from 2021/01 to 2025/12. Portfolios are rebalanced every month:
hold_start <- as.Date("2021-01-01")
hold_end <- as.Date("2025-12-01")
panel <- stocks %>%
filter(code %in% members$code, month >= formation, month <= hold_end) %>%
group_by(code) %>%
arrange(month, .by_group = TRUE) %>%
mutate(cap_lag = dplyr::lag(mktcap)) %>%
ungroup() %>%
filter(month >= hold_start, !is.na(ret), !is.na(cap_lag))
build <- function(codes, scheme) {
d <- panel %>% filter(code %in% codes)
if (scheme == "EW") {
d <- d %>% group_by(month) %>% mutate(w = 1 / n()) %>% ungroup()
} else {
d <- d %>% group_by(month) %>% mutate(w = cap_lag / sum(cap_lag)) %>% ungroup()
}
d
}
defs <- list(
"Alpha-EW" = list(top_alpha$code, "EW"),
"Alpha-VW" = list(top_alpha$code, "VW"),
"FF3exp-EW" = list(top_exp$code, "EW"),
"FF3exp-VW" = list(top_exp$code, "VW"),
"Top50-VW" = list(members$code, "VW") # proxy of the top 50 (Task 3)
)
wts <- bind_rows(lapply(names(defs), function(nm) {
build(defs[[nm]][[1]], defs[[nm]][[2]]) %>% mutate(port = nm)
}))
port_ret <- wts %>%
group_by(port, month) %>%
summarise(ret = sum(w * ret), .groups = "drop")
HHI = sum of squared weights. Effective N = 1 / HHI (an equal-weight portfolio of N stocks has effective N = N).
conc <- wts %>%
filter(grepl("VW", port)) %>%
group_by(port, month) %>%
summarise(max_w = max(w),
top3 = sum(sort(w, decreasing = TRUE)[1:3], na.rm = TRUE),
hhi = sum(w^2), .groups = "drop") %>%
arrange(port, month) %>%
group_by(port) %>%
summarise(`Largest weight, first month (%)` = 100 * first(max_w),
`Largest weight, average (%)` = 100 * mean(max_w),
`Top 3 weight, average (%)` = 100 * mean(top3),
`HHI, average` = mean(hhi),
`Effective N, average` = mean(1 / hhi))
kable(conc, digits = 2)
| port | Largest weight, first month (%) | Largest weight, average (%) | Top 3 weight, average (%) | HHI, average | Effective N, average |
|---|---|---|---|---|---|
| Alpha-VW | 80.66 | 81.92 | 92.08 | 0.68 | 1.48 |
| FF3exp-VW | 30.46 | 34.84 | 64.26 | 0.19 | 5.36 |
| Top50-VW | 43.64 | 45.94 | 54.57 | 0.22 | 4.69 |
Three biggest holdings in the first holding month (2021/01):
wts %>%
filter(grepl("VW", port), month == hold_start) %>%
group_by(port) %>%
arrange(desc(w), .by_group = TRUE) %>%
slice(1:3) %>%
ungroup() %>%
transmute(Portfolio = port, Code = code, Name = name, `Weight (%)` = 100 * w) %>%
kable(digits = 1)
| Portfolio | Code | Name | Weight (%) |
|---|---|---|---|
| Alpha-VW | 2330 | TSMC | 80.7 |
| Alpha-VW | 2454 | MediaTek | 7.0 |
| Alpha-VW | 2303 | UMC | 3.4 |
| FF3exp-VW | 2317 | Hon Hai | 30.5 |
| FF3exp-VW | 2308 | DELTA | 16.3 |
| FF3exp-VW | 2303 | UMC | 14.0 |
| Top50-VW | 2330 | TSMC | 43.6 |
| Top50-VW | 2317 | Hon Hai | 4.0 |
| Top50-VW | 2454 | MediaTek | 3.8 |
rets <- port_ret %>%
bind_rows(etf %>%
filter(month >= hold_start, month <= hold_end) %>%
transmute(port = "0050", month, ret)) %>%
pivot_wider(names_from = port, values_from = ret) %>%
arrange(month) %>%
inner_join(ff, by = "month")
cat("Holding months:", nrow(rets), "(", format(min(rets$month)), "to",
format(max(rets$month)), ")\n")
## Holding months: 60 ( 2021-01-01 to 2025-12-01 )
Over 2021/01 - 2025/12:
perf <- function(r, bench, d) {
dd <- data.frame(ex = r - d$rf, mkt = d$mkt, smb = d$smb, hml = d$hml)
m <- lm(ex ~ mkt + smb + hml, data = dd)
s <- summary(m)
act <- r - bench
te <- sd(act) * sqrt(12)
data.frame(
`Ann. return (%)` = (prod(1 + r / 100)^(12 / length(r)) - 1) * 100,
`Ann. vol (%)` = sd(r) * sqrt(12),
`FF3 alpha (%/mo)` = unname(coef(m)[1]),
`t(alpha)` = unname(s$coefficients[1, 3]),
`Tracking error (%)` = te,
`Info. ratio` = mean(act) * 12 / te,
check.names = FALSE)
}
ports <- c("Alpha-EW", "Alpha-VW", "FF3exp-EW", "FF3exp-VW", "Top50-VW", "0050")
perf_tab <- bind_rows(lapply(ports, function(p) perf(rets[[p]], rets[["0050"]], rets)))
perf_tab <- cbind(Portfolio = ports, perf_tab, stringsAsFactors = FALSE)
# 0050 against itself: TE and IR are not meaningful
perf_tab[perf_tab$Portfolio == "0050", c("Tracking error (%)", "Info. ratio")] <- NA
kable(perf_tab, digits = 3)
| Portfolio | Ann. return (%) | Ann. vol (%) | FF3 alpha (%/mo) | t(alpha) | Tracking error (%) | Info. ratio |
|---|---|---|---|---|---|---|
| Alpha-EW | 13.395 | 21.983 | -0.247 | -0.543 | 14.078 | -0.373 |
| Alpha-VW | 24.430 | 26.105 | 0.289 | 1.112 | 8.312 | 0.614 |
| FF3exp-EW | 17.816 | 19.431 | -0.181 | -0.460 | 13.901 | -0.137 |
| FF3exp-VW | 20.502 | 22.057 | -0.014 | -0.031 | 12.940 | 0.069 |
| Top50-VW | 20.090 | 18.675 | 0.127 | 1.293 | 2.387 | -0.039 |
| 0050 | 19.991 | 19.637 | 0.105 | 0.904 |
growth <- sapply(ports, function(p) c(100, 100 * cumprod(1 + rets[[p]] / 100)))
dates <- c(formation, rets$month)
cols <- c("firebrick", "orange", "steelblue", "navy", "darkgreen", "black")
matplot(dates, growth, type = "l", lty = 1, lwd = c(2, 2, 2, 2, 2, 3), col = cols,
xlab = "", ylab = "Value of 100", main = "Growth of 100: portfolios vs 0050")
legend("topleft", legend = ports, col = cols, lwd = 2, bty = "n", cex = 0.85)
Numbers from the tables: the best annualized return among the five portfolios is Alpha-VW (24.4% a year, against 20% for 0050). The best information ratio is Alpha-VW (0.61). 0 of the 5 portfolios have an FF3 alpha with |t| above 2.
Points to comment on (edit to match your results):
write.csv(top_alpha, "hw8_top10_alpha.csv", row.names = FALSE)
write.csv(top_exp, "hw8_top10_ff3exp.csv", row.names = FALSE)
write.csv(conc, "hw8_concentration.csv", row.names = FALSE)
write.csv(perf_tab, "hw8_performance.csv", row.names = FALSE)
write.csv(rets %>% mutate(month = format(month, "%Y-%m")),
"hw8_monthly_returns.csv", row.names = FALSE)
cat("Saved 5 csv files in:", data_dir, "\n")
## Saved 5 csv files in: C:/Users/DELL/Downloads/rdataa