Residual Reversal on the 100 Largest Taiwan Stocks

Take-Home Project, Part 3 — compared with 0050 and the TAIEX total return index

Yesuigen Temuujin

2026-11-26

0. Setup and configuration

How to use this file. It runs as-is in demo mode (simulated data) so you can check that the whole pipeline works. To use your real data, set USE_DEMO <- FALSE, put the four files in a raw/ folder, and edit the column names in COLS so they match your files (run glimpse() on each file to see them).

show code
library(tidyverse)
library(lubridate)
library(knitr)

dir.create("output", showWarnings = FALSE)

# ---------------- CONFIG: edit this block ----------------
USE_DEMO <- TRUE                       # TRUE = simulated data, FALSE = your TEJ files

F_STOCK <- "raw/stocks_monthly.txt"    # TEJ monthly: ticker, month, adjusted price, market cap
F_FACT  <- "raw/ff3_monthly.txt"       # monthly Fama-French factors
F_ETF   <- "raw/etf0050_monthly.txt"   # id, month, level  (0050 adjusted price)
F_TAI   <- "raw/taiex_tr_monthly.txt"  # id, month, level  (TAIEX total return index)
ENC     <- "UTF-8"                     # use "Big5" if Chinese headers look garbled

# names in YOUR files (new_name = "name in file")
COLS <- list(
  stock = c(ticker = "ticker", month = "month", price = "adj_close", mcap = "mktcap"),
  fact  = c(month = "month", mktrf = "mktrf", smb = "smb", hml = "hml", rf = "rf"),
  etf   = c(month = "month", level = "level"),
  tai   = c(month = "month", level = "level")
)
FACTOR_IN_PERCENT <- TRUE   # TRUE if the factor file is in percent (1.2 = 1.2%)
# ----------------------------------------------------------

N_UNIV  <- 100   # stocks in the universe
W       <- 36    # regression window (months)
MINOBS  <- 30    # minimum valid returns in the window
FORM_START <- ymd("2020-12-01"); FORM_END <- ymd("2025-11-01")

to_month <- function(x) {                # "202012", "2020/12/31", "2020-12-31", Date -> first of month
  s <- gsub("[^0-9]", "", as.character(x))
  ymd(paste0(substr(s, 1, 6), "01"))
}
pct <- function(x, d = 2) sprintf("%.*f%%", d, 100 * x)
show code
if (USE_DEMO) {
  set.seed(114034050)
  mths <- seq(ymd("2017-12-01"), ymd("2025-12-01"), by = "month")
  n <- length(mths); N <- 160
  fac <- tibble(month = mths, mktrf = rnorm(n, .008, .04), smb = rnorm(n, 0, .02),
                hml = rnorm(n, 0, .02), rf = .0004)
  beta <- cbind(rnorm(N, 1, .3), rnorm(N, 0, .5), rnorm(N, 0, .5))
  eps  <- matrix(rnorm(n * N, 0, .06), n, N)
  for (t in 2:n) eps[t, ] <- eps[t, ] - 0.15 * eps[t - 1, ]      # built-in reversal
  r <- cbind(fac$mktrf, fac$smb, fac$hml) %*% t(beta) + fac$rf + eps
  P <- 50 * apply(1 + r, 2, cumprod)
  P[sample(length(P), 60)] <- NA                                   # a few random gaps
  for (j in sample(N, 6)) P[sample(60:n, 1):n, j] <- NA            # a few "delistings"
  shares <- exp(rnorm(N, 3, 1))
  stocks <- tibble(ticker = rep(sprintf("%04d", 1100 + 1:N), each = n),
                   month = rep(mths, N), price = c(P), mcap = c(P * rep(shares, each = n) * 1e3))
  mk <- cumprod(1 + fac$mktrf + fac$rf + rnorm(n, 0, .005))
  etf <- tibble(month = mths, level = 70 * mk) |> filter(month >= FORM_START)
  tai <- tibble(month = mths, level = 15000 * mk * 1.001^(1:n)) |> filter(month >= FORM_START)
} else {
  rd <- function(f) vroom::vroom(f, locale = vroom::locale(encoding = ENC),
                                 show_col_types = FALSE, progress = FALSE)
  stocks <- rd(F_STOCK) |> rename(all_of(COLS$stock))
  fac    <- rd(F_FACT)  |> rename(all_of(COLS$fact))
  etf    <- rd(F_ETF)   |> rename(all_of(COLS$etf))
  tai    <- rd(F_TAI)   |> rename(all_of(COLS$tai))
  if (FACTOR_IN_PERCENT) fac <- fac |> mutate(across(c(mktrf, smb, hml, rf), ~ .x / 100))
}

stocks <- stocks |> mutate(month = to_month(month), ticker = as.character(ticker))
fac    <- fac    |> mutate(month = to_month(month)) |> arrange(month)
etf    <- etf    |> mutate(month = to_month(month)) |> arrange(month)
tai    <- tai    |> mutate(month = to_month(month)) |> arrange(month)
glimpse(stocks)
Rows: 15,520
Columns: 4
$ ticker <chr> "1101", "1101", "1101", "1101", "1101", "1101", "1101", "1101",…
$ month  <date> 2017-12-01, 2018-01-01, 2018-02-01, 2018-03-01, 2018-04-01, 20…
$ price  <dbl> 51.31737, 53.07722, 54.09928, 52.85194, 53.95149, 50.01050, 50.…
$ mcap   <dbl> 545196.6, 563893.2, 574751.6, 561499.8, 573181.5, 531312.3, 539…

R1. Data and universe

show code
n_dup <- sum(duplicated(stocks[c("ticker", "month")]))
stocks <- stocks |> filter(!is.na(month), !is.na(ticker)) |> distinct(ticker, month, .keep_all = TRUE)

all_m <- fac$month                                   # master calendar = factor months
stopifnot(!anyDuplicated(all_m), max(all_m) >= ymd("2025-12-01"))
tick  <- sort(unique(stocks$ticker))
nm    <- length(all_m)

to_mat <- function(v) {                              # long -> months x stocks matrix
  m <- matrix(NA_real_, nm, length(tick), dimnames = list(as.character(all_m), tick))
  ii <- match(stocks$month, all_m); jj <- match(stocks$ticker, tick); ok <- !is.na(ii)
  m[cbind(ii[ok], jj[ok])] <- stocks[[v]][ok]
  m
}
PRICE <- to_mat("price"); PRICE[PRICE <= 0] <- NA
MC    <- to_mat("mcap")
RET   <- rbind(NA_real_, PRICE[-1, , drop = FALSE] / PRICE[-nm, , drop = FALSE] - 1)  # NA if prev month missing
dimnames(RET) <- dimnames(PRICE)

form_m <- seq(FORM_START, FORM_END, by = "month")

universe <- map_dfr(form_m, function(fm) {
  ii <- match(fm, all_m)                                  # row of formation month t
  ok <- which(!is.na(MC[ii, ]) & !is.na(PRICE[ii, ]))
  jj <- ok[order(-MC[ii, ok])][seq_len(min(N_UNIV, length(ok)))]   # top-100 by market cap
  tibble(form_m = fm, i = ii, j = jj, ticker = tick[jj], mcap = MC[ii, jj],
         ret_hold = RET[cbind(ii + 1, jj)])               # month t+1 return
})

checks_r1 <- tibble(
  check = c("duplicate stock-month rows in raw file (removed)", "formation months",
            "min stocks per month", "max stocks per month", "duplicate stock-month rows in universe"),
  value = c(n_dup, n_distinct(universe$form_m),
            min(count(universe, form_m)$n), max(count(universe, form_m)$n),
            sum(duplicated(universe[c("form_m", "ticker")]))))
kable(checks_r1)
check value
duplicate stock-month rows in raw file (removed) 0
formation months 60
min stocks per month 100
max stocks per month 100
duplicate stock-month rows in universe 0

R2. Residual signal

For each stock and formation month t: regress the excess return on MKT, SMB, HML over the 36 months ending in t. The residual of month t is ε̂i, t, the residual standard error is $\hat\sigma_i=\sqrt{\sum \hat\varepsilon^2/(n-4)}$, and the signal is zi, t = ε̂i, t/σ̂i.

show code
Y <- sweep(RET, 1, fac$rf, "-")                       # excess returns
X <- cbind(1, fac$mktrf, fac$smb, fac$hml)

signal_one <- function(i, j) {
  idx <- (i - W + 1):i
  y <- Y[idx, j]; ok <- !is.na(y); n <- sum(ok)
  if (!ok[W] || n < MINOBS) return(c(n_obs = n, eps = NA, sigma = NA, z = NA))
  e <- lm.fit(X[idx[ok], , drop = FALSE], y[ok])$residuals
  s <- sqrt(sum(e^2) / (n - 4))
  e_t <- unname(e[n])                                     # last residual = month t
  c(n_obs = n, eps = e_t, sigma = s, z = e_t / s)
}

sig <- universe |>
  mutate(res = map2(i, j, ~ as_tibble_row(signal_one(.x, .y)))) |>
  unnest(res) |>
  mutate(reason = case_when(!is.na(z) ~ "valid",
                            is.na(RET[cbind(i, j)]) ~ "return in month t missing",
                            TRUE ~ "fewer than 30 valid returns"))

sig |> group_by(year = year(form_m)) |>
  summarise(universe_rows = n(), valid_signal = sum(reason == "valid"),
            dropped_too_few_obs = sum(reason == "fewer than 30 valid returns"),
            dropped_missing_month_t = sum(reason == "return in month t missing")) |>
  kable(caption = "Valid signals and dropped stocks by formation year")
Valid signals and dropped stocks by formation year
year universe_rows valid_signal dropped_too_few_obs dropped_missing_month_t
2020 100 100 0 0
2021 1200 1197 0 3
2022 1200 1196 0 4
2023 1200 1197 0 3
2024 1200 1197 0 3
2025 1100 1093 0 7
show code
kable(tibble(check = c("max window length (months)", "window ends in formation month"),
             value = c(W, "yes: rows (i-35):i, last row = month t")))
check value
max window length (months) 36
window ends in formation month yes: rows (i-35):i, last row = month t

Hand check for one stock and one month.

show code
pick <- sig |> filter(reason == "valid", form_m == ymd("2023-06-01")) |> slice(1)
i <- pick$i; j <- pick$j
d <- tibble(month = all_m[(i - W + 1):i], y = Y[(i - W + 1):i, j],
            mktrf = fac$mktrf[(i - W + 1):i], smb = fac$smb[(i - W + 1):i], hml = fac$hml[(i - W + 1):i])
fit <- lm(y ~ mktrf + smb + hml, data = d)
cat("Stock", pick$ticker, "| formation month", format(pick$form_m, "%Y-%m"), "| n =", nobs(fit), "\n")
Stock 1158 | formation month 2023-06 | n = 36 
show code
summary(fit)

Call:
lm(formula = y ~ mktrf + smb + hml, data = d)

Residuals:
     Min       1Q   Median       3Q      Max 
-0.12509 -0.02833  0.01103  0.03495  0.10377 

Coefficients:
             Estimate Std. Error t value Pr(>|t|)    
(Intercept)  0.011653   0.009725   1.198 0.239622    
mktrf        1.181559   0.288889   4.090 0.000272 ***
smb          0.151327   0.419451   0.361 0.720640    
hml         -0.514862   0.447271  -1.151 0.258213    
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.0558 on 32 degrees of freedom
Multiple R-squared:  0.3959,    Adjusted R-squared:  0.3393 
F-statistic: 6.991 on 3 and 32 DF,  p-value: 0.0009534
show code
e_t   <- tail(resid(fit), 1)
s_hat <- sqrt(sum(resid(fit)^2) / (nobs(fit) - 4))
tibble(item = c("residual in month t", "sigma by hand", "sigma from lm()", "z by hand", "z in signal table"),
       value = c(e_t, s_hat, summary(fit)$sigma, e_t / s_hat, pick$z)) |> kable(digits = 6)
item value
residual in month t 0.011005
sigma by hand 0.055799
sigma from lm() 0.055799
z by hand 0.197225
z in signal table 0.197225

R3. Quintile holdings

show code
hold <- sig |>
  filter(!is.na(z)) |>
  group_by(form_m) |>
  mutate(q = ntile(z, 5)) |>                        # Q1 = lowest z
  ungroup() |>
  mutate(hold_m = form_m %m+% months(1), has_ret = !is.na(ret_hold)) |>
  group_by(form_m, q) |>
  mutate(n_q = n(),
         w_ew = if_else(has_ret, 1 / sum(has_ret), 0),
         w_vw = if_else(has_ret, mcap / sum(mcap[has_ret]), 0)) |>
  ungroup()

qsize <- hold |> count(form_m, q)
wsum  <- hold |> group_by(form_m, q) |> summarise(ew = sum(w_ew), vw = sum(w_vw), .groups = "drop")

kable(tibble(
  check = c("max quintile size gap within a month (should be <= 1)",
            "weights sum to 1 (EW), max abs error", "weights sum to 1 (VW), max abs error",
            "holding-month return missing (stock-months dropped)", "share of stock-months dropped"),
  value = c(max(qsize |> group_by(form_m) |> summarise(g = max(n) - min(n)) |> pull(g)),
            max(abs(wsum$ew - 1)), max(abs(wsum$vw - 1)),
            sum(!hold$has_ret), round(mean(!hold$has_ret), 4))))
check value
max quintile size gap within a month (should be <= 1) 1.0000
weights sum to 1 (EW), max abs error 0.0000
weights sum to 1 (VW), max abs error 0.0000
holding-month return missing (stock-months dropped) 23.0000
share of stock-months dropped 0.0038
show code
hold |> group_by(year = year(hold_m)) |> summarise(dropped = sum(!has_ret), of = n()) |> kable()
year dropped of
2021 3 1197
2022 4 1197
2023 5 1196
2024 4 1197
2025 7 1193

R4. Portfolio returns

show code
qret <- hold |> filter(has_ret) |>
  group_by(hold_m, q) |>
  summarise(EW = sum(w_ew * ret_hold), VW = sum(w_vw * ret_hold), .groups = "drop") |>
  pivot_longer(c(EW, VW), names_to = "w", values_to = "ret") |>
  mutate(portfolio = paste0("Q", q, " (", w, ")"))

ls_ret <- qret |> select(hold_m, q, w, ret) |>
  pivot_wider(names_from = q, values_from = ret, names_prefix = "Q") |>
  transmute(hold_m, w, ret = Q1 - Q5, portfolio = paste0("LS (", w, ")"))

uni_ret <- universe |> filter(!is.na(ret_hold)) |>
  group_by(form_m) |>
  summarise(`EW universe` = mean(ret_hold), `VW universe` = sum(mcap * ret_hold) / sum(mcap), .groups = "drop") |>
  mutate(hold_m = form_m %m+% months(1)) |> select(-form_m) |>
  pivot_longer(-hold_m, names_to = "portfolio", values_to = "ret")

bench_ret <- function(df, name) df |> arrange(month) |>
  mutate(ret = level / lag(level) - 1) |> filter(month >= ymd("2021-01-01"), month <= ymd("2025-12-01")) |>
  transmute(hold_m = month, portfolio = name, ret)
etf_r <- bench_ret(etf, "0050"); tai_r <- bench_ret(tai, "TAIEX_TR")
if (any(etf_r$ret < -0.5, na.rm = TRUE)) warning("0050 has a jump below -50%: the June 2025 4-for-1 split is NOT adjusted!")

series <- c(paste0("Q", 1:5, " (EW)"), "LS (EW)", paste0("Q", 1:5, " (VW)"), "LS (VW)",
            "0050", "TAIEX_TR", "EW universe", "VW universe")

pr <- bind_rows(select(qret, hold_m, portfolio, ret), select(ls_ret, hold_m, portfolio, ret),
                uni_ret, etf_r, tai_r) |>
  mutate(portfolio = factor(portfolio, levels = series)) |>
  left_join(fac |> rename(hold_m = month), by = "hold_m") |>
  arrange(portfolio, hold_m)

count(pr, portfolio) |> mutate(ok = n == 60) |> kable(caption = "Check: 60 holding months per series")
Check: 60 holding months per series
portfolio n ok
Q1 (EW) 60 TRUE
Q2 (EW) 60 TRUE
Q3 (EW) 60 TRUE
Q4 (EW) 60 TRUE
Q5 (EW) 60 TRUE
LS (EW) 60 TRUE
Q1 (VW) 60 TRUE
Q2 (VW) 60 TRUE
Q3 (VW) 60 TRUE
Q4 (VW) 60 TRUE
Q5 (VW) 60 TRUE
LS (VW) 60 TRUE
0050 60 TRUE
TAIEX_TR 60 TRUE
EW universe 60 TRUE
VW universe 60 TRUE
show code
stopifnot(nrow(pr) == 16 * 60)

R5. Performance table

show code
perf_one <- function(d, is_ls) {
  r  <- d$ret
  rx <- if (is_ls) r else r - d$rf                       # LS needs no cash, so use the return itself
  wealth <- c(1, cumprod(1 + r))
  fit <- lm(rx ~ mktrf + smb + hml, data = d); co <- summary(fit)$coefficients
  tibble(cum_ret = tail(wealth, 1) - 1,
         ann_ret = tail(wealth, 1)^(12 / length(r)) - 1,
         ann_vol = sd(r) * sqrt(12),
         sharpe  = mean(rx) / sd(rx) * sqrt(12),
         max_dd  = min(wealth / cummax(wealth) - 1),
         worst_m = min(r),
         alpha = co[1, 1], alpha_t = co[1, 3],
         b_mkt = co[2, 1], t_mkt = co[2, 3], b_smb = co[3, 1], t_smb = co[3, 3],
         b_hml = co[4, 1], t_hml = co[4, 3])
}

turn_calc <- function(h, wcol) {
  h <- h |> filter(has_ret) |> select(form_m, q, ticker, w = all_of(wcol), ret_hold)
  fms <- sort(unique(h$form_m))
  map_dfr(2:length(fms), function(k) {
    old <- h |> filter(form_m == fms[k - 1]) |> group_by(q) |>
      mutate(wd = w * (1 + ret_hold) / sum(w * (1 + ret_hold))) |> ungroup() |> select(q, ticker, wd)
    new <- h |> filter(form_m == fms[k]) |> select(q, ticker, w)
    full_join(old, new, by = c("q", "ticker")) |> replace_na(list(wd = 0, w = 0)) |>
      group_by(q) |> summarise(turn = 0.5 * sum(abs(w - wd)), .groups = "drop") |> mutate(form_m = fms[k])
  })
}
turn_tbl <- function(wcol, tag) {
  t <- turn_calc(hold, wcol)
  avg <- t |> group_by(q) |> summarise(turn = mean(turn), .groups = "drop")
  ls  <- t |> filter(q %in% c(1, 5)) |> group_by(form_m) |> summarise(turn = mean(turn)) |> pull(turn) |> mean()
  tibble(portfolio = c(paste0("Q", avg$q, " (", tag, ")"), paste0("LS (", tag, ")")), turnover = c(avg$turn, ls))
}
turnover <- bind_rows(turn_tbl("w_ew", "EW"), turn_tbl("w_vw", "VW"))

perf <- map_dfr(series, function(s) {
  perf_one(filter(pr, portfolio == s), grepl("^LS", s)) |> mutate(portfolio = s, .before = 1)
}) |> left_join(turnover, by = "portfolio") |>
  mutate(portfolio = factor(portfolio, levels = series))

perf |> transmute(portfolio,
    cum = pct(cum_ret, 1), ann = pct(ann_ret, 1), vol = pct(ann_vol, 1), sharpe = round(sharpe, 2),
    mdd = pct(max_dd, 1), worst = pct(worst_m, 1),
    alpha = pct(alpha, 2), `t(a)` = round(alpha_t, 2),
    mkt = round(b_mkt, 2), `t(m)` = round(t_mkt, 1), smb = round(b_smb, 2), `t(s)` = round(t_smb, 1),
    hml = round(b_hml, 2), `t(h)` = round(t_hml, 1), turnover = ifelse(is.na(turnover), "–", pct(turnover, 1))) |>
  kable(caption = "Performance of all 16 series (monthly FF3 alpha; Sharpe uses excess returns, LS uses the raw return)")
Performance of all 16 series (monthly FF3 alpha; Sharpe uses excess returns, LS uses the raw return)
portfolio cum ann vol sharpe mdd worst alpha t(a) mkt t(m) smb t(s) hml t(h) turnover
Q1 (EW) 93.3% 14.1% 13.5% 1.01 -11.5% -8.0% 1.16% 6.50 0.99 20.1 -0.14 -1.6 0.15 1.9 85.3%
Q2 (EW) 30.8% 5.5% 13.2% 0.44 -13.5% -8.6% 0.49% 2.76 0.97 19.8 -0.04 -0.5 0.12 1.5 81.2%
Q3 (EW) 6.8% 1.3% 13.0% 0.13 -14.9% -10.8% 0.17% 1.03 0.95 20.4 -0.23 -2.9 0.17 2.3 79.7%
Q4 (EW) -27.5% -6.2% 14.0% -0.42 -34.8% -12.3% -0.47% -2.58 1.02 20.3 -0.13 -1.5 0.07 0.8 80.5%
Q5 (EW) -57.2% -15.6% 14.2% -1.14 -58.1% -14.9% -1.36% -7.07 1.05 19.9 0.03 0.3 0.17 2.0 87.1%
LS (EW) 334.0% 34.1% 6.9% 4.32 -2.1% -2.1% 2.52% 9.68 -0.06 -0.9 -0.17 -1.4 -0.02 -0.2 86.2%
Q1 (VW) 93.8% 14.2% 14.3% 0.96 -11.9% -8.9% 1.16% 4.40 0.98 13.5 -0.05 -0.4 0.08 0.7 86.4%
Q2 (VW) 40.0% 7.0% 14.6% 0.50 -16.7% -9.8% 0.62% 2.66 1.04 16.2 -0.05 -0.5 0.14 1.3 83.0%
Q3 (VW) 3.0% 0.6% 13.6% 0.07 -19.7% -10.1% 0.14% 0.61 0.93 15.2 -0.37 -3.6 0.31 3.1 81.5%
Q4 (VW) -23.0% -5.1% 15.7% -0.28 -34.6% -10.3% -0.33% -1.53 1.13 18.7 -0.27 -2.6 0.17 1.7 82.7%
Q5 (VW) -64.0% -18.5% 16.1% -1.21 -65.2% -16.1% -1.61% -6.44 1.15 16.7 -0.04 -0.4 0.27 2.4 88.2%
LS (VW) 403.5% 38.2% 10.0% 3.32 -6.4% -6.4% 2.77% 7.45 -0.17 -1.6 -0.01 -0.1 -0.19 -1.1 87.3%
0050 -1.2% -0.2% 12.9% 0.01 -23.5% -10.8% 0.01% 0.16 1.00 47.5 0.00 0.1 0.00 0.1 –
TAIEX_TR 4.9% 1.0% 12.9% 0.10 -21.8% -10.7% 0.11% 1.47 1.00 47.5 0.00 0.1 0.00 0.1 –
EW universe -2.9% -0.6% 12.9% -0.02 -21.0% -10.6% -0.00% -0.03 1.00 44.7 -0.10 -2.7 0.14 3.8 –
VW universe -7.5% -1.5% 13.7% -0.08 -25.3% -10.2% -0.07% -0.63 1.05 36.2 -0.16 -3.2 0.19 4.0 –
show code
# ---- files to submit ----
holdings_out <- hold |> select(form_m, ticker, mcap, z, q, hold_m, ret_hold, w_ew, w_vw) |>
  mutate(form_ym = format(form_m, "%Y-%m"), hold_ym = format(hold_m, "%Y-%m"), .before = 1) |>
  select(-form_m, -hold_m)
write_csv(holdings_out, "output/holdings.csv")
write_csv(pr |> transmute(portfolio, hold_ym = format(hold_m, "%Y-%m"), ret), "output/portfolio_returns.csv")
write_csv(perf, "output/performance.csv")

R6. Charts and comparison

show code
growth <- pr |> group_by(portfolio) |> arrange(hold_m) |>
  mutate(value = 100 * cumprod(1 + ret)) |> ungroup() |>
  select(portfolio, hold_m, value) |>
  bind_rows(tibble(portfolio = factor(series, levels = series), hold_m = ymd("2020-12-01"), value = 100))

th <- theme_minimal(base_size = 12) + theme(legend.position = "bottom", legend.title = element_blank(),
        plot.title = element_text(face = "bold"), panel.grid.minor = element_blank())

g1 <- growth |> filter(portfolio %in% c(paste0("Q", 1:5, " (EW)"), "0050", "TAIEX_TR")) |>
  ggplot(aes(hold_m, value, colour = portfolio, linewidth = portfolio %in% c("0050", "TAIEX_TR"))) +
  geom_line() + scale_linewidth_manual(values = c(.7, 1.3), guide = "none") +
  labs(title = "Growth of NT$100: residual-reversal quintiles (equal-weighted) vs benchmarks",
       x = NULL, y = "NT$") + th
g1; ggsave("output/chart1_quintiles_growth.png", g1, width = 9, height = 5, dpi = 200)

show code
g2 <- growth |> filter(portfolio %in% c("LS (EW)", "LS (VW)", "0050", "TAIEX_TR")) |>
  ggplot(aes(hold_m, value, colour = portfolio)) + geom_line(linewidth = 1) +
  labs(title = "Growth of NT$100: long-short (Q1 - Q5) vs 0050 and TAIEX_TR",
       subtitle = "LS is a zero-investment, market-neutral portfolio: not a like-for-like comparison", x = NULL, y = "NT$") + th
g2; ggsave("output/chart2_longshort_growth.png", g2, width = 9, height = 5, dpi = 200)

show code
avg_q <- pr |> filter(grepl("^Q[1-5]", portfolio)) |>
  mutate(w = str_extract(portfolio, "EW|VW"), q = str_extract(portfolio, "Q[1-5]")) |>
  group_by(q, w) |> summarise(avg = mean(ret), .groups = "drop")

g3 <- ggplot(avg_q, aes(q, avg, fill = w)) + geom_col(position = "dodge", width = .7) +
  scale_y_continuous(labels = scales::percent_format(accuracy = .1)) +
  labs(title = "Average monthly return by residual-reversal quintile", x = NULL, y = NULL) + th
g3; ggsave("output/chart3_quintile_bars.png", g3, width = 8, height = 4.5, dpi = 200)

show code
avg_ew <- avg_q |> filter(w == "EW") |> arrange(q) |> pull(avg)
mono   <- all(diff(avg_ew) < 0)
cat("Average monthly EW returns Q1..Q5:", paste(pct(avg_ew, 2), collapse = " | "),
    "\nStrictly decreasing from Q1 to Q5 (monotonic)?", mono)
Average monthly EW returns Q1..Q5: 1.18% | 0.52% | 0.18% | -0.45% | -1.32% 
Strictly decreasing from Q1 to Q5 (monotonic)? TRUE
show code
perf |> filter(portfolio %in% c("LS (EW)", "LS (VW)", "Q1 (EW)", "0050", "TAIEX_TR")) |>
  transmute(Portfolio = portfolio, `Ann. return` = pct(ann_ret, 1), Volatility = pct(ann_vol, 1),
            Sharpe = round(sharpe, 2), `Max drawdown` = pct(max_dd, 1),
            `FF3 alpha (t)` = sprintf("%.2f%% (%.2f)", 100 * alpha, alpha_t),
            Turnover = ifelse(is.na(turnover), "–", pct(turnover, 1))) |>
  kable(caption = "Comparison table")
Comparison table
Portfolio Ann. return Volatility Sharpe Max drawdown FF3 alpha (t) Turnover
Q1 (EW) 14.1% 13.5% 1.01 -11.5% 1.16% (6.50) 85.3%
LS (EW) 34.1% 6.9% 4.32 -2.1% 2.52% (9.68) 86.2%
LS (VW) 38.2% 10.0% 3.32 -6.4% 2.77% (7.45) 87.3%
0050 -0.2% 12.9% 0.01 -23.5% 0.01% (0.16) –
TAIEX_TR 1.0% 12.9% 0.10 -21.8% 0.11% (1.47) –

R7. Discussion

show code
g <- function(s) perf |> filter(portfolio == s)
ls <- g("LS (EW)"); lv <- g("LS (VW)"); q1 <- g("Q1 (EW)"); b50 <- g("0050"); tx <- g("TAIEX_TR")
sig_txt <- function(t) ifelse(abs(t) >= 2, "statistically significant", "not statistically significant")

cat(sprintf(
"**Is there a reversal effect?** Average monthly returns fall from %s in Q1 to %s in Q5, so the pattern is %s. The long-short portfolio (Q1 minus Q5) earns an FF3 alpha of %s per month (t = %.2f, %s) when equal-weighted and %s (t = %.2f, %s) when value-weighted. Because the alpha is measured after removing market, size and value exposure, the evidence for reversal rests on the alpha and its t-statistic, not on the raw return alone.\n\n",
  pct(avg_ew[1]), pct(avg_ew[5]), ifelse(mono, "monotonic", "not monotonic"),
  pct(ls$alpha), ls$alpha_t, sig_txt(ls$alpha_t), pct(lv$alpha), lv$alpha_t, sig_txt(lv$alpha_t)))

Is there a reversal effect? Average monthly returns fall from 1.18% in Q1 to -1.32% in Q5, so the pattern is monotonic. The long-short portfolio (Q1 minus Q5) earns an FF3 alpha of 2.52% per month (t = 9.68, statistically significant) when equal-weighted and 2.77% (t = 7.45, statistically significant) when value-weighted. Because the alpha is measured after removing market, size and value exposure, the evidence for reversal rests on the alpha and its t-statistic, not on the raw return alone.

show code
cat(sprintf(
"**Factor loadings.** The market loading of LS (EW) is %.2f (t = %.1f), against %.2f for Q1 (EW) and %.2f for 0050. Q1 and 0050 are mostly market bets, while LS is close to market-neutral because the long and short legs carry similar factor exposure. This is what the residual signal is designed to do: the ranking uses the part of last month's return that the three factors do not explain, so the long-short portfolio should earn from stock-specific reversal and not from a factor tilt. LS loadings on SMB (%.2f) and HML (%.2f) show how much size or value exposure is left.\n\n",
  ls$b_mkt, ls$t_mkt, q1$b_mkt, b50$b_mkt, ls$b_smb, ls$b_hml))

Factor loadings. The market loading of LS (EW) is -0.06 (t = -0.9), against 0.99 for Q1 (EW) and 1.00 for 0050. Q1 and 0050 are mostly market bets, while LS is close to market-neutral because the long and short legs carry similar factor exposure. This is what the residual signal is designed to do: the ranking uses the part of last month’s return that the three factors do not explain, so the long-short portfolio should earn from stock-specific reversal and not from a factor tilt. LS loadings on SMB (-0.17) and HML (-0.02) show how much size or value exposure is left.

show code
cat(sprintf(
"**Benchmarks.** Long-only Q1 (EW) returns %s a year with a Sharpe ratio of %.2f, compared with %s and %.2f for 0050 and %s and %.2f for TAIEX_TR. LS returns %s a year with a Sharpe ratio of %.2f, but this is not like-for-like: LS is a zero-investment, market-neutral portfolio that needs short selling and margin, and its return is a spread, not a return on invested capital. 0050 and TAIEX_TR are fully invested long-only portfolios that carry market risk, so their Sharpe ratios and drawdowns answer a different question.\n\n",
  pct(q1$ann_ret, 1), q1$sharpe, pct(b50$ann_ret, 1), b50$sharpe, pct(tx$ann_ret, 1), tx$sharpe,
  pct(ls$ann_ret, 1), ls$sharpe))

Benchmarks. Long-only Q1 (EW) returns 14.1% a year with a Sharpe ratio of 1.01, compared with -0.2% and 0.01 for 0050 and 1.0% and 0.10 for TAIEX_TR. LS returns 34.1% a year with a Sharpe ratio of 4.32, but this is not like-for-like: LS is a zero-investment, market-neutral portfolio that needs short selling and margin, and its return is a spread, not a return on invested capital. 0050 and TAIEX_TR are fully invested long-only portfolios that carry market risk, so their Sharpe ratios and drawdowns answer a different question.

show code
cat(sprintf(
"**Why the results may be hard to earn in practice.** (1) *Turnover and costs:* the average monthly turnover is %s for Q1 (EW) and %s for LS (EW); with a 0.3%% securities transaction tax on every sale plus brokerage fees and price impact, a high-turnover strategy can lose much of its alpha. (2) *Short selling:* Taiwan restricts short selling, borrowing costs and availability vary by stock, and the short leg is the hardest to implement; the ±10%% daily price limit can also delay trades after extreme moves. (3) *Sample and estimation noise:* 60 holding months is a short sample, and each residual comes from a 36-month regression, so the signal is noisy and the result may not repeat.\n",
  pct(q1$turnover, 0), pct(ls$turnover, 0)))

Why the results may be hard to earn in practice. (1) Turnover and costs: the average monthly turnover is 85% for Q1 (EW) and 86% for LS (EW); with a 0.3% securities transaction tax on every sale plus brokerage fees and price impact, a high-turnover strategy can lose much of its alpha. (2) Short selling: Taiwan restricts short selling, borrowing costs and availability vary by stock, and the short leg is the hardest to implement; the ±10% daily price limit can also delay trades after extreme moves. (3) Sample and estimation noise: 60 holding months is a short sample, and each residual comes from a 36-month regression, so the signal is noisy and the result may not repeat.

show code
sessionInfo()$R.version$version.string
[1] "R version 4.5.3 (2026-03-11 ucrt)"