<jupyter_start><jupyter_text>FINM36700 Mid-term 1 <NAME>  Section 1. 1. False. The mean-variance portoflio will allocate weights according to the covariance, not the individual asset's mean and variance. Therefore, it is not neccessarily than mean-variance portoflio will long the highest Sharpe Ratio asset and short the lowest Sharpe Ratio asset.  2. False. Leveraged ETF will track the underlying index more accurately for a given day, but the tracking could diverge over time. This is due to the compounding effect, especially during volatile days when LETF is reset daily.  3. True. Because the short life of BITO, the mean returns might not be estimated accurately, especially when the asset is highly volatile. In replicating the returns of BITO with short examples, we should include an intercept to eliminate means and focus on explaining variations.  4. No.  HDG fail to deliver the returns as shown by HFRI adjusted for its risk. HDG is designed to track the MLFM-ES rather than HFRI. Also, HDG has lower kurtosis compared with HFRI.  5. The way that HF replicate their portfolio returns may be different with Merry Lynch factors, also, there might not using different methods in regard to intercept. The alpha alledged by HF might be misleading.<jupyter_code>import pandas as pd
import numpy as np
import math
import scipy
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import math
from numpy.linalg import inv
raw_data = pd.read_excel("proshares_analysis_data.xlsx",sheet_name='merrill_factors',index_col='date')


for i in range(5):
    raw_data.iloc[:,i]=raw_data.iloc[:,i]-raw_data.iloc[:,1]
    
data = raw_data.drop("USGG3M Index",axis=1)
data<jupyter_output><empty_output><jupyter_text>2.1 What are the weights of the tangency portfolio, w tan ?<jupyter_code>mean_data = data.mean()*12
cov_data = data.cov()*12
cov_data_inv = inv(cov_data)
N = cov_data.shape[0]
weights_tangent = cov_data_inv@mean_data/(np.ones(N)@cov_data_inv@mean_data)
tangent_weights = pd.DataFrame({'Weights':weights_tangent},index=data.columns)
tangent_weights
def compute_tangency(df_tilde, diagonalize_Sigma=False):


    Sigma = df_tilde.cov()

    # N is the number of assets

    N = Sigma.shape[0]

    Sigma_adj = Sigma.copy()

    if diagonalize_Sigma:

        Sigma_adj.loc[:,:] = np.diag(np.diag(Sigma_adj))



    mu_tilde = df_tilde.mean()

    Sigma_inv = np.linalg.inv(Sigma_adj)

    weights = Sigma_inv @ mu_tilde / (np.ones(N) @ Sigma_inv @ mu_tilde)

    # For convenience, I'll wrap the solution back into a pandas.Series object.

    omega_tangency = pd.Series(weights, index=mu_tilde.index)

    return omega_tangency, mu_tilde, Sigma_adj

omega_tangency, mu_tilde, Sigma = compute_tangency(data)

omega_tangency.to_frame('Tangency Weights')


def target_mv_portfolio(df_tilde, target_return=0.02, diagonalize_Sigma=False):


    omega_tangency, mu_tilde, Sigma = compute_tangency(df_tilde, diagonalize_Sigma=diagonalize_Sigma)

    Sigma_adj = Sigma.copy()

    if diagonalize_Sigma:

        Sigma_adj.loc[:,:] = np.diag(np.diag(Sigma_adj))

    Sigma_inv = np.linalg.inv(Sigma_adj)

    N = Sigma_adj.shape[0]

    delta_tilde = ((np.ones(N) @ Sigma_inv @ mu_tilde)/(mu_tilde @ Sigma_inv @ mu_tilde)) * target_return

    omega_star = delta_tilde * omega_tangency

    return omega_star, mu_tilde, Sigma_adj


omega_star, mu_tilde, Sigma = target_mv_portfolio(data)

omega_star_df = omega_star.to_frame('MV Portfolio Weights')

omega_star_df
optimal_portfolio_return = omega_star_df.transpose() @ mean_data 
aa = omega_star_df.transpose() @ cov_data @ omega_star_df
optimal_portfolio_std = math.sqrt(aa['MV Portfolio Weights'])
SR = optimal_portfolio_return/optimal_portfolio_std

aaa = {'Return':optimal_portfolio_return['MV Portfolio Weights'], 'Volatility':optimal_portfolio_std,'Sharpe Ratio':SR['MV Portfolio Weights']}
pd.DataFrame(aaa,index=['Optimal Portfolio'])


data_in_sample = data[data.index <= '2018-12-31']

omega_star, mu_tilde, Sigma = target_mv_portfolio(data_in_sample)

omega_star_df2 = omega_star.to_frame('MV Portfolio Weights')

omega_star_df2<jupyter_output><empty_output><jupyter_text>Out of sample<jupyter_code>data_out_sample = data[data.index > '2018-12-31']
optimal_portfolio_return = omega_star_df2.transpose() @ data_out_sample.mean()*12
aat = omega_star_df2.transpose() @ data_out_sample.cov()*12 @ omega_star_df2
optimal_portfolio_std = math.sqrt(aat['MV Portfolio Weights'])
SR = optimal_portfolio_return/optimal_portfolio_std
aaa = {'Return':optimal_portfolio_return['MV Portfolio Weights'], 'Volatility':optimal_portfolio_std,'Sharpe Ratio':SR['MV Portfolio Weights']}
pd.DataFrame(aaa,index=['Optimal Portfolio'])<jupyter_output><empty_output><jupyter_text>The problem will be better, because these assets have lower correlations relative to stocks. They tend not to move toghter at the same time. The portfolio variance will be more stable. As shown, we can see the out-of-sample variance for 5 factors are higher than in sample  Section 3.<jupyter_code>from sklearn.metrics import mean_absolute_error as mae
import scipy
from sklearn import linear_model
import statsmodels.api as sm
x = pd.DataFrame(data.iloc[:,1])
y = pd.DataFrame(data.iloc[:,3])
regr1 = linear_model.LinearRegression(fit_intercept= True)
regr1.fit(x, y)

aaa={'Intercept':regr1.intercept_[0],'Coeff':regr1.coef_[0]}
pd.DataFrame(aaa,index=['Result'])<jupyter_output><empty_output><jupyter_text>Optimal Hedge ratio is the beta,  -0.484675<jupyter_code>beta = regr1.coef_[0]
SPY_hedge_return = data['SPY US Equity'].mean()*beta *12
SPY_hedge_std = data['SPY US Equity'].std()*math.sqrt(12)*beta
SPY_hedge_SR = SPY_hedge_return/SPY_hedge_std
aaa = {'Return':SPY_hedge_return, 'Volatility':SPY_hedge_std,'Sharpe Ratio':SPY_hedge_SR}
pd.DataFrame(aaa,index=['SPY Replicate'])

EEM_return = data['EEM US Equity'].mean()*beta *12
EEM_std = data['EEM US Equity'].std()*math.sqrt(12)*beta
EEM_SR = EEM_return/EEM_std
aaa = {'Return':EEM_return, 'Volatility':EEM_std,'Sharpe Ratio':EEM_SR}
pd.DataFrame(aaa,index=['EEM'])
R_squared = regr1.score(x,y)
R_squared<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10190151145782544, 'fraction_numerical': 0.013164310092637738, 'mean_word_length': 5.953672316384181, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 23, '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}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '452580', 'license': 'MIT', 'n_tokens_mistral': 2241, 'n_tokens_neox': 2088, 'n_words': 540, 'path': 'solutions/mid1/submissions/chenchen_144302_6241795_Midterm Chen Chen -1.ipynb', 'repo_name': 'tulyu96/finm-portfolio-2021', 'size': '6156'}