<commit_before>---
layout: post
title:  "What Do Markets Think of President Cheeto?"
date:   2017-02-22
author: <NAME>
---

Trump largely remains a wildcard for the financial markets. As a first cut at understanding his expected impact on the economy, the last chapter of my dissertation looked at how various industries responded to his election, as seen through the stock market. The code below is general enough that it can be modified to conduct any event study based on cumulative abnormal returns. 

We'll need the following libraries:

{% highlight python %}

import os, re, csv
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import datetime as dt
from sklearn import linear_model
from scipy import stats
from tabulate import tabulate
from operator import mul
lm = linear_model.LinearRegression()

{% endhighlight %}

We're interested in how stock prices responded to some of the scandals during Trump's campaign, and to his surprise electoral victory. So let's use a function to make a dictionary of the events of interest and their dates below. 

{% highlight python %}

'''
Wikileaks releases Clinton e-mails	     				3/16/16
Trump entertains renegotiating national debt	           	5/5/16
E-mails show DNC was rigged against Sanders			7/22/16
Trump rags on Khan family	                 			7/30/16
Hillary catches pneumonia	                      			9/11/16
Trump attacks Alicia Machado	                				9/30/16
NYT leaks Trump's tax returns	          				10/1/16
Lewd Trump audio tape surfaces	                     		10/7/16
James Comey re-opens Clinton e-mail investigation		10/28/16
Donald Trump is declared POTUS					11/9/16
'''

def DefineEvents():
    '''
    Returns dictionary of event_name:event_date
    '''
    events = dict()
    events["<NAME>ails"] = dt.datetime(2016,3,16) # Wikileaks 
    events["Trump Debt"] = dt.datetime(2016,5,5) # National Debt
    events["Hillary DNC"] = dt.datetime(2016,7,22) # DNC Leak
    events["<NAME>ans"] = dt.datetime(2016,7,30) # Attack on Khan fam.
    events["Hillary Pneumonia"] = dt.datetime(2016,9,11) # Hillary pneumonia
    events["Trump Taxes"] = dt.datetime(2016,9,30) # tax returns + beauty queen
    events["Trump Tape"] = dt.datetime(2016,9,30) # Trump lewd remarks 
    events["Election"] = dt.datetime(2016,11,8) # election
    events["Comey Emails"] = dt.datetime(2016,10,28) # Comey letter
    return events; 

{% endhighlight %}

Load in our time series of stock prices, one column for each security, available [here](/assets/stockSample_11Oct2.csv) in .csv format. Notice that headings are Bloomberg tickers. 
Our full sample of securities and related information is in [securityList.csv](/assets/securityList.csv). This file provides the name of the firm, its Bloomberg ticker, the exchange on which it trades (NYSE or NASDAQ), and the industry to which the firm belongs. All of the included industries should have had good reasons to react strongly to the result of the 2016 election (you can see Ch. 3 of my [PhD thesis](/assets/Weinreb_thesis.pdf) for more on this). 

We can also write a function to plot each stock over time, using the iShares Mexico ETF (EWW) as an example - its price was pretty volatile during election season given Trump's comments about the wall, etc. etc. 

{% highlight python %}
df = pd.read_csv('stockSample_11Oct2.csv', index_col = 0, parse_dates = True)
df.dropna(axis = 0, how = 'all', inplace = True)

def PlotStock(ticker): 
    '''
    Input: ticker e.g. 'HUM US Equity'
    Returns: plot of time series with vertical line for each date in events dict
    '''
    ax = df[[ticker]].plot()
    ymin, ymax = ax.get_ylim()
    ax.vlines(x=list(DefineEvents().values()), ymin = ymin, ymax = ymax, color='r')
    ax.set_ylim([ymin, ymax])
    ax.legend_.remove()
    plt.title(ticker)

PlotStock("EWW US Equity") 

{% endhighlight %}

{% maincolumn 'assets/img/eww.png' "The iShares Mexico ETF during election season"%}

Now to the event study... 

We can model the returns of a specific stock during some \emph{estimation window} of length $$L_1$$ days before our event of interest (say, election day). By convention, call the first day of the estimation window $$\tau_0$$ and the last day $$\tau_1$$. We use the ``Market" model, where the returns of a stock $${\bf R}$$ are a linear function of the average market return $${\bf m}$$ plus noise, estimated as follows:
$$ R_t = \beta_0 + \beta_1 m_t+ \epsilon_t $$ 
$$ \mathbb{E}[\epsilon_t] = 0 $$
$$ \mathbb{V}[\epsilon_t] = \sigma^2 $$

where $$(\beta_0, \beta_1)$$ is a vector of coefficients to be estimated. 

We could have used time series models like GARCH or ARIMA processes, but these don't actually fit the data any better than the OLS model above. Standard errors for these more complex time series models will be smaller than ours in any case, so the claims we make about statistical significance will be conservative.  

Using our model of what stock returns should be in normal times, let's compute the *abnormal returns* during the estimation window by subtracting the returns predicted by our model, $$\mathbb{E}[R_t] = \hat{\beta_0} + \hat{\beta_1}m_t$$, from the observed returns $$R_t$$; thus, at time $$t$$, the abnormal return is simply $$\hat{\epsilon_t} = R_t -  \hat{\beta_0} - \hat{\beta_1}m_t$$. The resulting series of $$L_1$$ abnormal returns will have mean $$0$$ by construction and some estimated variance, denoted $$\hat{\sigma_\epsilon}^2$$. 

Next, consider the behavior of stock returns during an *event window* of $$L_2$$ consecutive days, beginning with the day of our event of interest $$\tau_1 + 1$$ through day $$\tau_2$$. For example, this might be the first three days where Trump was declared POTUS (November 9 through November 11th). We compute abnormal returns during this event window, subtracting realized returns from their expected values based our earlier market model. 

Finally, we aggregate abnormal returns during the event window into the *cumulative abnormal return* (CAR) given by
$$ \widehat{CAR} = \sum_{t = \tau_1 + 1}^{\tau_2} \hat{\epsilon_t}$$

Because we assumed abnormal returns are i.i.d. $$\mathcal{N}(0, \sigma^2)$$, then under the null hypothesis of no stock market reaction to election-related news, $$\widehat{CAR}$$ will be normally distributed with mean 0 and variance 

$$ \hat{\sigma}^2 = (\tau_2 - \tau_1 - 1)\sigma_{\epsilon}^2$$

Thus, we can construct a test statistic for the null hypothesis by standardizing the CAR by its variance -- what some people refer to as the standardized cumulative abnormal return:

$$ \widehat{SCAR} = \frac{\widehat{CAR}}{\hat{\sigma}\sqrt{\tau_2 - \tau_1 - 1}} $$

With a sufficiently large estimation window (i.e. when $$L_1 > 30$$), this statistic will be distributed approximately standard normal. In particular, for a two-tailed test, our p-value will be  $$2 (1 - \Phi(\widehat{\abs{SCAR}}))$$ where $$ \Phi(\cdot)$$ is the standard normal CDF. Note that the value of $$\widehat{SCAR}$$ depends on both the length of the estimation window, $$L_1$$, as well as the length of the event window, $$L_2$$.  

 

While the statistics above pertain to the abnormal returns of single stocks, we can also aggregate the abnormal returns of several companies into an industry-wide abnormal return, which is the dependent variable we care about. Given a series of CARs for $$n$$ individual stocks, we can compute the aggregate CAR as

$$ \overline{CAR}  =\frac{1}{n} \sum_{i = 1}^{n} \widehat{CAR}_i$$

Our individual stocks here might be Ford, Chrysler, and GM, where we're looking at the behavior of automakers. The variance of the industry-wide CAR for an event will require us to account for the within-industry covariance between abnormal returns for each company in the industry. The expected positive correlation between the abnormal returns of stocks In the same industry implies that the variance of an industry-specific CAR will be wider than that for uncorrelated assets. One easy way to go is to compute the variance-covariance matrix $${\bf \Sigma}$$ of the abnormal returns across stocks in a given industry during the estimation window, and use this matrix to compute the variance of our aggregate CAR:

$$ \mathbb{V}(\overline{CAR}) = \frac{1}{n^2} \left( \sum_{i = 1}^{n} \hat{\sigma}^2_{i}+ 2 \cdot \sum_{j > i \geq 1}^{n} \text{Cov}(\hat{\epsilon}_{i}, \hat{\epsilon}_{j}) \right)$$

where $$\text{Cov}(\hat{\epsilon}_i, \hat{\epsilon}_j)$$ is the $$ij$$-th element of $${\bf \Sigma}$$. Then, our industry-wide CAR is distributed approximately $$\mathcal{N}(\overline{CAR}, \mathbb{V}(\overline{CAR}))$$. 
    



<commit_msg>math again<commit_after>---
layout: post
title:  "What Do Markets Think of President Cheeto?"
date:   2017-02-22
author: <NAME>
---

Trump largely remains a wildcard for the financial markets. As a first cut at understanding his expected impact on the economy, the last chapter of my dissertation looked at how various industries responded to his election, as seen through the stock market. The code below is general enough that it can be modified to conduct any event study based on cumulative abnormal returns. 

We'll need the following libraries:

{% highlight python %}

import os, re, csv
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import datetime as dt
from sklearn import linear_model
from scipy import stats
from tabulate import tabulate
from operator import mul
lm = linear_model.LinearRegression()

{% endhighlight %}

We're interested in how stock prices responded to some of the scandals during Trump's campaign, and to his surprise electoral victory. So let's use a function to make a dictionary of the events of interest and their dates below. 

{% highlight python %}

'''
Wikileaks releases Clinton e-mails	     				3/16/16
Trump entertains renegotiating national debt	           	5/5/16
E-mails show DNC was rigged against Sanders			7/22/16
Trump rags on Khan family	                 			7/30/16
Hillary catches pneumonia	                      			9/11/16
Trump attacks Alicia Machado	                				9/30/16
NYT leaks Trump's tax returns	          				10/1/16
Lewd Trump audio tape surfaces	                     		10/7/16
James Comey re-opens Clinton e-mail investigation		10/28/16
Donald Trump is declared POTUS					11/9/16
'''

def DefineEvents():
    '''
    Returns dictionary of event_name:event_date
    '''
    events = dict()
    events["Hillary Emails"] = dt.datetime(2016,3,16) # Wikileaks 
    events["Trump Debt"] = dt.datetime(2016,5,5) # National Debt
    events["Hillary DNC"] = dt.datetime(2016,7,22) # DNC Leak
    events["Trump Khans"] = dt.datetime(2016,7,30) # Attack on Khan fam.
    events["Hillary Pneumonia"] = dt.datetime(2016,9,11) # Hillary pneumonia
    events["Trump Taxes"] = dt.datetime(2016,9,30) # tax returns + beauty queen
    events["Trump Tape"] = dt.datetime(2016,9,30) # Trump lewd remarks 
    events["Election"] = dt.datetime(2016,11,8) # election
    events["Comey Emails"] = dt.datetime(2016,10,28) # Comey letter
    return events; 

{% endhighlight %}

Load in our time series of stock prices, one column for each security, available [here](/assets/stockSample_11Oct2.csv) in .csv format. Notice that headings are Bloomberg tickers. 
Our full sample of securities and related information is in [securityList.csv](/assets/securityList.csv). This file provides the name of the firm, its Bloomberg ticker, the exchange on which it trades (NYSE or NASDAQ), and the industry to which the firm belongs. All of the included industries should have had good reasons to react strongly to the result of the 2016 election (you can see Ch. 3 of my [PhD thesis](/assets/Weinreb_thesis.pdf) for more on this). 

We can also write a function to plot each stock over time, using the iShares Mexico ETF (EWW) as an example - its price was pretty volatile during election season given Trump's comments about the wall, etc. etc. 

{% highlight python %}
df = pd.read_csv('stockSample_11Oct2.csv', index_col = 0, parse_dates = True)
df.dropna(axis = 0, how = 'all', inplace = True)

def PlotStock(ticker): 
    '''
    Input: ticker e.g. 'HUM US Equity'
    Returns: plot of time series with vertical line for each date in events dict
    '''
    ax = df[[ticker]].plot()
    ymin, ymax = ax.get_ylim()
    ax.vlines(x=list(DefineEvents().values()), ymin = ymin, ymax = ymax, color='r')
    ax.set_ylim([ymin, ymax])
    ax.legend_.remove()
    plt.title(ticker)

PlotStock("EWW US Equity") 

{% endhighlight %}

{% maincolumn 'assets/img/eww.png' "The iShares Mexico ETF during election season"%}

Now to the event study... 

We can model the returns of a specific stock during some \emph{estimation window} of length $$L_1$$ days before our event of interest (say, election day). By convention, call the first day of the estimation window $$\tau_0$$ and the last day $$\tau_1$$. We use the ``Market" model, where the returns of a stock $${\bf R}$$ are a linear function of the average market return $${\bf m}$$ plus noise, estimated as follows:

$$ R_t = \beta_0 + \beta_1 m_t+ \epsilon_t $$ 

$$ \mathbb{E}[\epsilon_t] = 0 $$

$$ \mathbb{V}[\epsilon_t] = \sigma^2 $$

where $$(\beta_0, \beta_1)$$ is a vector of coefficients to be estimated. 

We could have used time series models like GARCH or ARIMA processes, but these don't actually fit the data any better than the OLS model above. Standard errors for these more complex time series models will be smaller than ours in any case, so the claims we make about statistical significance will be conservative.  

Using our model of what stock returns should be in normal times, let's compute the *abnormal returns* during the estimation window by subtracting the returns predicted by our model, $$\mathbb{E}[R_t] = \hat{\beta_0} + \hat{\beta_1}m_t$$, from the observed returns $$R_t$$; thus, at time $$t$$, the abnormal return is simply $$\hat{\epsilon_t} = R_t -  \hat{\beta_0} - \hat{\beta_1}m_t$$. The resulting series of $$L_1$$ abnormal returns will have mean $$0$$ by construction and some estimated variance, denoted $$\hat{\sigma_\epsilon}^2$$. 

Next, consider the behavior of stock returns during an *event window* of $$L_2$$ consecutive days, beginning with the day of our event of interest $$\tau_1 + 1$$ through day $$\tau_2$$. For example, this might be the first three days where Trump was declared POTUS (November 9 through November 11th). We compute abnormal returns during this event window, subtracting realized returns from their expected values based our earlier market model. 

Finally, we aggregate abnormal returns during the event window into the *cumulative abnormal return* (CAR) given by
$$ \widehat{CAR} = \sum_{t = \tau_1 + 1}^{\tau_2} \hat{\epsilon_t}$$

Because we assumed abnormal returns are i.i.d. $$\mathcal{N}(0, \sigma^2)$$, then under the null hypothesis of no stock market reaction to election-related news, $$\widehat{CAR}$$ will be normally distributed with mean 0 and variance 

$$ \hat{\sigma}^2 = (\tau_2 - \tau_1 - 1)\sigma_{\epsilon}^2$$

Thus, we can construct a test statistic for the null hypothesis by standardizing the CAR by its variance -- what some people refer to as the standardized cumulative abnormal return:

$$ \widehat{SCAR} = \frac{\widehat{CAR}}{\hat{\sigma}\sqrt{\tau_2 - \tau_1 - 1}} $$

With a sufficiently large estimation window (i.e. when $$L_1 > 30$$), this statistic will be distributed approximately standard normal. In particular, for a two-tailed test, our p-value will be  $$2 (1 - \Phi(\widehat{|SCAR|}))$$ where $$ \Phi(\cdot)$$ is the standard normal CDF. Note that the value of $$\widehat{SCAR}$$ depends on both the length of the estimation window, $$L_1$$, as well as the length of the event window, $$L_2$$.  

 

While the statistics above pertain to the abnormal returns of single stocks, we can also aggregate the abnormal returns of several companies into an industry-wide abnormal return, which is the dependent variable we care about. Given a series of CARs for $$n$$ individual stocks, we can compute the aggregate CAR as

$$ \overline{CAR}  =\frac{1}{n} \sum_{i = 1}^{n} \widehat{CAR}_i$$

Our individual stocks here might be Ford, Chrysler, and GM, where we're looking at the behavior of automakers. The variance of the industry-wide CAR for an event will require us to account for the within-industry covariance between abnormal returns for each company in the industry. The expected positive correlation between the abnormal returns of stocks In the same industry implies that the variance of an industry-specific CAR will be wider than that for uncorrelated assets. One easy way to go is to compute the variance-covariance matrix $${\bf \Sigma}$$ of the abnormal returns across stocks in a given industry during the estimation window, and use this matrix to compute the variance of our aggregate CAR:

$$ \mathbb{V}(\overline{CAR}) = \frac{1}{n^2} \left( \sum_{i = 1}^{n} \hat{\sigma}^2_{i}+ 2 \cdot \sum_{j > i \geq 1}^{n} \text{Cov}(\hat{\epsilon}_{i}, \hat{\epsilon}_{j}) \right)$$

where $$\text{Cov}(\hat{\epsilon}_i, \hat{\epsilon}_j)$$ is the $$ij$$-th element of $${\bf \Sigma}$$. Then, our industry-wide CAR is distributed approximately $$\mathcal{N}(\overline{CAR}, \mathbb{V}(\overline{CAR}))$$. 
    




{'fraction_non_alphanumeric': 0.1027674849467346, 'fraction_numerical': 0.021537748957850857, 'mean_word_length': 3.96921749136939, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2729294', 'n_tokens_mistral': 5257, 'n_tokens_neox': 4742, 'n_words': 2247}