First, we need pandas, numpy, scipy and a datasource for our portfolio. I prefer 'bt' for the later.
import pandas as pd import numpy as np import pandas.io.data as web import datetime import matplotlib.pyplot as plt import bt
from scipy.stats import norm
So lets pull the data
start = datetime.datetime(2013, 5, 1) portfolio = bt.get('aapl, tlt, fxe, gs, c, fb, ms, ko, bac', start=start) port = pd.DataFrame(index=portfolio.columns)
Now we have two dataframes. One with our historical values as portfolio, the other as port which holds the security names which we will later store our VaR values in. Next we create the actual VaRCoV function:
def var_cov_var(P, c, mu, sigma): alpha = norm.ppf(1-c, mu, sigma) return P - P*(alpha + 1)
def getVar(portfolio, c): #portfolio dataframe, confidence interval P = 15000 #each position % of portfolio, should create a new one to store marketvalue of each position to be more precise #c = 0.99 #confidence interval, moved to function totalrisk = 0 for i in portfolio: rets = portfolio[i].pct_change() mu = np.mean(rets) sigma = np.std(rets) var = var_cov_var(P, c, mu, sigma) port["VaR"][i] = var totalrisk += var return port, totalrisk
getVar(portfolio, .95)
Out[471]:
( VaR
aapl 328.585833
tlt 205.453309
fxe 136.978460
gs 274.577792
c 315.838626
fb 566.777609
ms 332.530446
ko 220.500392
bac 319.658819, 2700.9012842524335)
Chees.