library(quantmod)    # download from Yahoo Finance
library(tidyverse)   # dplyr, tidyr, readr, ggplot2
library(lubridate)   # dates
library(moments)     # skewness, kurtosis

FROM <- as.Date("2018-10-01")   # enough for 250-day window before Mar 2020
TO   <- as.Date("2024-09-30")   # enough for +60 trading days after Dec 2023
dir.create("data_real", showWarnings = FALSE)

1. Firms, indices and events

firms <- tribble(
  ~ticker,       ~name,                          ~subsector,            ~region,  ~market_index,
  "MAERSK-B.CO", "A.P. Moller - Maersk",         "Container shipping",  "Europe", "^OMXC25",
  "HLAG.DE",     "Hapag-Lloyd",                  "Container shipping",  "Europe", "^GDAXI",
  "2603.TW",     "Evergreen Marine",             "Container shipping",  "Asia",   "^TWII",
  "2609.TW",     "Yang Ming Marine Transport",   "Container shipping",  "Asia",   "^TWII",
  "1919.HK",     "COSCO Shipping Holdings",      "Container shipping",  "Asia",   "^HSI",
  "DSV.CO",      "DSV",                          "Freight forwarding",  "Europe", "^OMXC25",
  "KNIN.SW",     "Kuehne+Nagel",                 "Freight forwarding",  "Europe", "^SSMI",
  "0144.HK",     "China Merchants Port",         "Port and terminals",  "Asia",   "^HSI"
)

events <- tribble(
  ~event_id, ~event_day_europe, ~event_day_asia,
  "COVID",   "2020-03-12",      "2020-03-12",
  "SUEZ",    "2021-03-24",      "2021-03-24",
  "REDSEA",  "2023-12-15",      "2023-12-18"
) %>% mutate(across(starts_with("event_day"), ymd))

firms
## # A tibble: 8 × 5
##   ticker      name                       subsector          region market_index
##   <chr>       <chr>                      <chr>              <chr>  <chr>       
## 1 MAERSK-B.CO A.P. Moller - Maersk       Container shipping Europe ^OMXC25     
## 2 HLAG.DE     Hapag-Lloyd                Container shipping Europe ^GDAXI      
## 3 2603.TW     Evergreen Marine           Container shipping Asia   ^TWII       
## 4 2609.TW     Yang Ming Marine Transport Container shipping Asia   ^TWII       
## 5 1919.HK     COSCO Shipping Holdings    Container shipping Asia   ^HSI        
## 6 DSV.CO      DSV                        Freight forwarding Europe ^OMXC25     
## 7 KNIN.SW     Kuehne+Nagel               Freight forwarding Europe ^SSMI       
## 8 0144.HK     China Merchants Port       Port and terminals Asia   ^HSI
events
## # A tibble: 3 × 3
##   event_id event_day_europe event_day_asia
##   <chr>    <date>           <date>        
## 1 COVID    2020-03-12       2020-03-12    
## 2 SUEZ     2021-03-24       2021-03-24    
## 3 REDSEA   2023-12-15       2023-12-18

2. Download real prices (Yahoo Finance)

get_one <- function(sym, adjusted = TRUE, tries = 3) {
  for (k in seq_len(tries)) {
    x <- tryCatch(getSymbols(sym, src = "yahoo", from = FROM, to = TO,
                             auto.assign = FALSE), error = function(e) NULL)
    if (!is.null(x)) {
      v <- if (adjusted) Ad(x) else Cl(x)
      return(tibble(date = as.Date(index(x)), value = as.numeric(v)))
    }
    Sys.sleep(3)
  }
  message("FAILED: ", sym)
  NULL
}

prices <- map_dfr(firms$ticker, function(tk) {
  message("Downloading ", tk); Sys.sleep(1)
  d <- get_one(tk, adjusted = TRUE)
  if (is.null(d)) NULL else mutate(d, ticker = tk, adj_close = value) %>% select(date, ticker, adj_close)
}) %>% drop_na()

indices <- map_dfr(unique(firms$market_index), function(ix) {
  message("Downloading ", ix); Sys.sleep(1)
  d <- get_one(ix, adjusted = FALSE)
  if (is.null(d)) NULL else mutate(d, index = ix, close = value) %>% select(date, index, close)
}) %>% drop_na()

write_csv(prices,  "data_real/prices_long.csv")
write_csv(indices, "data_real/index_long.csv")
write_csv(firms,   "data_real/firms.csv")

3. Quick checks (do not skip)

# Rows and date range per stock/index. Expect roughly 1,400-1,500 rows each.
prices  %>% group_by(ticker) %>% summarise(n = n(), start = min(date), end = max(date))
## # A tibble: 8 × 4
##   ticker          n start      end       
##   <chr>       <int> <date>     <date>    
## 1 0144.HK      1475 2018-10-02 2024-09-27
## 2 1919.HK      1475 2018-10-02 2024-09-27
## 3 2603.TW      1457 2018-10-01 2024-09-27
## 4 2609.TW      1457 2018-10-01 2024-09-27
## 5 DSV.CO       1500 2018-10-01 2024-09-27
## 6 HLAG.DE      1524 2018-10-01 2024-09-27
## 7 KNIN.SW      1509 2018-10-01 2024-09-27
## 8 MAERSK-B.CO  1500 2018-10-01 2024-09-27
indices %>% group_by(index)  %>% summarise(n = n(), start = min(date), end = max(date))
## # A tibble: 5 × 4
##   index       n start      end       
##   <chr>   <int> <date>     <date>    
## 1 ^GDAXI   1524 2018-10-01 2024-09-27
## 2 ^HSI     1475 2018-10-02 2024-09-27
## 3 ^OMXC25  1459 2018-10-01 2024-09-27
## 4 ^SSMI    1497 2018-10-01 2024-09-27
## 5 ^TWII    1457 2018-10-01 2024-09-27
# Tickers that failed to download
setdiff(firms$ticker, unique(prices$ticker))
## character(0)
setdiff(unique(firms$market_index), unique(indices$index))
## character(0)

4. Daily log returns and descriptive statistics

returns <- prices %>%
  arrange(ticker, date) %>%
  group_by(ticker) %>%
  mutate(ret = log(adj_close) - lag(log(adj_close))) %>%
  ungroup() %>% drop_na(ret)

desc <- returns %>%
  group_by(ticker) %>%
  summarise(n_days = n(),
            mean_pct = 100 * mean(ret),
            sd_pct   = 100 * sd(ret),
            min_pct  = 100 * min(ret),
            max_pct  = 100 * max(ret),
            skew     = skewness(ret),
            ex_kurt  = kurtosis(ret) - 3,
            ann_vol_pct = 100 * sd(ret) * sqrt(252)) %>%
  left_join(select(firms, ticker, subsector), by = "ticker")

desc %>% mutate(across(where(is.numeric), ~ round(., 3)))
## # A tibble: 8 × 10
##   ticker      n_days mean_pct sd_pct min_pct max_pct   skew ex_kurt ann_vol_pct
##   <chr>        <dbl>    <dbl>  <dbl>   <dbl>   <dbl>  <dbl>   <dbl>       <dbl>
## 1 0144.HK       1474    0.018   1.89   -11.3   20.8   1.03    15.2         30.0
## 2 1919.HK       1474    0.156   3.27   -15.7   25.6   0.213    4.76        51.9
## 3 2603.TW       1456    0.188   3.20   -17.8    9.53 -0.223    2.69        50.9
## 4 2609.TW       1456    0.187   3.30   -10.5   14.4   0.171    2.41        52.5
## 5 DSV.CO        1499    0.059   1.94   -15.9    9.57 -0.38     5.25        30.9
## 6 HLAG.DE       1523    0.135   3.67   -19.9   24.7   0.026    4.61        58.2
## 7 KNIN.SW       1508    0.041   1.69   -14.6    9.46 -0.658    5.99        26.9
## 8 MAERSK-B.CO   1499    0.059   2.53   -18.6   11.7  -0.514    4.01        40.2
## # ℹ 1 more variable: subsector <chr>

5. Price chart (rebased to 100)

prices %>%
  group_by(ticker) %>% mutate(rebased = 100 * adj_close / first(adj_close)) %>%
  left_join(select(firms, ticker, subsector), by = "ticker") %>%
  ggplot(aes(date, rebased, colour = ticker)) +
  geom_line(linewidth = 0.4) +
  geom_vline(data = events, aes(xintercept = event_day_europe), linetype = 2) +
  scale_y_log10() +
  labs(title = "Adjusted prices (first day = 100, log scale); dashed lines = event days",
       x = NULL, y = "Rebased price") +
  theme_minimal()

6. Next step

Fill in firm_chars.csv from annual reports (slack, geo_exposure, integrated, log_mktcap, leverage). Then copy the three CSV files from data_real/ into data/real/ of the project folder and run Rscript R/02_event_study.R data/real to get the abnormal returns, CARs and tests.