---
title: "15 Fama-French Three-Factor Model (1992)"
format:
  html:
    self-contained: TRUE
---

```{r, include = F, eval = F}
# Download CRSP data from WRDS

library(tidyverse)
library(DBI)
library(RPostgres)

con <- dbConnect(
  RPostgres::Postgres(),
  host = "wrds-pgdata.wharton.upenn.edu",
  port = 9737,
  dbname = "wrds",
  sslmode = "require",
  user = "______",
  password = "______"
)

stock_panel <- dbGetQuery(con, "
  SELECT 
    a.permno,
    a.date,
    a.ret,
    a.prc,
    a.shrout,
    b.ticker,
    b.comnam
  FROM crsp.msf AS a
  LEFT JOIN crsp.msenames AS b
    ON a.permno = b.permno
    AND a.date BETWEEN b.namedt AND b.nameendt
  WHERE a.date >= '2000-01-01'
    AND a.ret IS NOT NULL
    AND a.prc IS NOT NULL
    AND a.shrout IS NOT NULL
  ORDER BY a.permno, a.date
")

DBI::dbDisconnect(con)

write_csv(stock_panel, "stock_panel.csv")
```

```{r, message = F}
library(tidyverse)

stock_panel <- read_csv("stock_panel.csv")
```

We'll use Kenneth French's official `Mkt-RF`, `SMB`, and `HML`.

```{r, message = F}
library(frenchdata)

fama <- download_french_data('Fama/French 3 Factors')$subsets$data[[1]] %>%
  rename(mkt_rf = `Mkt-RF`) %>%
  mutate(
    date = ym(date),
    across(c(mkt_rf, SMB, HML, RF), ~ .x / 100)
    )

joined_data <- stock_panel %>%
  mutate(date = floor_date(date, unit = "month")) %>%
  left_join(fama, join_by(date))
```

Here we compare CAPM to the Fama-French 3 Factor model for Apple's stock (permno 14593):

```{r}
joined_data %>%
  filter(permno == 14593)

joined_data %>%
  filter(permno == 14593) %>%
  lm(ret - RF ~ mkt_rf, data = .) %>%
  broom::tidy()

joined_data %>%
  filter(permno == 14593) %>%
  lm(ret - RF ~ mkt_rf + SMB + HML, data = .) %>%
  broom::tidy()
```

## Part 3: Comparing CAPM vs Fama-French for these 12 Stocks

Your goal: use `map()` to estimate CAPM versus the Fama-French 3 Factor model for 12 stocks in the data set.

`map()` should return a tibble that looks like this:

| comnam    | permno | CAPM beta | FF beta | CAPM alpha | FF alpha | SMB loading | HML loading |
|-----------|--------|-----------|---------|------------|----------|-------------|-------------|
| Microsoft | 10107  |           |         |            |          |             |             |
| Amazon    | 84788  |           |         |            |          |             |             |
| Tesla     | 93436  |           |         |            |          |             |             |
| NVIDIA    | 86580  |           |         |            |          |             |             |
| Facebook  | 13407  |           |         |            |          |             |             |
| McDonalds | 43449  |           |         |            |          |             |             |
| Coca Cola | 11995  |           |         |            |          |             |             |
| Netflix   | 89393  |           |         |            |          |             |             |
| Nike      | 57665  |           |         |            |          |             |             |
| Walmart   | 55976  |           |         |            |          |             |             |
| Costco    | 87055  |           |         |            |          |             |             |
| Starbucks | 77702  |           |         |            |          |             |             |

Fill in the blanks to estimate CAPM and FF3 for each of these stocks.

```{r}
factor_loadings <- map(
  .x = c(10107, 84788, 93436, 86580, 13407, 43449, 11995, 
         89393, 57665, 55976, 87055, 77702),
  
  .f = function(p) {
    data <- joined_data %>%
      filter(_______________________)
    
    capm_results <- data %>%
      lm(_______________________, data = .) %>%
      broom::tidy()
    
    ff_results <- data %>%
      lm(_______________________, data = .) %>%
      broom::tidy()
    
    data %>%
      slice(1) %>% 
      select(permno, comnam) %>%
      mutate(
        capm_beta = capm_results %>% filter(term == "mkt_rf") %>% pull(estimate),
        ff_beta = ______________________________________________,
        capm_alpha = ______________________________________________,
        ff_alpha = ______________________________________________,
        smb_loading = ______________________________________________,
        hml_loading = ______________________________________________
        )
  }
) %>%
  bind_rows()

# Interpretation questions: answer these questions in R after you've
# run the map() analysis.

# Which 3 stocks have the highest exposure to market-level risk according to CAPM?
factor_loadings %>% arrange(___________) %>% slice(1:3)

# What about according to Fama-French?
factor_loadings %>% arrange(___________) %>% slice(1:3)

# Which 3 stocks have the highest SMB loading (which behaves most like a small company)?
factor_loadings %>% arrange(___________) %>% slice(1:3)

# Which 3 stocks have the lowest SMB loading (which behaves most like a large company)?
factor_loadings %>% arrange(___________) %>% slice(1:3)

# Which 3 stocks have the highest HML loading (which behaves most like a value company)?
factor_loadings %>% arrange(___________) %>% slice(1:3)

# Which 3 stocks have the lowest HML loading (which behaves most like a growth company)?
factor_loadings %>% arrange(___________) %>% slice(1:3)

# Which 5 stocks have the largest CAPM alpha? Did controlling for SMB and HML help bring alpha down for these stocks?
factor_loadings %>% arrange(___________) %>% slice(1:5)
```
