<jupyter_start><jupyter_text>1Short Answer (25pts)(5pts) True or False. (And explain your reason.)Mean-variance optimization goes long the highest Sharpe-Ratio assets and shorts the lowest Sharpe-ratio assets.(5pts) True or False. (And explain your reason.)Investing in an LETF makes more sense for a long-term horizon than a short-term horizon.(5pts) This week ProShares launches BITO on the NYSE. The ETF holds Bitcoin futures con- tracts. Suppose in a year from now, we want to try to replicate BITO using SPY and IEF as regressors in a LFD. Because BITO will only have a year of data, we do not trust that we will have a good estimate of the mean return.Do you suggest that we (in a year) estimate the regression with an intercept or without an intercept? Why?(5pts) Is HDG effective at tracking HFRI in-sample? And out of sample?(5pts) A hedge fund claims to beat the market by having a very high alpha. After regressing the hedge fund returns on the 6 Merrill-Lynch style factors, you find the alpha to be negative. Explain why this discrepancy can happen. 1. FalseMean-variance optimization long the tangent portfolio, short or long the risk-free asset. It does not focus on individual assets 2. In a long-term horizon, because the LETF will have a low transaction cost, with the compounding effect, it wil generate higher return in the long-run. 3. If we want to replicate the in-sample mean, do not include an intercept. If we want to best replicate the variation, maximize correlation, and ignore the in sample mean, then include an intercept. 4. Yes, in both in-sample and OOS, the factors HDG chooses was able to track the HFRI with a high R-square(around 0.85) and low tracking error(around 0.001) 5. Maybe the hedge fund chose another benchmark, other than the 6 Merrill-Lynch style factors. Therefore, the 6 Merrill-Lynch style factors did not replicate the hedge fund as good as the other factors.<jupyter_code>import pandas as pd
import numpy as np

import seaborn as sns

import statsmodels.api as sm
import statsmodels.formula.api as smf

import matplotlib.pyplot as plt
from scipy import stats


xlsx = pd.ExcelFile('proshares_analysis_data.xlsx')
df = pd.read_excel(xlsx, 'merrill_factors').set_index('date')


df['e_SPY US Equity'] = df['SPY US Equity']-df['USGG3M Index']
df['e_EEM US Equity'] = df['EEM US Equity']-df['USGG3M Index']
df['e_EFA US Equity'] = df['EFA US Equity']-df['USGG3M Index']
df['e_EUO US Equity'] = df['EUO US Equity']-df['USGG3M Index']
df['e_IWM US Equity'] = df['IWM US Equity']-df['USGG3M Index']

df1 = df.iloc[:,6:11]
df1.head(5)<jupyter_output><empty_output><jupyter_text>2.1<jupyter_code>def compute_tangency(excess_ret, diagonalize_Sigma=False):
    
    """  
    Parameters:
    - annualized excess returns data: DataFrame,
    - diagonalize_Sigma: bool
    
    Returns:
    - tangency portfolio weights
    - the associated vector of average returns and the covariance matrix.

    """

    Sigma = excess_ret.cov()
    mu_tilde = excess_ret.mean()
    N = Sigma.shape[0]  # number of assets

    if diagonalize_Sigma:
        Sigma.loc[:,:] = np.diag(np.diag(Sigma))
    Sigma_inv = np.linalg.inv(Sigma)
    
    weights = Sigma_inv @ mu_tilde / (np.ones(N) @ Sigma_inv @ mu_tilde)
    tangency_weights = pd.Series(weights, index=mu_tilde.index)
    
    return tangency_weights, mu_tilde, Sigma


annualized_excess_ret = df1 * 12
tangency_weights, mu_tilde, Sigma = compute_tangency(annualized_excess_ret)
tangency_weights<jupyter_output><empty_output><jupyter_text>2.2<jupyter_code>def target_mv_portfolio(excess_ret, target_return, diagonalize_Sigma=False):

    """
    Parameters:
    - annualized excess returns data: DataFrame,
    - annualized target return: numeric
    - diagonalize_Sigma: bool

    Returns: 
    - MV optimal portfolio weights
    
    """
    
    # Solve for tangency portfolio
    tangency_weights, mu_tilde, Sigma = compute_tangency(excess_ret, diagonalize_Sigma=diagonalize_Sigma)
    
    N = Sigma.shape[0]
    if diagonalize_Sigma:
        Sigma.loc[:,:] = np.diag(np.diag(Sigma))   
    Sigma_inv = np.linalg.inv(Sigma)
    
    delta_tilde = ((np.ones(N) @ Sigma_inv @ mu_tilde) / (mu_tilde @ Sigma_inv @ mu_tilde)) * target_return
    mv_weights = delta_tilde * tangency_weights
    
    return mv_weights


mv_weights = target_mv_portfolio(annualized_excess_ret, target_return=0.02 * 12)
mv_weights


sum(mv_weights)<jupyter_output><empty_output><jupyter_text>The sum of optimal weights are larger than 1. Therefore, the optimal portfolio short in risk-free rate. 2.3<jupyter_code># Mean
port_mean = mu_tilde @ mv_weights

# Volatlity
port_vol = np.sqrt(mv_weights @ Sigma @ mv_weights) / np.sqrt(12)

# Sharpe ratio
port_sharpe_ratio = port_mean / port_vol

summary_mv = pd.DataFrame({'Mean':port_mean, 'Vol':port_vol, 'Sharpe':port_sharpe_ratio}, index=['MV'])
print("Mean: ", port_mean)
print("Volatility: ", port_vol)
print("Sharpe_ratio: ", port_sharpe_ratio)<jupyter_output>Mean:  0.24000000000000005
Volatility:  0.15855753914025056
Sharpe_ratio:  1.513646095299892<jupyter_text>2.4<jupyter_code>subset = df1.loc['2011':'2018']


annualized_excess_ret = subset * 12
tangency_weights, mu_tilde, Sigma = compute_tangency(annualized_excess_ret)
tangency_weights

subset2  = df1.loc['2019':'2021']
mu_tilde = subset2.mean()
Sigma = subset2.cov()

# Mean
port_mean = mu_tilde @ tangency_weights

# Volatlity
port_vol = np.sqrt(tangency_weights @ Sigma @ tangency_weights) / np.sqrt(12)

# Sharpe ratio
port_sharpe_ratio = port_mean / port_vol

print("Mean: ", port_mean)
print("Volatility: ", port_vol)
print("Sharpe_ratio: ", port_sharpe_ratio)<jupyter_output>Mean:  0.023491424452651257
Volatility:  0.01588351967750394
Sharpe_ratio:  1.4789810400727808<jupyter_text>2.5 It would be better than the five risky assets, because these five (gold...) conmodity futures are less correlated to each other than the five risky assets. 3.1<jupyter_code>y = df1['e_EEM US Equity']
x = df1['e_SPY US Equity']
model = sm.OLS(y, X).fit()
print(model.summary())<jupyter_output>OLS Regression Results                                
=======================================================================================
Dep. Variable:        e_EEM US Equity   R-squared (uncentered):                   1.000
Model:                            OLS   Adj. R-squared (uncentered):              1.000
Method:                 Least Squares   F-statistic:                          5.084e+05
Date:                Mon, 18 Oct 2021   Prob (F-statistic):                   4.32e-221
Time:                        19:28:51   Log-Likelihood:                          694.64
No. Observations:                 122   AIC:                                     -1387.
Df Residuals:                     121   BIC:                                     -1384.
Df Model:                           1                                                  
Covariance Type:            nonrobust                                                  
================================[...]<jupyter_text>the optimal hedge ratio over the full sample of data is 0.9996<jupyter_code>df['hedge'] = 0.9996*df['EEM US Equity']<jupyter_output><empty_output><jupyter_text>3.2<jupyter_code>mean = df['hedge'].mean()*12
vol = df['hedge'].std() * np.sqrt(12)
sharp_r = mean / vol
print(mean)
print(vol)
print(sharp_r)<jupyter_output>0.0434776632490982
0.1832504397914188
0.23725816592083376<jupyter_text>3.3<jupyter_code>EEM_mean = df['EEM US Equity'].mean()*12
EEM_mean<jupyter_output><empty_output><jupyter_text>ALmost the same, because the hedged position perfectly hedged all the risk with an R-square of 1. 3.4 Because the SPY already perfectly hedged EEM. The addition of IWM will not help improve the performance. 4.1<jupyter_code>X = sm.add_constant(df['EFA US Equity'])
y = df['SPY US Equity']
model = sm.OLS(y, X).fit()
print(model.summary())<jupyter_output>OLS Regression Results                            
==============================================================================
Dep. Variable:          SPY US Equity   R-squared:                       0.743
Model:                            OLS   Adj. R-squared:                  0.740
Method:                 Least Squares   F-statistic:                     346.2
Date:                Mon, 18 Oct 2021   Prob (F-statistic):           3.64e-37
Time:                        19:35:48   Log-Likelihood:                 305.73
No. Observations:                 122   AIC:                            -607.5
Df Residuals:                     120   BIC:                            -601.9
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
=================================================================================
                    coef    std err          t   [...]
{'fraction_non_alphanumeric': 0.11876618259596983, 'fraction_numerical': 0.041652594844084206, 'mean_word_length': 2.925762262483429, 'pattern_counts': {'":': 0, '<': 36, '<?xml version=': 0, '>': 36, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 1, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '579733', 'license': 'MIT', 'n_tokens_mistral': 3076, 'n_tokens_neox': 2731, 'n_words': 803, 'path': 'solutions/mid1/submissions/chenxuan_167931_6241689_2021_midterm_XuanChen.ipynb', 'repo_name': 'tulyu96/finm-portfolio-2021', 'size': '8883'}