<jupyter_start><jupyter_text>**4.1a**<jupyter_code>V_P = portfolio_variance(Var, weight)
V_P = round(V_P[:, 0][0], 5)
V_P<jupyter_output><empty_output><jupyter_text>**4.1b**<jupyter_code># beta_i = cov(Rmarket, Ri) / var(Rmarket)
# cov(aX + bY, Z) = a × cov(X, Z) + b × cov(Y, Z)

beta_1 = 0.064 / 0.04
print('Beta for Asset 1: ' + str(beta_1))

beta_2 = 0.032 / 0.04
print('Beta for Asset 2: ' + str(beta_2))

beta_P = (0.4 * 0.064 + 0.4 * 0.032) / 0.04
beta_P = round(beta_P, 5)
print('Beta for portfolio: ' + str(beta_P))<jupyter_output>Beta for Asset 1: 1.6
Beta for Asset 2: 0.8
Beta for portfolio: 0.96<jupyter_text>**4.1c**<jupyter_code># E[ri] − rf = βi (E[rmarket] − rf )

E_P = beta_P * (0.1 - 0.04) + 0.04
print('Expected return for portfolio is: ' + str(E_P))<jupyter_output>Expected return for portfolio is: 0.0976<jupyter_text>**4.1d**<jupyter_code># Refer to the attacked document for calculation details<jupyter_output><empty_output><jupyter_text>**4.2a1**<jupyter_code>data_raw = pd.read_csv('ps4_data.csv')
data_raw
data_raw.columns.values
data_raw.describe()
df = data_raw
df = df.set_index('Date')
df
df.columns
df_raw = df.sub(df['T-bills'], axis=0)
df_raw = df_raw.drop(columns=['T-bills'])
df_raw
#Portfolio 1: GM and IBM
w_1 = np.array([0.5, 0.5])
w_1 = w_1.reshape((1,-1))
w_1 = w_1.transpose()
w_1
#Portfolio 2: GM, IBM and Anheuser Busch
w_2 = np.array([1/3, 1/3, 1/3])
w_2 = w_2.reshape((1,-1))
w_2 = w_2.transpose()
w_2
#Portfolio 3: GM, Toyota, IBM and Anheuser Busch
w_3 = np.array([1/4, 1/4, 1/4, 1/4])
w_3 = w_3.reshape((1,-1))
w_3 = w_3.transpose()
w_3
#Portfolio 4: 'TOYOTA', 'GM', 'BMW', 'FORD', 'CHRYSLER', 'APPLE', 'IBM', 'COMPAQ', 'HP', 
#'BUSCH','HEINEKEN', 'KIRIN', 'MOLSON'
w_4 = np.ones(13)
w_4 /= 13
w_4 = w_4.reshape((1,-1))
w_4 = w_4.transpose()
w_4
df = df_raw/100
df
describe = df.describe()
describe.loc['mean']
mu_temp = np.array([[describe.loc['mean','GM'], describe.loc['mean','IBM']]])
mu_1 = mu_temp @ w_1
covar_1 = df[['GM', 'IBM']].cov()
var_1 = portfolio_variance(covar_1, w_1)
print('Average monthly excess return for Portfolio 1: ' + str(round(mu_1[:, 0][0] * 100, 5)) + '%')
print('Variance of monthly excess return for Portfolio 1: ' + str(round(var_1.iloc[0,0], 5)))
mu_temp = np.array([[describe.loc['mean','GM'], describe.loc['mean','IBM'], describe.loc['mean','BUSCH']]])
mu_2 = mu_temp @ w_2
covar_2 = df[['GM', 'IBM', 'BUSCH']].cov()
var_2 = portfolio_variance(covar_2, w_2)
print('Average monthly excess return for Portfolio 2: ' + str(round(mu_2[:, 0][0]*100, 5)) + '%')
print('Variance of monthly excess return for Portfolio 2: ' + str(round(var_2.iloc[0,0], 5)))
mu_temp = np.array([[describe.loc['mean','GM'], describe.loc['mean','IBM'], describe.loc['mean','BUSCH'], describe.loc['mean','TOYOTA']]])
mu_3 = mu_temp @ w_3
covar_3 = df[['GM', 'IBM', 'BUSCH','TOYOTA']].cov()
var_3 = portfolio_variance(covar_3, w_3)
print('Average monthly excess return for Portfolio 3: ' + str(round(mu_3[:, 0][0]*100, 5)) + '%')
print('Variance of monthly excess return for Portfolio 3: ' + str(round(var_3.iloc[0,0], 5)))
mu_temp = np.array([describe.iloc[1,-13:]])
mu_4 = mu_temp @ w_4
covar_4 = df.iloc[:,-13:].cov()
var_4 = portfolio_variance(covar_4, w_4)
print('Average monthly excess return for Portfolio 4: ' + str(round(mu_4[:, 0][0]*100, 5)) + '%')
print('Variance of monthly excess return for Portfolio 4: ' + str(round(var_4.iloc[0,0], 5)))<jupyter_output>Average monthly excess return for Portfolio 4: 1.22384%
Variance of monthly excess return for Portfolio 4: 0.00251<jupyter_text>**4.2a2**<jupyter_code>df.iloc[:,-13:]
from sklearn.linear_model import LinearRegression
Y_1 = (df['IBM'] * 0.5).add(0.5 * df['GM'], axis=0)
X_1 = df[['Market: World']]
reg_1 = LinearRegression().fit(X_1, Y_1)
print('Portfolio 1 Beta from linear reg: ' + str(reg_1.coef_[0]))

# beta_i = cov(Rmarket, Ri) / var(Rmarket)
# cov(aX + bY, Z) = a × cov(X, Z) + b × cov(Y, Z)
covar_P1 = df[['GM', 'IBM', 'Market: World']].cov()
beta_P1 = (0.5 * covar_P1.iloc[0,2] + 0.5 * covar_P1.iloc[1,2]) / covar_P1.iloc[2,2]
print('Portfolio 1 Beta from definition: ' + str(beta_P1))
(df['IBM'] * 0.5).add(0.5 * df['GM'], axis=0)
X_1
covar_P1 = df[['GM', 'IBM', 'Market: World']].cov()
covar_P1
Y_2 = (df['IBM'] / 3).add(df['GM'] / 3, axis=0).add(df['BUSCH'] / 3, axis=0)
X_2 = df[['Market: World']]
reg_2 = LinearRegression().fit(X_2, Y_2)
print('Portfolio 2 Beta from linear reg: ' + str(reg_2.coef_[0]))

# beta_i = cov(Rmarket, Ri) / var(Rmarket)
# cov(aX + bY, Z) = a × cov(X, Z) + b × cov(Y, Z)
covar_P2 = df[['GM', 'IBM', 'BUSCH', 'Market: World']].cov()
beta_P2 = ( covar_P2.iloc[0,3] / 3 + covar_P2.iloc[1,3] / 3 + covar_P2.iloc[2,3] / 3) / covar_P2.iloc[3,3]
print('Portfolio 2 Beta from definition: ' + str(beta_P2))
Y_3 = (df['IBM'] / 4).add(df['GM'] / 4, axis=0).add(df['BUSCH'] / 4, axis=0).add(df['TOYOTA'] / 4, axis=0)
X_3 = df[['Market: World']]
reg_3 = LinearRegression().fit(X_3, Y_3)
print('Portfolio 3 Beta from linear reg: ' + str(reg_3.coef_[0]))

# beta_i = cov(Rmarket, Ri) / var(Rmarket)
# cov(aX + bY, Z) = a × cov(X, Z) + b × cov(Y, Z)
covar_P3 = df[['GM', 'IBM', 'BUSCH', 'TOYOTA', 'Market: World']].cov()
beta_P3 = ( covar_P3.iloc[0,4] / 4 + covar_P3.iloc[1,4] / 4 + covar_P3.iloc[2,4] / 4 + covar_P3.iloc[3,4] / 4) / covar_P3.iloc[4,4]
print('Portfolio 3 Beta from definition: ' + str(beta_P3))
Y_4 = (df.iloc[:,-13:] / 13).sum(axis=1)
X_4 = df[['Market: World']]
reg_4 = LinearRegression().fit(X_4, Y_4)
print('Portfolio 4 Beta from linear reg: ' + str(reg_4.coef_[0]))

# beta_i = cov(Rmarket, Ri) / var(Rmarket)
# cov(aX + bY, Z) = a × cov(X, Z) + b × cov(Y, Z)
covar_P4 = pd.concat([df.iloc[:,-13:], df[['Market: World']]], axis=1).cov()
beta_P4 = ( covar_P4.iloc[:-1,13].sum() / 13) / covar_P4.iloc[13,13]
print('Portfolio 4 Beta from definition: ' + str(beta_P4))<jupyter_output>Portfolio 4 Beta from linear reg: 0.9312077484900599
Portfolio 4 Beta from definition: 0.9312077484900597<jupyter_text>**4.2a3**<jupyter_code># Refer to the attacked document for discussion details<jupyter_output><empty_output><jupyter_text>**4.2b1**<jupyter_code>reg_list = []
for i in range(13):
    Y_each = df.iloc[:,-13+i]
    X_each = df[['Market: World']]
    reg_each = LinearRegression().fit(X_each, Y_each)
    reg_list.append(reg_each.coef_[0])
    print('Beta of each 13 common stock from linear reg: ' + str(reg_each.coef_[0]))


df_reg = pd.DataFrame(data={'Beta': reg_list})
df_reg['Stock Name'] = df.iloc[:,-13:].columns.values
df_reg = df_reg.set_index('Stock Name')
df_reg
beta_P1_new = sum(df_reg.loc[['GM','IBM'],'Beta'].tolist())/2
print('Portfolio 1 Beta from definition: ' + str(beta_P1))
print('Portfolio 1 Beta from weighted average of each asset: ' + str(beta_P1_new))
beta_P2_new = sum(df_reg.loc[['GM','IBM','BUSCH'],'Beta'].tolist())/3
print('Portfolio 2 Beta from definition: ' + str(beta_P2))
print('Portfolio 2 Beta from weighted average of each asset: ' + str(beta_P2_new))
beta_P3_new = sum(df_reg.loc[['GM','IBM','BUSCH','TOYOTA'],'Beta'].tolist())/4
print('Portfolio 3 Beta from definition: ' + str(beta_P3))
print('Portfolio 3 Beta from weighted average of each asset: ' + str(beta_P3_new))
beta_P4_new = sum(df_reg.iloc[:,0].tolist())/13
print('Portfolio 4 Beta from definition: ' + str(beta_P4))
print('Portfolio 4 Beta from weighted average of each asset: ' + str(beta_P4_new))<jupyter_output>Portfolio 4 Beta from definition: 0.9312077484900597
Portfolio 4 Beta from weighted average of each asset: 0.9312077484900596<jupyter_text>**4.2b2**<jupyter_code>capm_expected_return_list = []
for i in range(13):
    capm_expected_return_list.append(reg_list[i] * describe.loc['mean','Market: World'])

capm_expected_return_list
describe.iloc[1,-13:].tolist()
plt.figure(figsize=(8, 5))
plt.xlabel('Common Stock')
plt.ylabel('Return')
plt.xticks(rotation=90)
plt.plot(df.iloc[:,-13:].columns.values, describe.iloc[1,-13:].tolist(),'bo', markersize=10, label='Sample Average')
plt.plot(df.iloc[:,-13:].columns.values, capm_expected_return_list,'ro', markersize=10, label='CAPM Expected')
plt.legend(bbox_to_anchor=(0, 1), loc='upper left', ncol=1)
plt.show()<jupyter_output><empty_output><jupyter_text>**3a**<jupyter_code>prob = 10 * pow(0.5, 9) * 0.5 + pow(0.5, 10)
print('Probably of any given manager achieves: ' + str(prob))
i=1
prob_best=0
for i in range(1,501):
    prob_best += pow(prob, i)* pow((1 - prob), 500-i) * (math.factorial(500)/(math.factorial(i)*math.factorial(500-i))) 
print('Probably of at least 1 out of 500 manager achieves: ' + str(prob_best))<jupyter_output>Probably of at least 1 out of 500 manager achieves: 0.9954840995436917
{'fraction_non_alphanumeric': 0.2026635784597568, 'fraction_numerical': 0.06577880718008107, 'mean_word_length': 5.658442559753277, 'pattern_counts': {'":': 0, '<': 35, '<?xml version=': 0, '>': 35, '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': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '465865', 'license': 'MIT', 'n_tokens_mistral': 4059, 'n_tokens_neox': 3726, 'n_words': 780, 'path': 'Assignment4_DongZheng.ipynb', 'repo_name': 'nusstu-dz/DBA5109-Quantitative-Risk-Management', 'size': '8635'}