Take-Home Project, Part 3: Residual reversal, 100 largest Taiwan stocks

Base R only. No packages to install.

HOW TO RUN

1. Put this file in your project folder. Inside it, make a folder “raw” with

- your TEJ monthly stock file(s): ticker, month, adjusted price, market cap

- your monthly Fama-French file: month, market premium, SMB, HML, rf

- etf0050_monthly.txt (optional: public fallback is built in)

- taiex_tr_monthly.txt (optional: downloaded from TWSE if missing)

2. In RStudio: Session > Set Working Directory > To Source File Location,

then click Source. Or in a terminal: Rscript part3_residual_reversal.R

3. To test that the code runs before adding data, set DEMO <- TRUE.

DEMO results are random numbers. Never submit them.

—————————————————————————

0. Settings (normally only this block ever needs editing)

—————————————————————————

DEMO <- FALSE # TRUE = run on simulated data (code test only) RUN_OPTIONAL <- TRUE # D1 to D4 (bonus) RAW_DIR <- “raw”

Leave NULL for automatic detection. Set only if the script asks you to.

STOCK_FILES <- NULL # e.g. c(“raw/stock_monthly.txt”, “raw/adj_price.txt”) FACTOR_FILE <- NULL # e.g. “raw/ff3_monthly.txt” COL_ID <- NULL # exact column names in your stock file(s) COL_MONTH <- NULL COL_ADJPRICE <- NULL # must be the ADJUSTED price column COL_MKTCAP <- NULL COL_MKT <- NULL; COL_SMB <- NULL; COL_HML <- NULL; COL_RF <- NULL FACTOR_FILTER <- NULL # if the factor file has several rows per month, e.g. # list(column = “id”, value = “TSE”) FACTOR_UNIT <- “auto” # “auto”, “percent” or “decimal” RF_BASIS <- “auto” # “auto”, “annual” or “monthly”

ROUND_TRIP_COST <- 0.001425 * 2 + 0.003 # 2 x 0.1425% commission + 0.3% sales tax

—————————————————————————

Helpers

—————————————————————————

OUT_DIR <- if (DEMO) “output_demo” else “output” dir.create(OUT_DIR, showWarnings = FALSE) LOG <- file.path(OUT_DIR, “checks_log.txt”) cat(““, file = LOG)

say <- function(…) { msg <- paste0(…) cat(msg, sep = “”) cat(msg, file = LOG, sep = “”, append = TRUE) } hdr <- function(x) { say(” “); say(”========== “, x,” ==========“) } show_obj <- function(x) say(capture.output(print(x))) check <- function(ok, label) { say(sprintf(”[%s] %s”, if (isTRUE(ok)) “PASS” else “FAIL”, label)) if (!isTRUE(ok)) stop(“Check failed:”, label, call. = FALSE) }

mi_of <- function(ym) (ym %/% 100) * 12 + (ym %% 100) - 1 # month index ym_of <- function(mi) (mi %/% 12) * 100 + (mi %% 12) + 1

normalise <- function(x) tolower(gsub(“[[:space:]_.-]”, ““, gsub(”“,”“, x)))

read_any <- function(path) { bytes <- readBin(path, “raw”, n = file.info(path)\(size) if (length(bytes) < 3) stop("File is empty: ", path) if (bytes[1] == as.raw(0xFF) && bytes[2] == as.raw(0xFE)) { txt <- iconv(list(bytes[-(1:2)]), from = "UTF-16LE", to = "UTF-8") } else if (bytes[1] == as.raw(0xFE) && bytes[2] == as.raw(0xFF)) { txt <- iconv(list(bytes[-(1:2)]), from = "UTF-16BE", to = "UTF-8") } else if (any(bytes == as.raw(0))) { txt <- iconv(list(bytes), from = "UTF-16LE", to = "UTF-8") } else { if (bytes[1] == as.raw(0xEF) && bytes[2] == as.raw(0xBB) && bytes[3] == as.raw(0xBF)) bytes <- bytes[-(1:3)] txt <- rawToChar(bytes) if (validUTF8(txt)) { Encoding(txt) <- "UTF-8" } else { txt <- iconv(txt, from = "CP950", to = "UTF-8", sub = "?") # Big5 } } if (is.na(txt)) stop("Could not decode the text encoding of ", path) lines <- strsplit(txt, "\r\n|\n|\r")[[1]] lines <- lines[nzchar(trimws(lines))] sep <- if (grepl("\t", lines[1])) "\t" else if (grepl(",", lines[1])) "," else if (grepl(";", lines[1])) ";" else "" if (nzchar(sep)) lines <- sub(paste0(sep, "+\)“),”“, lines) read.table(text = lines, sep = sep, header = TRUE, quote =”"“, comment.char =”“, check.names = FALSE, colClasses =”character”, fill = TRUE, strip.white = TRUE, row.names = NULL) }

find_col <- function(df, aliases, override = NULL) { nm <- normalise(names(df)) if (!is.null(override)) { j <- which(nm == normalise(override)) return(if (length(j)) j[1] else NA_integer_) } bare <- gsub(“\([^)]\)|[^\uff09]”, ““, nm) # drop”(unit)” for (a in normalise(aliases)) { j <- which(nm == a) if (length(j)) return(j[1]) } for (a in normalise(aliases)) { j <- which(bare == a) if (length(j)) return(j[1]) } NA_integer_ }

ID_NAMES <- c(“ticker”, “stock_id”, “co_id”, “coid”, “symbol”, “code”, “id”, “b49238ee38bc”, “b49238ee365f”, “16c3f8ee38bc”, “0a1968ee365f”, “0a1968ee38bc”, “16c3f8”, “ee365f”) MONTH_NAMES <- c(“ym”, “yyyymm”, “form_ym”, “month”, “mdate”, “date”, “e74708”, “e747085e5”, “cc75995e571f”, “5e571f”) ADJ_NAMES <- c(“adj_close”, “close_adj”, “adj_price”, “price_adj”, “adjusted_close”, “adjusted_price”, “adj_prc”, “prc_adj”, “adjclose”, “close_a”, “abf5745366e40f9”, “abf574f8c5366e40f9”, “5366e40f9_abf574”, “5366e40f9(abf574)”, “5366e40f9(143)abf574”, ”664b0a06fabf5745366e40f9”, ”08439f5366e40f9”) PLAIN_PRICE_NAMES <- c(”close”, ”price”, ”5366e40f9”, ”5366e40f9(143)”, ”5366e40f9(143)708”) CAP_NAMES <- c(“mktcap”, “mkt_cap”, “market_cap”, “marketcap”, “mcap”, “me”, “mv”, “market_value”, “e0203c”, “e0203c(67e42c143)”, “e3de0203c”, “e0203c(67e42c)”) MKT_NAMES <- c(“mkt”, “mktrf”, “mkt_rf”, “mkt_excess”, “rm_rf”, “rmrf”, “mrp”, “e028348a86aaea216c”, “e028348a86aaea216c(%)”, “e02834ea216c”) SMB_NAMES <- c(“smb”, “smb3”, “98fa21ea216c(36e0b50)”, “98fa21ea216c”, “98fa216e0b50”) HML_NAMES <- c(“hml”, “hml3”, “de803ce020f9bd4ea216c”, “de803ce020f9bd4ea216c(36e0b50)”, “e33762e0203cbd4ea216c”, “0f903c6e0b50”) RF_NAMES <- c(“rf”, “risk_free”, “riskfree”, “rf_rate”, “1218a86aa229387”, “1218a86aa229387(%)”)

parse_date <- function(x) { u <- unique(x) one <- function(s) { s <- sub(“[ T][0-9]{1,2}:.\(", "", trimws(s)) s <- gsub("^-|-\)“,”“, gsub(”[^0-9]+“,”-“, s)) y <- m <- NA_integer_; d <- 0L if (is.na(s) || !nzchar(s)) return(c(NA, NA)) if (grepl(”-“, s)) { p <- as.integer(strsplit(s,”-“)[[1]]) y <- p[1]; m <- p[2]; if (length(p) > 2) d <- p[3] } else { n <- nchar(s) if (n %in% c(7, 8)) { y <- as.integer(substr(s, 1, n - 4)); m <- as.integer(substr(s, n - 3, n - 2)) d <- as.integer(substr(s, n - 1, n)) } else if (n %in% c(5, 6)) { y <- as.integer(substr(s, 1, n - 2)); m <- as.integer(substr(s, n - 1, n)) } } if (is.na(y) || is.na(m) || m < 1 || m > 12) return(c(NA, NA)) if (y < 1911) y <- y + 1911L # Taiwan (ROC) years c(y 100 + m, d) } res <- vapply(u, function(s) as.numeric(one(s)), numeric(2), USE.NAMES = FALSE) k <- match(x, u) list(ym = res[1, k], day = res[2, k]) }

to_num <- function(x) { x <- gsub(“,”, ““, trimws(x)) x[x %in% c(””, ”-”, ”–”, ”NA”, ”NaN”, ”.”)] <- NA suppressWarnings(as.numeric(x)) } clean_ticker <- function(x) sub(”^([0-9A-Za-z]+).*$“,”\1”, trimws(x))

—————————————————————————

Simulated data (only when DEMO = TRUE)

—————————————————————————

if (DEMO) { set.seed(1) RAW_DIR <- “raw_demo” dir.create(RAW_DIR, showWarnings = FALSE) STOCK_FILES <- NULL; FACTOR_FILE <- NULL; FACTOR_FILTER <- NULL COL_ID <- COL_MONTH <- COL_ADJPRICE <- COL_MKTCAP <- NULL COL_MKT <- COL_SMB <- COL_HML <- COL_RF <- NULL FACTOR_UNIT <- RF_BASIS <- “auto” d_mi <- mi_of(201712):mi_of(202512); T_ <- length(d_mi); N_ <- 450 d_f <- data.frame(ym = ym_of(d_mi), mkt = rnorm(T_, 0.9, 4.5), smb = rnorm(T_, 0, 2.5), hml = rnorm(T_, 0.2, 2.5), rf = 1.2) ids <- c(“2330”, as.character(setdiff(1101:1700, 2330))[seq_len(N_ - 1)]) beta <- cbind(rnorm(N_, 1, 0.3), rnorm(N_, 0.2, 0.4), rnorm(N_, 0, 0.4)) d_r <- as.matrix(d_f[, 2:4]) %% t(beta) / 100 + 0.001 + matrix(rnorm(T_ N_, 0, 0.08), T_, N_) d_r <- pmax(d_r, -0.8) d_p <- apply(1 + d_r, 2, cumprod) * 50 shares <- exp(rnorm(N_, 6, 1.2)); shares[1] <- 1e6 d_s <- data.frame(ticker = rep(ids, each = T_), ym = rep(ym_of(d_mi), N_), adj_close = round(as.vector(d_p), 6), mktcap = round(as.vector(sweep(d_p, 2, shares, “”)), 2)) gone <- ids[2:15]; late <- ids[16:30] d_s <- d_s[!(d_s\(ticker %in% gone & d_s\)ym > 202306) & !(d_s\(ticker %in% late & d_s\)ym < 202003), ] wt <- function(x, f) write.table(x, file.path(RAW_DIR, f), sep = ”, row.names = FALSE, quote = FALSE) wt(d_s, ”stock_monthly.txt”); wt(d_f, ”ff3_monthly.txt”) bm_ym <- ym_of(mi_of(202012):mi_of(202512)) wt(data.frame(id = ”0050”, month = bm_ym, level = 25 cumprod(1 + rnorm(61, 0.012, 0.05))),”etf0050_monthly.txt”) wt(data.frame(id = “TAIEX_TR”, month = bm_ym, level = 25000 * cumprod(1 + rnorm(61, 0.011, 0.045))), “taiex_tr_monthly.txt”) say(“*** DEMO MODE: all numbers below are SIMULATED. Do not submit them. ***“) }

—————————————————————————

R1. Data and universe

—————————————————————————

hdr(“R1. Data and universe”) if (!dir.exists(RAW_DIR)) stop(“Folder ‘“, RAW_DIR,”’ not found in”, getwd(), “.the working directory to your project folder and put the TEJ files in raw/.”, “(Or set DEMO <- TRUE to test the code.)”, call. = FALSE)

all_files <- list.files(RAW_DIR, pattern = “\.(txt|csv|tsv)$”, full.names = TRUE, ignore.case = TRUE) bench_names <- c(“etf0050_monthly.txt”, “taiex_tr_monthly.txt”) candidates <- all_files[!tolower(basename(all_files)) %in% bench_names] candidates <- unique(c(candidates, STOCK_FILES, FACTOR_FILE)) if (!length(candidates)) stop(“No stock or factor files found in ‘“, RAW_DIR,”’.”, call. = FALSE)

tables <- list() for (f in candidates) { tb <- tryCatch(read_any(f), error = function(e) { say(“Could not read”, f, “:”, conditionMessage(e)); NULL }) if (!is.null(tb)) tables[[f]] <- tb }

is_factor_table <- function(tb) !is.na(find_col(tb, SMB_NAMES, COL_SMB)) && !is.na(find_col(tb, HML_NAMES, COL_HML)) factor_hits <- names(tables)[vapply(tables, is_factor_table, logical(1))] if (is.null(FACTOR_FILE)) { if (length(factor_hits) != 1) stop(“Expected exactly one Fama-French file, found”, length(factor_hits), “:”, paste(factor_hits, collapse = “,”), “FACTOR_FILE (and COL_SMB / COL_HML if needed) in the settings block.”, call. = FALSE) FACTOR_FILE <- factor_hits }

stock_candidates <- if (is.null(STOCK_FILES)) setdiff(names(tables), factor_hits) else STOCK_FILES adj_list <- list(); cap_list <- list(); seen <- character(0) for (f in stock_candidates) { tb <- tables[[f]] if (is.null(tb)) next j_id <- find_col(tb, ID_NAMES, COL_ID) j_mo <- find_col(tb, MONTH_NAMES, COL_MONTH) j_ad <- find_col(tb, ADJ_NAMES, COL_ADJPRICE) # A plain “close” column counts as adjusted only if the file name says so if (is.na(j_ad) && is.null(COL_ADJPRICE) && grepl(“adj|abf574|08439f”, basename(f), ignore.case = TRUE)) j_ad <- find_col(tb, PLAIN_PRICE_NAMES) j_cp <- find_col(tb, CAP_NAMES, COL_MKTCAP) seen <- c(seen, paste0(” “, f,”: “, paste(names(tb), collapse =” | “))) if (is.na(j_id) || is.na(j_mo) || (is.na(j_ad) && is.na(j_cp))) next dt <- parse_date(tb[[j_mo]]) base <- data.frame(ticker = clean_ticker(tb[[j_id]]), ym = dt\(ym, day = dt\)day, stringsAsFactors = FALSE) if (!is.na(j_ad)) adj_list[[f]] <- cbind(base, value = to_num(tb[[j_ad]])) if (!is.na(j_cp)) cap_list[[f]] <- cbind(base, value = to_num(tb[[j_cp]])) say(”Stock file: “, f,” | id = “, names(tb)[j_id],” | month = “, names(tb)[j_mo],” | adjusted price = “, if (is.na(j_ad))”-” else names(tb)[j_ad], ” | market cap = “, if (is.na(j_cp))”-” else names(tb)[j_cp]) } if (!length(adj_list) || !length(cap_list)) stop(“Could not identify the”, if (!length(adj_list)) “ADJUSTED PRICE” else “MARKET CAP”, ” column. Columns found:“, paste(seen, collapse =”“),”the adjusted-price file calls its column just ‘close’, put ‘adj’ in the file name.”, “set COL_ID, COL_MONTH, COL_ADJPRICE, COL_MKTCAP in the settings block.”, call. = FALSE)

tidy_values <- function(lst, label) { d <- do.call(rbind, lst) d <- d[!is.na(d\(ym) & nzchar(d\)ticker) & !is.na(d\(value) & d\)value > 0, ] d <- unique(d) if (label == “adj_price” && any(duplicated(d[, c(“ticker”, “ym”, “day”)]))) stop(“Two different adjusted prices for the same stock and date. An unadjusted”, “column is probably being mixed in: set STOCK_FILES / COL_ADJPRICE.”, call. = FALSE) d <- d[order(d\(ticker, d\)ym, d$day), ] dup <- duplicated(d[, c(“ticker”, “ym”)], fromLast = TRUE) say(sprintf(“%s: %d extra rows for the same stock-month removed (latest date kept)”, label, sum(dup))) d <- d[!dup, c(“ticker”, “ym”, “value”)] names(d)[3] <- label d } adj <- tidy_values(adj_list, “adj_price”) cap <- tidy_values(cap_list, “mktcap”) stock <- merge(adj, cap, by = c(“ticker”, “ym”), all = TRUE)

Common stocks: 4-digit codes, no ETFs (00xx) and no TDRs (91xx)

stock <- stock[grepl(“^[1-9][0-9]{3}\(", stock\)ticker) & !grepl(”^91”, stock\(ticker), ] stock <- stock[stock\)ym >= 201712 & stock\(ym <= 202512, ] check(nrow(stock) > 0, "stock data found between 2017-12 and 2025-12") check(!any(duplicated(stock[, c("ticker", "ym")])), "no duplicate stock-month rows") say(sprintf("Common-stock panel: %d rows, %d stocks, months %d to %d", nrow(stock), length(unique(stock\)ticker)), min(stock\(ym), max(stock\)ym))) check(min(stock\(ym) <= 201712 && max(stock\)ym) >= 202512, “stock data cover 2017-12 through 2025-12”)

months <- mi_of(201712):mi_of(202512) tickers <- sort(unique(stock\(ticker)) pos <- cbind(match(mi_of(stock\)ym), months), match(stock\(ticker, tickers)) P <- matrix(NA_real_, length(months), length(tickers), dimnames = list(ym_of(months), tickers)) MC <- P P[pos] <- stock\)adj_price MC[pos] <- stock$mktcap # Return is NA (never zero) whenever this month’s or last month’s price is missing RET <- P * NA_real_ RET[-1, ] <- P[-1, , drop = FALSE] / P[-nrow(P), , drop = FALSE] - 1

form_mi <- mi_of(202012):mi_of(202511) hold_mi <- form_mi + 1 hold_ym <- ym_of(hold_mi)

universe_at <- function(mi, N = 100, liquid = FALSE) { i <- match(mi, months) cp <- MC[i, ] ok <- is.finite(cp) if (liquid) { # proxy filter: a return in each of the last 12 months, and not in the # smallest 20% of stocks by market cap that month traded <- colSums(is.finite(RET[(i - 11):i, , drop = FALSE])) == 12 ok <- ok & traded & cp >= quantile(cp[ok], 0.20, names = FALSE) } id <- tickers[ok] id <- id[order(-cp[ok], id)] head(id, N) } universe <- lapply(form_mi, universe_at) n_univ <- vapply(universe, length, integer(1)) check(length(form_mi) == 60, “60 formation months (2020-12 to 2025-11)”) check(all(n_univ == 100), “100 stocks in every formation month”)

Factors ———————————————————————

ff <- if (!is.null(tables[[FACTOR_FILE]])) tables[[FACTOR_FILE]] else read_any(FACTOR_FILE) if (!is.null(FACTOR_FILTER)) { j <- find_col(ff, FACTOR_FILTER\(column, FACTOR_FILTER\)column) ff <- ff[trimws(ff[[j]]) == FACTOR_FILTER\(value, , drop = FALSE] } cols <- c(month = find_col(ff, MONTH_NAMES, COL_MONTH), mkt = find_col(ff, MKT_NAMES, COL_MKT), smb = find_col(ff, SMB_NAMES, COL_SMB), hml = find_col(ff, HML_NAMES, COL_HML), rf = find_col(ff, RF_NAMES, COL_RF)) if (is.na(cols["month"])) cols["month"] <- find_col(ff, MONTH_NAMES) if (any(is.na(cols))) stop("Factor file: could not find column(s) ", paste(names(cols)[is.na(cols)], collapse = ", "), ".\nColumns are: ", paste(names(ff), collapse = " | "), "\nSet COL_MKT, COL_SMB, COL_HML, COL_RF in the settings block.", call. = FALSE) fac <- data.frame(ym = parse_date(ff[[cols["month"]]])\)ym, mkt = to_num(ff[[cols[“mkt”]]]), smb = to_num(ff[[cols[“smb”]]]), hml = to_num(ff[[cols[“hml”]]]), rf = to_num(ff[[cols[“rf”]]])) fac <- unique(fac[!is.na(fac\(ym) & fac\)ym >= 201712 & fac\(ym <= 202512, ]) if (any(duplicated(fac\)ym))) stop(“Factor file has several rows per month. Set FACTOR_FILTER in the settings block.”, “Columns are:”, paste(names(ff), collapse = ” | “), call. = FALSE) unit <- FACTOR_UNIT if (unit ==”auto”) unit <- if (median(abs(fac\(mkt), na.rm = TRUE) > 0.3) "percent" else "decimal" if (unit == "percent") fac[, c("mkt", "smb", "hml", "rf")] <- fac[, c("mkt", "smb", "hml", "rf")] / 100 basis <- RF_BASIS if (basis == "auto") basis <- if (median(fac\)rf, na.rm = TRUE) > 0.004) “annual” else “monthly” if (basis == “annual”) fac\(rf <- fac\)rf / 12 say(sprintf(“Factors: %s | input unit = %s | rf quoted %s | mean monthly rf used = %.5f”, FACTOR_FILE, unit, basis, mean(fac\(rf, na.rm = TRUE))) FM <- as.matrix(fac[match(ym_of(months), fac\)ym), c(“mkt”, “smb”, “hml”, “rf”)]) need <- months >= mi_of(201801) check(all(is.finite(FM[need, ])), “factors complete for 2018-01 through 2025-12”)

Benchmarks ——————————————————————-

bench_ym <- ym_of(mi_of(202012):mi_of(202512))

read_benchmark <- function(path) { tb <- read_any(path) j_mo <- find_col(tb, MONTH_NAMES) j_lv <- find_col(tb, c(“level”, ADJ_NAMES, “adj”, “value”, “index”, “307578”, “5366e4307578”, “83116c307578”, PLAIN_PRICE_NAMES)) if (is.na(j_mo) || is.na(j_lv)) stop(path, ” needs the columns id, month, level. Found: “, paste(names(tb), collapse =” | “), call. = FALSE) dt <- parse_date(tb[[j_mo]]) d <- data.frame(ym = dt\(ym, day = dt\)day, level = to_num(tb[[j_lv]])) d <- d[!is.na(d\(ym) & !is.na(d\)level), ] d <- d[order(d\(ym, d\)day), ] d <- d[!duplicated(d\(ym, fromLast = TRUE), ] d\)level[match(bench_ym, d$ym)] }

Public fallback for 0050: month-end adjusted prices, retrieved 2026-11-28 from

https://www.digrin.com/stocks/detail/0050.TW/price (Dec 2020 to Dec 2025)

ETF0050_PUBLIC <- c( 25.87, 27.72, 28.84, 29.13, 30.40, 29.64, 30.04, 29.49, 30.42, 29.71, 29.44, 29.91, 31.54, 31.36, 30.68, 30.59, 28.52, 28.75, 25.65, 26.55, 26.46, 23.28, 22.29, 26.18, 24.80, 27.21, 27.32, 27.96, 27.00, 29.01, 29.69, 30.05, 29.33, 28.62, 28.27, 30.65, 31.60, 32.08, 34.22, 37.70, 37.79, 39.64, 44.52, 43.40, 43.52, 44.15, 46.03, 44.94, 46.98, 48.98, 46.84, 42.03, 41.02, 43.74, 47.07, 50.52, 51.46, 56.65, 63.46, 61.11, 64.30)

download_taiex_tr <- function(path) { say(“Downloading the TAIEX total return index from TWSE (about 4 minutes) …”) out <- data.frame(id = “TAIEX_TR”, month = bench_ym, level = NA_real_) pat <- “\["[0-9]{2,3}/[0-9]{2}/[0-9]{2}","[0-9,.]+"” for (k in seq_along(bench_ym)) { urls <- sprintf(c(“https://www.twse.com.tw/rwd/zh/TAIEX/MFI94U?date=%d01&response=json”, “https://www.twse.com.tw/indicesReport/MFI94U?response=json&date=%d01”), bench_ym[k]) for (attempt in 1:4) { txt <- tryCatch(suppressWarnings(paste(readLines(urls[(attempt - 1) %% 2 + 1], warn = FALSE, encoding = “UTF-8”), collapse = ““)), error = function(e)”“) txt <- gsub(”[[:space:]]“,”“, gsub(”\/“,”/“, txt, fixed = TRUE)) rows <- regmatches(txt, gregexpr(pat, txt))[[1]] if (length(rows)) { v <- do.call(rbind, strsplit(gsub(”^\["|"\(", "", rows), "\",\"")) dt <- parse_date(v[, 1]) keep <- which(dt\)ym == bench_ym[k]) if (length(keep)) { last <- keep[which.max(dt\(day[keep])] out\)level[k] <- to_num(v[last, 2]) } } Sys.sleep(3) # TWSE blocks rapid requests if (!is.na(out\(level[k])) break } if (is.na(out\)level[k])) stop(“TAIEX total return download failed at”, bench_ym[k], “.”, “Download it by hand from the TWSE website (67a84c1cf2a0b0a0a10f983116c307578) and save it as”, path, ” with columns id, month, level (months 202012 to 202512).”, call. = FALSE) if (k %% 12 == 1) say(” got “, bench_ym[k],”: “, out$level[k]) } write.table(out, path, sep =”, row.names = FALSE, quote = FALSE) }

p0050 <- file.path(RAW_DIR, “etf0050_monthly.txt”) if (file.exists(p0050)) { lvl_0050 <- read_benchmark(p0050); say(“0050 prices:”, p0050) } else { lvl_0050 <- ETF0050_PUBLIC say(“0050 prices: built-in public series (digrin.com). Use your Part 2 file if you have it.”) } ptr <- file.path(RAW_DIR, “taiex_tr_monthly.txt”) if (!file.exists(ptr)) download_taiex_tr(ptr) lvl_tr <- read_benchmark(ptr); say(“TAIEX total return index:”, ptr)

check(length(lvl_0050) == 61 && all(is.finite(lvl_0050)), “0050 has all 61 month-ends”) check(length(lvl_tr) == 61 && all(is.finite(lvl_tr)), “TAIEX_TR has all 61 month-ends”) ret_0050 <- lvl_0050[-1] / lvl_0050[-61] - 1 ret_tr <- lvl_tr[-1] / lvl_tr[-61] - 1 r_split <- ret_0050[hold_ym == 202506] check(r_split > -0.5, sprintf(“no split jump in 0050 in 2025-06 (return = %.2f%%)”, 100 * r_split))

—————————————————————————

R2. Residual signal

—————————————————————————

build_signals <- function(N = 100, window = 36, minobs = 30, liquid = FALSE) { out <- vector(“list”, length(form_mi)) for (k in seq_along(form_mi)) { i <- match(form_mi[k], months) ids <- universe_at(form_mi[k], N, liquid) rows <- max(1, i - window + 1):i # ends in formation month t X <- cbind(1, FM[rows, c(“mkt”, “smb”, “hml”), drop = FALSE]) Y <- RET[rows, ids, drop = FALSE] - FM[rows, “rf”] x_ok <- is.finite(rowSums(X)) n <- length(ids) n_obs <- integer(n); e_t <- sig <- z <- rep(NA_real_, n); status <- rep(“ok”, n) for (s in seq_len(n)) { ok <- x_ok & is.finite(Y[, s]) n_obs[s] <- sum(ok) if (!ok[length(ok)]) { status[s] <- “no_return_in_t”; next } if (n_obs[s] < minobs) { status[s] <- “too_few_obs”; next } fit <- lm.fit(X[ok, , drop = FALSE], Y[ok, s]) e <- fit$residuals sig[s] <- sqrt(sum(e^2) / (n_obs[s] - 4)) e_t[s] <- e[length(e)] z[s] <- e_t[s] / sig[s] } status[status == “ok” & !is.finite(z)] <- “no_signal” out[[k]] <- data.frame(form_ym = ym_of(form_mi[k]), ticker = ids, mktcap = unname(MC[i, ids]), raw_ret = unname(RET[i, ids]), n_obs = n_obs, window_start = ym_of(months[min(rows)]), window_end = ym_of(months[max(rows)]), resid = e_t, sigma = sig, z = z, status = status, stringsAsFactors = FALSE) } do.call(rbind, out) }

hdr(“R2. Residual signal”) signals <- build_signals() year <- signals\(form_ym %/% 100 signal_counts <- do.call(rbind, lapply(sort(unique(year)), function(y) { d <- signals[year == y, ] data.frame(formation_year = y, stock_months = nrow(d), valid = sum(d\)status == “ok”), distinct_valid_stocks = length(unique(d\(ticker[d\)status == “ok”])), dropped_too_few_obs = sum(d\(status == "too_few_obs"), dropped_no_return_t = sum(d\)status == “no_return_in_t”), dropped_other = sum(d\(status == "no_signal")) })) show_obj(signal_counts) write.csv(signal_counts, file.path(OUT_DIR, "signal_counts.csv"), row.names = FALSE) check(max(signals\)n_obs) <= 36, “regression window has at most 36 months”) check(all(signals\(window_end == signals\)form_ym), “every window ends in the formation month”) check(min(signals\(window_start) == 201801, "first window starts 2018-01") check(all(signals\)n_obs[signals$status == “ok”] >= 30), “valid signals have 30+ observations”)

Worked example with lm()

valid <- signals[signals\(status == "ok", ] ex <- valid[valid\)ticker == “2330” & valid\(form_ym == 202012, ] if (!nrow(ex)) ex <- valid[1, ] i <- match(mi_of(ex\)form_ym), months); rows <- (i - 35):i exd <- data.frame(ym = ym_of(months[rows]), excess = RET[rows, ex\(ticker] - FM[rows, "rf"], FM[rows, c("mkt", "smb", "hml")]) exd <- exd[complete.cases(exd), ] m <- lm(excess ~ mkt + smb + hml, data = exd) say("\n", sprintf("Worked example: stock %s, formation month %d", ex\)ticker, ex\(form_ym)) show_obj(summary(m)) hand_e <- unname(tail(residuals(m), 1)) hand_s <- sqrt(sum(residuals(m)^2) / (nrow(exd) - 4)) say(sprintf("residual e_t = %.6f | sigma = sqrt(SSR/(n-4)) = %.6f | n = %d", hand_e, hand_s, nrow(exd))) say(sprintf("z by hand = e_t / sigma = %.6f | z in table = %.6f", hand_e / hand_s, ex\)z)) check(isTRUE(all.equal(hand_s, summary(m)\(sigma)), "sigma by hand equals lm() residual std. error") check(isTRUE(all.equal(hand_e / hand_s, ex\)z)), “z by hand equals the signal used”)

—————————————————————————

R3 and R4. Holdings, weights, returns, turnover

—————————————————————————

build_portfolios <- function(sig, key = “z”) { sig <- sig[sig\(status == "ok", ] H <- lapply(seq_along(form_mi), function(k) { d <- sig[sig\)form_ym == ym_of(form_mi[k]), ] if (nrow(d) < 5) stop(“Fewer than 5 valid stocks in”, ym_of(form_mi[k])) d <- d[order(d[[key]], d\(ticker), ] n <- nrow(d) d\)quintile <- ceiling(seq_len(n) * 5 / n) # 1 = lowest signal d\(hold_ym <- hold_ym[k] d\)hold_ret <- unname(RET[match(hold_mi[k], months), d\(ticker]) has <- is.finite(d\)hold_ret) one <- rep(1, n) d\(w_ew_form <- one / ave(one, d\)quintile, FUN = sum) d\(w_vw_form <- d\)mktcap / ave(d\(mktcap, d\)quintile, FUN = sum) # drop stocks without a holding-month return and rescale d\(w_ew <- has / ave(as.numeric(has), d\)quintile, FUN = sum) d\(w_vw <- d\)mktcap * has / ave(d\(mktcap * has, d\)quintile, FUN = sum) d }) hold <- do.call(rbind, H)

nm <- c(paste0(“Q”, 1:5, “EW”), paste0(”Q”, 1:5, ”VW”), ”LS_EW”, ”LS_VW”) R <- TO <- matrix(NA_real, 60, 12, dimnames = list(hold_ym, nm)) for (wt in c(”EW”, ”VW”)) for (q in 1:5) { col <- paste0(”Q”, q, ””, wt); w <- paste0(“w_”, tolower(wt)) old <- NULL for (k in 1:60) { d <- H[[k]][H[[k]]\(quintile == q & is.finite(H[[k]]\)hold_ret), ] R[k, col] <- sum(d[[w]] * d\(hold_ret) new <- setNames(d[[w]], d\)ticker) if (!is.null(old)) { id <- union(names(old), names(new)) a <- setNames(numeric(length(id)), id); b <- a a[names(old)] <- old; b[names(new)] <- new TO[k, col] <- 0.5 * sum(abs(b - a)) } grown <- d[[w]] * (1 + d\(hold_ret) # drifted old weights old <- setNames(grown / sum(grown), d\)ticker) } } for (wt in c(“EW”, “VW”)) { ls <- paste0(“LS_”, wt); q1 <- paste0(“Q1_”, wt); q5 <- paste0(“Q5_”, wt) R[, ls] <- R[, q1] - R[, q5] TO[, ls] <- (TO[, q1] + TO[, q5]) / 2 } list(holdings = hold, returns = R, turnover = TO) }

hdr(“R3. Quintile holdings”) base <- build_portfolios(signals, “z”) h <- base\(holdings sizes <- table(h\)form_ym, h\(quintile) check(all(apply(sizes, 1, function(x) diff(range(x))) <= 1), "quintile sizes differ by at most one stock in every month") for (w in c("w_ew_form", "w_vw_form", "w_ew", "w_vw")) { s <- tapply(h[[w]], list(h\)form_ym, h\(quintile), sum) check(all(abs(s - 1) < 1e-10), paste("weights add up to 1:", w)) } n_miss <- sum(!is.finite(h\)hold_ret)) say(sprintf(“Missing holding-month return: %d of %d stock-months (%.3f%%), in %d of 60 months”, n_miss, nrow(h), 100 * n_miss / nrow(h), length(unique(h\(form_ym[!is.finite(h\)hold_ret)])))) if (n_miss) show_obj(h[!is.finite(h$hold_ret), c(“form_ym”, “hold_ym”, “ticker”, “quintile”)]) say(“Quintile sizes (min and max across months):”) show_obj(apply(sizes, 2, range))

hdr(“R4. Portfolio returns”) univ_ret <- t(vapply(seq_along(form_mi), function(k) { ids <- universe[[k]] r <- RET[match(hold_mi[k], months), ids]; cp <- MC[match(form_mi[k], months), ids] ok <- is.finite(r) c(mean(r[ok]), sum(r[ok] * cp[ok]) / sum(cp[ok])) }, numeric(2))) ALL <- cbind(base$returns, “0050” = ret_0050, TAIEX_TR = ret_tr, EW_universe = univ_ret[, 1], VW_universe = univ_ret[, 2]) check(ncol(ALL) == 16 && nrow(ALL) == 60 && all(is.finite(ALL)), “16 series, each with 60 monthly returns”)

portfolio_returns <- data.frame(portfolio = rep(colnames(ALL), each = 60), hold_ym = rep(hold_ym, 16), ret = as.vector(ALL)) check(nrow(portfolio_returns) == 960, “portfolio_returns has 960 rows”)

—————————————————————————

R5. Performance table

—————————————————————————

hf <- as.data.frame(FM[match(hold_mi, months), ]) # factors of holding month

nw_t <- function(fit, L = 3) { # Newey-West t-statistics X <- model.matrix(fit); u <- X * residuals(fit); n <- nrow(X) S <- crossprod(u) for (l in seq_len(L)) { G <- crossprod(u[(l + 1):n, , drop = FALSE], u[1:(n - l), , drop = FALSE]) S <- S + (1 - l / (L + 1)) * (G + t(G)) } B <- solve(crossprod(X)) coef(fit) / sqrt(diag(B %% S %% B)) }

perf_one <- function(r, name, turnover = NA_real_, idx = seq_along(r)) { r <- r[idx]; f <- hf[idx, ]; n <- length(r) zero_inv <- grepl(“^LS”, name) exc <- if (zero_inv) r else r - f\(rf fit <- lm(exc ~ mkt + smb + hml, data = cbind(exc = exc, f)) co <- summary(fit)\)coefficients wealth <- cumprod(1 + r) data.frame(portfolio = name, cum_return = wealth[n] - 1, ann_return = wealth[n]^(12 / n) - 1, ann_vol = sd(r) * sqrt(12), sharpe = mean(exc) / sd(exc) * sqrt(12), max_drawdown = min(wealth / cummax(c(1, wealth))[-1] - 1), worst_month = min(r), worst_month_ym = hold_ym[idx][which.min(r)], mean_monthly = mean(r), alpha_monthly = co[1, 1], alpha_t = co[1, 3], beta_mkt = co[2, 1], t_mkt = co[2, 3], beta_smb = co[3, 1], t_smb = co[3, 3], beta_hml = co[4, 1], t_hml = co[4, 3], avg_turnover = turnover, stringsAsFactors = FALSE, row.names = NULL) } perf_table <- function(R, TO, idx = seq_len(nrow(R))) { do.call(rbind, lapply(colnames(R), function(p) { to <- if (!is.null(TO) && p %in% colnames(TO)) mean(TO[idx, p], na.rm = TRUE) else NA_real_ perf_one(R[, p], p, to, idx) })) }

hdr(“R5. Performance”) performance <- perf_table(ALL, base$turnover) check(nrow(performance) == 16, “performance table has 16 rows”) rounded <- function(d) { k <- vapply(d, is.double, logical(1)); d[k] <- lapply(d[k], round, 4); d } old_width <- options(width = 200) show_obj(rounded(performance))

holdings <- h[order(h\(form_ym, h\)quintile, h$z), c(“form_ym”, “ticker”, “hold_ym”, “quintile”, “n_obs”, “resid”, “sigma”, “z”, “raw_ret”, “mktcap”, “hold_ret”, “w_ew_form”, “w_vw_form”, “w_ew”, “w_vw”)] check(nrow(holdings) <= 6000 && !any(duplicated(holdings[, c(“form_ym”, “ticker”)])), sprintf(“holdings: %d rows (max 6000), unique on form_ym and ticker”, nrow(holdings))) write.csv(holdings, file.path(OUT_DIR, “holdings.csv”), row.names = FALSE) write.csv(portfolio_returns, file.path(OUT_DIR, “portfolio_returns.csv”), row.names = FALSE) write.csv(performance, file.path(OUT_DIR, “performance.csv”), row.names = FALSE)

—————————————————————————

R6. Charts and comparison table

—————————————————————————

hdr(“R6. Charts and comparison”) dates <- as.Date(sprintf(“%d-%02d-01”, bench_ym %/% 100, bench_ym %% 100)) tag <- if (DEMO) ” [SIMULATED DEMO DATA]” else “”

growth_chart <- function(series, labels, col, lty, title, file) { W <- rbind(100, apply(1 + ALL[, series], 2, cumprod) * 100) png(file.path(OUT_DIR, file), width = 2000, height = 1200, res = 200) par(mar = c(3.5, 4.5, 3, 1)) matplot(as.numeric(dates), W, type = “l”, col = col, lty = lty, lwd = 2, xaxt = “n”, xlab = ““, ylab =”Value of NT$100”, main = paste0(title, tag)) at <- dates[format(dates, “%m”) == “12”] axis(1, at = as.numeric(at), labels = format(at, “%Y-%m”)) abline(h = 100, col = “grey60”, lty = 3) legend(“topleft”, legend = labels, col = col, lty = lty, lwd = 2, bty = “n”, cex = 0.85) dev.off() } growth_chart(c(paste0(“Q”, 1:5, “_EW”), “0050”, “TAIEX_TR”), c(paste0(“Q”, 1:5, ” (EW)“),”0050”, “TAIEX_TR”), c(“#08519c”, “#6baed6”, “#999999”, “#fd8d3c”, “#a63603”, “black”, “#31a354”), c(1, 1, 1, 1, 1, 2, 4), “Growth of NT$100: residual-reversal quintiles”, “chart1_quintiles.png”) growth_chart(c(“LS_EW”, “LS_VW”, “0050”, “TAIEX_TR”), c(“LS (EW)”, “LS (VW)”, “0050”, “TAIEX_TR”), c(“#08519c”, “#a63603”, “black”, “#31a354”), c(1, 1, 2, 4), “Growth of NT$100: long-short vs benchmarks”, “chart2_longshort.png”)

q_means <- rbind(EW = colMeans(ALL[, paste0(“Q”, 1:5, “_EW”)]), VW = colMeans(ALL[, paste0(“Q”, 1:5, “_VW”)])) * 100 colnames(q_means) <- paste0(“Q”, 1:5) png(file.path(OUT_DIR, “chart3_quintile_bars.png”), width = 1800, height = 1100, res = 200) par(mar = c(3.5, 4.5, 3, 1)) barplot(q_means, beside = TRUE, col = c(“#08519c”, “#fd8d3c”), ylim = range(0, q_means) * 1.25, ylab = “Average monthly return (%)”, main = paste0(“Average monthly return by quintile”, tag)) abline(h = 0) legend(“topright”, c(“Equal-weighted”, “Value-weighted”), fill = c(“#08519c”, “#fd8d3c”), bty = “n”) dev.off()

mono <- function(x) if (all(diff(x) < 0)) “monotonically decreasing” else if (all(diff(x) > 0)) “monotonically increasing” else “not monotonic” say(“Average monthly return by quintile (%):”); show_obj(round(q_means, 3)) say(“EW pattern:”, mono(q_means[“EW”, ]), ” | VW pattern: “, mono(q_means[“VW”, ]))

pct <- function(x) ifelse(is.na(x), “-”, sprintf(“%.2f%%”, 100 * x)) sel <- performance[match(c(“LS_EW”, “LS_VW”, “Q1_EW”, “0050”, “TAIEX_TR”), performance\(portfolio), ] comparison <- data.frame( portfolio = c("LS (EW)", "LS (VW)", "Q1 (EW)", "0050", "TAIEX_TR"), ann_return = pct(sel\)ann_return), volatility = pct(sel\(ann_vol), sharpe = sprintf("%.2f", sel\)sharpe), max_drawdown = pct(sel\(max_drawdown), ff3_alpha_t = sprintf("%s (%.2f)", pct(sel\)alpha_monthly), sel\(alpha_t), turnover = pct(sel\)avg_turnover)) show_obj(comparison) write.csv(comparison, file.path(OUT_DIR, “comparison_table.csv”), row.names = FALSE)

—————————————————————————

R7. Discussion, written from the results above

—————————————————————————

g <- function(p) performance[performance\(portfolio == p, ] ls <- g("LS_EW"); lsv <- g("LS_VW"); q1 <- g("Q1_EW"); e50 <- g("0050"); tr <- g("TAIEX_TR") p1 <- function(x) sprintf("%.2f%%", 100 * x) strength <- function(a, t) { if (a > 0 && t >= 1.96) "statistically significant evidence of reversal at the 5% level" else if (a > 0 && t >= 1.645) "only weak evidence of reversal (10% level)" else if (a > 0) "a positive but statistically insignificant alpha, so reversal is not established" else if (t <= -1.96) "a significantly negative alpha, which points to continuation rather than reversal" else "no evidence of reversal, since the alpha is not positive" } loadings <- function(d) sprintf("market %.2f (t=%.2f), SMB %.2f (t=%.2f), HML %.2f (t=%.2f)", d\)beta_mkt, d\(t_mkt, d\)beta_smb, d\(t_smb, d\)beta_hml, d\(t_hml) sig_names <- c("market", "size", "value")[abs(c(ls\)t_mkt, ls\(t_smb, ls\)t_hml)) >= 1.96] load_text <- if (!length(sig_names)) { “None of the LS loadings is significant, consistent with a return driven mainly by stock-specific effects.” } else { sprintf(“LS still has significant %s exposure: removing factor movements from the sorting variable does not make the holdings factor-neutral.”, paste(sig_names, collapse = ” and “)) } mkt_text <- if (abs(ls\(beta_mkt) < abs(q1\)beta_mkt) / 2)”Going short Q5 removes most of the market exposure that Q1 carries.” else “A large part of market exposure remains even after shorting Q5.” hl <- function(a, b) if (a > b) “higher” else “lower” drag <- mean(base\(turnover[, "Q1_EW"] + base\)turnover[, “Q5_EW”], na.rm = TRUE) * ROUND_TRIP_COST

discussion <- c( if (DEMO) “*** SIMULATED DEMO DATA - NOT REAL RESULTS ***” else NULL, “R7. Discussion”, ““, sprintf(”Reversal. Average monthly returns of the equal-weighted quintiles from Q1 to Q5 are %s; the pattern is %s. The Q1 minus Q5 spread averages %s per month. The FF3 alpha of LS (EW) is %s per month (t = %.2f): %s. For LS (VW) the alpha is %s (t = %.2f): %s.”, paste(sprintf(“%.2f%%”, q_means[“EW”, ]), collapse = “,”), mono(q_means[“EW”, ]), p1(ls\(mean_monthly), p1(ls\)alpha_monthly), ls\(alpha_t, strength(ls\)alpha_monthly, ls\(alpha_t), p1(lsv\)alpha_monthly), lsv\(alpha_t, strength(lsv\)alpha_monthly, lsv\(alpha_t)), "", sprintf("Loadings. LS (EW): %s. Q1 (EW): %s. 0050: %s. %s %s", loadings(ls), loadings(q1), loadings(e50), mkt_text, load_text), "", sprintf("Benchmarks. Q1 (EW) earned %s a year (volatility %s, Sharpe %.2f, maximum drawdown %s), against %s (%.2f, %s) for 0050 and %s (%.2f, %s) for TAIEX_TR. Its return is %s than 0050 and %s than TAIEX_TR. LS (EW) earned %s a year with Sharpe %.2f and drawdown %s. This is not like-for-like: LS is a zero-investment, largely hedged spread that needs short selling and margin, while the benchmarks are fully invested long positions that collect the market premium.", p1(q1\)ann_return), p1(q1\(ann_vol), q1\)sharpe, p1(q1\(max_drawdown), p1(e50\)ann_return), e50\(sharpe, p1(e50\)max_drawdown), p1(tr\(ann_return), tr\)sharpe, p1(tr\(max_drawdown), hl(q1\)ann_return, e50\(ann_return), hl(q1\)ann_return, tr\(ann_return), p1(ls\)ann_return), ls\(sharpe, p1(ls\)max_drawdown)), ““, sprintf(”Limitations. First, LS (EW) turns over %s of each leg monthly; at an assumed %s round-trip cost (commissions plus the 0.3%% sales tax) the two legs lose about %s per month before price impact. Second, short selling in Taiwan is restricted by borrowing supply, margin requirements, recalls and price rules, and the 10%% daily price limit can block trades. Third, 60 months is a short sample, and residuals from 36-month regressions are noisy estimates.”, p1(ls$avg_turnover), p1(ROUND_TRIP_COST), p1(drag))) writeLines(enc2utf8(discussion), file.path(OUT_DIR, “discussion.txt”), useBytes = TRUE) hdr(“R7. Discussion”) say(paste(discussion, collapse = “”)) say(“”, sprintf(“Discussion length: about %d words”, length(unlist(strsplit(paste(discussion, collapse = ” “),”[[:space:]]+“)))))

—————————————————————————

Optional tasks D1 to D4

—————————————————————————

optional <- function(label, code) { hdr(label) tryCatch(code, error = function(e) say(“Skipped (”, conditionMessage(e), “)”)) } brief <- function(d) rounded(d[, c(“portfolio”, “ann_return”, “sharpe”, “alpha_monthly”, “alpha_t”, “beta_mkt”, “beta_smb”, “beta_hml”, “avg_turnover”)]) save_opt <- function(d, f) write.csv(d, file.path(OUT_DIR, f), row.names = FALSE)

if (RUN_OPTIONAL) { optional(“D1. Raw reversal vs residual reversal”, { raw <- build_portfolios(signals, “raw_ret”) d1 <- rbind(cbind(signal = “residual”, perf_table(base\(returns, base\)turnover)), cbind(signal = “raw”, perf_table(raw\(returns, raw\)turnover))) save_opt(d1, “D1_raw_vs_residual.csv”) x <- d1[d1\(portfolio %in% c("LS_EW", "LS_VW"), ] show_obj(cbind(signal = x\)signal, brief(x))) for (p in c(“LS_EW”, “LS_VW”)) { y <- x[x\(portfolio == p, ] tot <- rowSums(abs(y[, c("beta_mkt", "beta_smb", "beta_hml")])) say(sprintf("%s: higher Sharpe = %s signal; lower sum of |loadings| = %s signal", p, y\)signal[which.max(y\(sharpe)], y\)signal[which.min(tot)])) } })

optional(“D2. Larger universes”, { d2 <- NULL for (u in list(list(“top300”, 300, FALSE), list(“all_liquid”, Inf, TRUE))) { s <- build_signals(N = u[[2]], liquid = u[[3]]) b <- build_portfolios(s, “z”) say(sprintf(“%s: average valid stocks per month = %.0f”, u[[1]], sum(s\(status == "ok") / 60)) d2 <- rbind(d2, cbind(universe = u[[1]], perf_table(b\)returns, b\(turnover))) } d2 <- rbind(cbind(universe = "top100", perf_table(base\)returns, base\(turnover)), d2) save_opt(d2, "D2_universe_size.csv") x <- d2[d2\)portfolio %in% c(“LS_EW”, “LS_VW”), ] show_obj(cbind(universe = x$universe, brief(x))) say(“Liquidity filter: a return in each of the last 12 months and market cap above the monthly 20th percentile.”) })

optional(“D3. Trading costs”, { TO <- base\(turnover for (w in c("EW", "VW")) # LS pays on both legs TO[, paste0("LS_", w)] <- TO[, paste0("Q1_", w)] + TO[, paste0("Q5_", w)] first <- ifelse(grepl("^LS", colnames(TO)), 1, 0.5) # initial purchase TO[1, ] <- first net <- base\)returns - ROUND_TRIP_COST * TO d3 <- perf_table(net, base\(turnover) save_opt(d3, "D3_net_of_costs.csv") say(sprintf("Assumed round-trip cost: %.4f%%", 100 * ROUND_TRIP_COST)) show_obj(brief(d3)) for (p in c("LS_EW", "LS_VW")) { a0 <- perf_one(base\)returns[, p], p)\(alpha_monthly slope <- a0 - perf_one(base\)returns[, p] - TO[, p], p)$alpha_monthly if (a0 <= 0) say(p, “: alpha is already zero or negative before costs”) else say(sprintf(“%s: alpha disappears at a round-trip cost of %.3f%%”, p, 100 * a0 / slope)) } })

optional(“D4. Robustness”, { d4 <- NULL for (v in list(list(“window24”, 24, 20), list(“window60”, 60, 30))) { b <- build_portfolios(build_signals(window = v[[2]], minobs = v[[3]]), “z”) d4 <- rbind(d4, cbind(variant = v[[1]], perf_table(b\(returns, b\)turnover))) } d4 <- rbind(d4, cbind(variant = “2021_2022”, perf_table(base\(returns, base\)turnover, which(hold_ym < 202301))), cbind(variant = “2023_2025”, perf_table(base\(returns, base\)turnover, which(hold_ym >= 202301)))) save_opt(d4, “D4_robustness.csv”) x <- d4[d4\(portfolio %in% c("LS_EW", "LS_VW"), ] show_obj(cbind(variant = x\)variant, brief(x))) say(“Note: data start in 2017-12, so early ‘60-month’ windows contain fewer than 60 months.”) say(“Newey-West (3 lags) t-statistics of alpha:”) for (p in c(“LS_EW”, “LS_VW”)) { fit <- lm(y ~ mkt + smb + hml, data = cbind(y = base$returns[, p], hf)) say(sprintf(” %s: %.2f”, p, nw_t(fit)[1])) } say(“Skipping the last week of the formation month needs daily data and is not included.”) }) } options(old_width) say(“”, paste(“FINISHED. All required checks passed. Results are in:”, normalizePath(OUT_DIR))) if (DEMO) say(“*** These were SIMULATED results. Set DEMO <- FALSE and use your TEJ files. ***“)