<jupyter_start><jupyter_text>Creates function that converts vector to column vector<jupyter_code>import numpy as np
import pandas as pd

def as_colvec(x):   
    if (x.ndim == 2):
        return x
    else:
        return np.expand_dims(x,axis=1)<jupyter_output><empty_output><jupyter_text>Creates 4d array<jupyter_code>np.arange(4)<jupyter_output><empty_output><jupyter_text>Creates a 4d column vector<jupyter_code>as_colvec (np.arange(4))<jupyter_output><empty_output><jupyter_text>Function that calculates Implied Returns<jupyter_code>def implied_returns(delta,sigma,w):    #delta= risk aversion coefficient, sigma= var covar matrix, w=portfolio weights
    ir = delta* sigma.dot(w).squeeze()
    ir.name = 'Implied Returns'
    return ir<jupyter_output><empty_output><jupyter_text>Black Litterman Functions<jupyter_code>def proportional_prior(sigma,tau,p):
    helit_omega = p.dot(tau*sigma).dot(p.T)
    return pd.DataFrame(np.diag(np.diag(helit_omega.values)),index=p.index, columns=p.index)
from numpy.linalg import inv

def bl(w_prior, sigma_prior, p, q, 
       omega = None,
       delta=7.5, tau=.20):

    if omega is None:
         omega = proportional_prior(sigma_prior, tau, p)
    
    N = w_prior.shape[0]
    
    K = q.shape[0]
    
    pi = implied_returns(delta, sigma_prior, w_prior)
    
    sigma_prior_scaled = tau * sigma_prior
    
    nu_bl = pi + sigma_prior_scaled.dot(p.T).dot(inv(p.dot(sigma_prior_scaled).dot(p.T)+ omega).dot(q-p.dot(pi).values))
    ##nu_bl = pi + (p.T).dot(sigma_prior_scaled).dot(inv(sigma_prior_scaled.dot(p)).dot(p.T)+ omega).dot(q-p.dot(pi).values)
    #nu_bl = pi + (p.T)@(sigma_prior_scaled)@(inv(sigma_prior_scaled@(p))@(p.T)+ omega)@(q-p@(pi).values)

    
    sigma_bl = sigma_prior + sigma_prior_scaled - sigma_prior_scaled.dot(p.T).dot(inv(p.dot(sigma_prior_scaled).dot(p.T)+ omega)).dot(p).dot(sigma_prior_scaled)
    ##sigma_bl = sigma_prior + sigma_prior_scaled - (p.T).dot(sigma_prior_scaled).dot(inv(sigma_prior_scaled.dot(p).dot(p.T)+ omega)).dot(sigma_prior_scaled).dot(p)
    
    #sigma_bl = sigma_prior + sigma_prior_scaled - (p.T)@(sigma_prior_scaled)@(inv(sigma_prior_scaled@ p @(p.T)+ omega))@(sigma_prior_scaled)@p

    return (nu_bl, sigma_bl)<jupyter_output><empty_output><jupyter_text>Reads in Data Reads only columns A:H from Excel i.e. until "Cash". Not the rest of the columns. It reads the prices and computes the returns of each product i.e. the percentage change between two successive prices.<jupyter_code>prices = pd.read_excel('prices.xlsx',header=1,index_col=0, parse_dates= True, usecols="A:H")
returns = prices.pct_change()
returns = returns.dropna()

#print(prices)<jupyter_output><empty_output><jupyter_text>Computes the Covariance of returns and multiplies with 52 weeks to get year's covariance.<jupyter_code>#returns= pd.DataFrame(returns)

#tickers = returns[:0] 
tickers = ['Euro Gov', 'Greek Gov', 'EU Corporate', 'EU HY' , 'Eur Eq', 'US Eq', 'Cash']
s = returns.cov()*52
s = np.matrix(s)
s = pd.DataFrame(s,index=tickers, columns=tickers)<jupyter_output><empty_output><jupyter_text>Computes Implied Returns Weights<jupyter_code>#input the weights of the benchmark
WEuroGov = .30
WGreekGov = .10
WEUCorporate = .20
WEUHY = .05
WEurEq = .10
WUSEq = .10
WCash = .15

weights = pd.Series([WEuroGov, WGreekGov, WEUCorporate, WEUHY, WEurEq, WUSEq, WCash],index= tickers)
#weights = np.matrix(weights)
#weights = pd.DataFrame(weights)

pi=implied_returns(delta=7.5,sigma=s, w=weights)
pi

def inverse(d):
    
    return pd.DataFrame(inv(d.values), index=d.columns, columns=d.index)

def w_msr(sigma, mu, scale=True):
    
    w = inverse(sigma).dot(mu)
    
    if scale:
        w= w/sum(w)
        return w
    
#input the expectations
EEuroGov = .50
EGreekGov = .10
EEUCorporate = .20
EEUHY = .05
EEurEq = .05
EUSEq = .05
ECash = .0

mu_exp = pd.Series([EEuroGov, EGreekGov, EEUCorporate, EEUHY, EEurEq, EUSEq, ECash], index=tickers)
np.round(w_msr(s, mu_exp)*100,2)
q= pd.Series(mu_exp)

p= pd.DataFrame([
    {'Euro Gov':1, 'Greek Gov':0, 'EU Corporate':0, 'EU HY':0, 'Eur Eq':0, 'US Eq':0, 'Cash':0},
    {'Euro Gov':0, 'Greek Gov':1, 'EU Corporate':0, 'EU HY':0, 'Eur Eq':0, 'US Eq':0, 'Cash':0},
    {'Euro Gov':0, 'Greek Gov':0, 'EU Corporate':1, 'EU HY':0, 'Eur Eq':0, 'US Eq':0, 'Cash':0},
    {'Euro Gov':0, 'Greek Gov':0, 'EU Corporate':0, 'EU HY':1, 'Eur Eq':0, 'US Eq':0, 'Cash':0},
    {'Euro Gov':0, 'Greek Gov':0, 'EU Corporate':0, 'EU HY':0, 'Eur Eq':1, 'US Eq':0, 'Cash':0},
    {'Euro Gov':0, 'Greek Gov':0, 'EU Corporate':0, 'EU HY':0, 'Eur Eq':0, 'US Eq':1, 'Cash':0},
    {'Euro Gov':0, 'Greek Gov':0, 'EU Corporate':0, 'EU HY':0, 'Eur Eq':0, 'US Eq':0, 'Cash':1}
    ])

bl_mu, bl_sigma = bl(w_prior= weights, sigma_prior=s, p=p, q=q)

bl_mu
w_msr(bl_sigma, bl_mu)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1643124221022019, 'fraction_numerical': 0.02098047361861238, 'mean_word_length': 4.893512851897185, 'pattern_counts': {'":': 0, '<': 33, '<?xml version=': 0, '>': 33, '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': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '197073', 'license': 'Apache-2.0', 'n_tokens_mistral': 2132, 'n_tokens_neox': 1955, 'n_words': 398, 'path': 'Archive/Main-Black-Litterman-Examples/BL 2nd attempt (coursera input).ipynb', 'repo_name': 'liaskast/Jupyter-Notebook-Portfolio-Optimization', 'size': '4814'}