Professional Documents
Culture Documents
Python
Nicolò Ravaglia
February 25, 2016
Abstract
In this paper, I present the implementation of Portfolio Risk Mea-
sures in Python 3.5. Several Risk Measures such as VaR, CVaR and
MVaR are adopted and different methodologies of computation are
showed: Parametric and Historical. The portfolio is dinamical in the
sense that each day computes the Risk Measures taking into account
the past 200 observations. The user can ask the program to download
stocks from Yahoo Finance by typing the Tickers associated to the
stocks and then assign the relative weights.
Keywords: Risk Measures, VaR, CVaR, Python, Portfolio
2 Methodology 3
3 Script 4
3.1 Modules . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3.2 Functions . . . . . . . . . . . . . . . . . . . . . . . . . 4
3.3 Figures . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.4 Outputs . . . . . . . . . . . . . . . . . . . . . . . . . . 18
4 Conclusion 19
1 Brief Introduction
1.1 VaR
Value at Risk is a statistical technique used to measure and quantify
the level of financial risk within a firm or investment portfolio over a
specific time frame. Value at Risk is used by risk managers in order
to measure and control the level of risk which the firm undertakes.
1.2 CVaR
Expected Shortfall or Conditional Value at Risk is a risk measure used
to evaluate the market risk or credit risk of a position or a portfolio.
It is an alternative to Value at Risk which is more sensitive to the
shape of the losses in the tail of the distribution; it is computed as the
expectation beyond the VaR.
1.4 MVaR
The Marginal VaR of a position with respect to a portfolio can be
thought of as the amount of risk that the position is adding to the
portfolio. It can be formally defined as the difference between the
VaR of the total portfolio and the VaR of the portfolio without the
position.
2 Methodology
The program is executed in an interactive way with the user, who asks
for the Tickers of the stocks, the relative weights and other data for the
computation of risk measures. The download of data changes every
day due to the fact that only the past 200 observations are analised:
this method is the most used in the industry and comprises almost one
year of financial data. In this example are presented data related to
’GOOG’, ’AAPL’ and ’HPQ’ which have, respectively, the following
weights 0.5,0.25 and 0.25.
3
3 Script
3.1 Modules
import time
import statistics
import numpy a s np
import s c i p y a s sp
import matplotlib . pyplot as p l t
import ysq
import csv
”time” is used to compute the time required by the program and
the user to run the procedure. ”statistics” is used to compute the mean
of the log-returns. ”numpy” is used to perform matrix operation be-
tween the series of financial data. ”scipy” is used for mathematical
functions. ”matplotlib.pyplot” is used to create the plots of the dis-
tributions as well as series of returns. ”csv” is used to save the data
in a CSV format. ”ysq” is a script that permits the download of data
from Yahoo Finance: it can be downloaded Here.
3.2 Functions
Insert tickers by asking to the user.
SymbolList = [ ]
def AskforTickers ( ) :
while 1:
T i c k e r s = i n p u t ( ” Enter t h e t i c k e r : ” )
SymbolList . append ( [ T i c k e r s ] )
i f T i c k e r s != ’ Exit ’ :
p r i n t ( ’ The t i c k e r i s now i n s i d e t h e T i c k e r s L i s t ’ )
else :
break
d e l SymbolList [ −1]
p r i n t ( SymbolList )
return ’ ’
Use this if you do not want the program to ask for the tickers to
the user: SymbolList = [[’AAPL’],[’HPQ’],[’GOOG’]].
4
Create the dates for the 200 observations.
ListD = [ ]
def ListDates ( ) :
s t a r t d a t e = ’2015 −01 −01 ’
end d a t e = today
symbol = ’AAPL’ # j u s t t o g i v e i t t h e symbol
by which a l l d a t e s a r e downloaded .
# Problem : i f t h e S t o c k s have d i f f e r e n t day s e r i e s
t h e r e i s a mismatch
# S o l u t i o n : h e r e we have s t o c k s with same d a t e s e r i e s
Stocks dates =
ysq . g e t h i s t o r i c a l p r i c e s ( symbol , s t a r t date , end d a t e )
If you do not want to use the pre-specified set of dates, use the fol-
lowing for example (be aware that in so doing you have to modify the
set of 200 observations): SymbolList = [[’AAPL’,’2015-01-01’,’2015-
10-19’], [’GOOG’,’2015-01-01’,’2015-10-19’], [’HPQ’,’2015-01-01’,’2015-
10-19’]]
5
Delete the dates up to the 201 observation so as to com-
pute the Portfolio Profit and Loss.
u = l e n ( ListD )
while u > 201:
d e l ListD [ −1]
# p r i n t ( ListD )
u = u − 1
Stocks l i s t =
ysq . g e t h i s t o r i c a l p r i c e s ( symbol , s t a r t date , end d a t e )
# p r i n t ( S t o c k s l i s t ) −− l e n ( S t o c k s l i s t )=202
ListS = [ ]
f o r t in range (1 , len ( Stocks l i s t ) ) : # d e c r e a s i n g the l i s t
to 201: look at the s t a r t i n g value
L i s t S . append ( S t o c k s l i s t [ t ] [ − 1 ] )
# L i s t S t o c k s = map( f l o a t , L i s t S ) i s a n o t h e r o n l y
t e m p o r a r e l y way t o do i t
j = 1
ListReturns = [ ]
w h i l e j <l e n ( L i s t S ) :
a = sp . l o g ( L i s t S [ j ] / L i s t S [ j −1])
L i s t R e t u r n s . append ( a )
6
j=j +1
# print ( ListReturns )
L i s t T o t R e t u r n s . append ( L i s t R e t u r n s )
i+=1
return ’ ’
p r i n t ( C r e a t e L o g R e t u r n S e r i e s ( L i s t T o t R e t u r n s , SymbolList ) )
ModList = [ ]
f o r n in range ( len ( ListTotReturns [ 0 ] ) ) : # i t puts the s e r i e s 1
r e t u r n f o l l o w e d by t h e s e r i e s 2 r e t u r n and s o on . .
p = 0
while p < len ( ListTotReturns ) :
ModList . append ( [ L i s t T o t R e t u r n s [ p ] [ n ] ] )
p+=1
# p r i n t ( ModList )
ModListTotReturns = np . a r r a y ( ModList , f l o a t )
ModListTotReturns =
ModListTotReturns . r e s h a p e ( 2 0 0 , i n t ( l e n ( SymbolList ) ) )
# p r i n t ( ModListTotReturns )
csvFile . close ()
7
Portfolio weights assignment.
PortfolioW = [ ]
def WeightsCreation ( PortfolioW ) :
p e s i = f l o a t ( i n p u t ( ’ Enter t h e P o r t f o l i o w e i g h t s : ’ ) )
P o r t f o l i o W . append ( p e s i )
#p r i n t ( p e s i )
Summation = sum (map( f l o a t , P o r t f o l i o W ) )
i f round ( Summation , 3 ) == 1 . 0 :
i f l e n ( P o r t f o l i o W ) == l e n ( SymbolList ) :
r e t u r n ’ Weights sum up t o 1 ’
else :
P o r t f o l i o W [ : ] = [ ] #i t empty t h e l i s t o f w e i g h t s
p r i n t ( ’ Weights and T i c k e r s do not c o i n c i d e . ’ )
p r i n t ( WeightsCreation ( PortfolioW ) )
return ’ ’
e l i f round ( Summation , 3 ) < 1 . 0 :
p r i n t ( WeightsCreation ( PortfolioW ) )
return ’ ’
e l s e : # c o n d i t i o n i f t h e w e i g h t s a r e g r e a t e r than 1
PortfolioW [ : ] = [ ]
p r i n t ( ’ P l e a s e , e n t e r t h e c o r r e c t number o f w e i g h t s : ’ )
p r i n t ( WeightsCreation ( PortfolioW ) )
return ’ ’
p r i n t ( WeightsCreation ( PortfolioW ) )
Weights = np . a r r a y ( PortfolioW , f l o a t )
8
Plot the Histogram of the Profit and Loss Distribution.
p l t . f i g u r e ( f i g s i z e =(10 , 6 ) ) #i t c r e a t e s a f i g u r e
ax = p l t . s u b p l o t ( 1 1 1 )
# ”111” means ”1 x1 g r i d , f i r s t s u b p l o t ”
ax . s p i n e s [ ” top ” ] . s e t v i s i b l e ( F a l s e )
ax . s p i n e s [ ” r i g h t ” ] . s e t v i s i b l e ( F a l s e )
ax . g e t x a x i s ( ) . t i c k bottom ( )
# s o a s t o s e e t h e t i c k s o n l y on t h e r i g h t and a t t h e bottom
ax . g e t y a x i s ( ) . t i c k l e f t ( )
p l t . x t i c k s ( f o n t s i z e =14)
p l t . y t i c k s ( r a n g e ( 5 , 1 0 1 , 5 ) , f o n t s i z e =14)
# CVaR
VaRs =[PLVaR0 ,PLVaR1 ]
PLCVaR = s t a t i s t i c s . mean ( VaRs )
p r i n t ( ’ The P&L CVaR ( 9 9%) i s ’ )
p r i n t ( ”%. 4 f%%” % (100 ∗ PLCVaR) )
9
Compute the correlation between the series.
S e r i e s = np . a r r a y ( L i s t T o t R e t u r n s , f l o a t )
p r i n t ( ’ The C o r r e l a t i o n Matrix i s : ’ )
CorrMatrix = np . c o r r c o e f ( S e r i e s )
# i t g i v e s you t h e n o r m a l i s e d C o v a r i a n c e Matrix , which i s t h e
C o r r e l a t i o n Matrix
p r i n t ( CorrMatrix )
print ( ’\n ’ )
p r i n t ( ’ The P o r t f o l i o Mean i s : ’ )
Pmean = s t a t i s t i c s . mean ( P r o f i t a n d L o s s D )
p r i n t ( ”%. 3 f%%” % (100 ∗ Pmean ) )
p r i n t ( ’ The P o r t f o l i o V a r i a n c e i s : ’ )
#p r i n t ( ” { 0 : . 3 f }%” . f o r m a t ( PVariance ∗ 1 0 0 ) )
#o t h e r way t o p r i n t t h e p e r c e n t a g e v a l u e
p r i n t ( ”%. 3 f%%” % (100 ∗ PVariance ) )
p r i n t ( ’ The P o r t f o l i o V o l a t i l i t y i s : ’)
PVol = np . s q r t ( PVariance )
p r i n t ( ”%. 3 f%%” % (100 ∗ PVol ) )
10
Parametric VaR Computation.
d e f ParametricMeasureVaR ( P r o f i t a n d L o s s D ) :
print ( ’\n ’ )
p r i n t ( ” P a r a m e t r i c VaR computation ” )
#P = e v a l ( i n p u t ( ” Enter t h e s t o c k amount : ” ) )
t = e v a l ( i n p u t ( ” Enter t h e time p e r i o d : ” ) )
a l p h a = e v a l ( i n p u t ( ” Enter t h e c o n f i d e n c e l e v e l ( ex : 2 . 3 3 ,
1.65): ”))
Nalpha = −a l p h a
T = sp . s q r t ( t )
#Ask t o u s e t h e EWMA o r t h e H i s t o r i c a l V o l a t i l i t y
ask = i n p u t ( ’ Do you want t h e EWMA V o l a t i l i t y o r t h e
H i s t o r i c a l one ( y ) ? ’ )
i f ask == ’ y ’ :
ParametricVaR = PVol∗ Nalpha ∗T
r e t u r n ”%. 4 f%%” % (100 ∗ ParametricVaR )
else :
# Use EWMA V o l a t i l i t y f o r t h e P a r a m e t r i c VaR
PandLD = [ item ∗∗2 f o r item i n P r o f i t a n d L o s s D ]
#p r i n t (PandLD)
#p r i n t ( l e n (PandLD ) )
Lambda = 0 . 9 4
EWMAVariance = [ ]
f o r i i n r a n g e ( l e n (PandLD ) ) :
EWMAvariance = (1−Lambda ) ∗ ( Lambda∗∗ i ) ∗PandLD [ i ]
EWMAVariance . append ( EWMAvariance )
d e f AskforParametricVaR ( ) :
a = i n p u t ( ’ Do you want t o compute t h e p a r a m e t r i c VaR? ’ )
i f a == ’ y ’ :
p r i n t ( ParametricMeasureVaR ( P r o f i t a n d L o s s D ) )
else :
p r i n t ( ’ No P a r a m e t r i c VaR r e q u i r e d f o r t h i s s e s s i o n . ’ )
return ’ ’
p r i n t ( AskforParametricVaR ( ) )
11
Plot the Portfolio Series and Profit and Loss returns.
d e f PlotSeriesandPLD ( SymbolList , S e r i e s , P r o f i t a n d L o s s D ) :
i = 0
w h i l e i < l e n ( SymbolList ) :
FirstPlot = plt . plot ( Series [ i ] , ’g ’ )
p l t . x l a b e l ( ’ Observations ’ )
p l t . y l a b e l ( ’ Log−Returns ’ )
p l t . t i t l e ( SymbolList [ i ] [ 0 ] )
p l t . g r i d ( True )
p l t . s a v e f i g ( ” Log−Return−S e r i e s ”+SymbolList [ i ] [ 0 ] + ” . png ” ,
bbox i n c h e s =” t i g h t ” )
p l t . show ( )
print ( FirstPlot )
i+=1
P o r t f o l i o P l o t = p l t . p l o t ( ProfitandLossD , ’ r ’ )
p l t . x l a b e l ( ’ Observations ’ )
p l t . y l a b e l ( ’ Log−Returns ’ )
p l t . t i t l e ( ’P&L ’ )
p l t . g r i d ( True )
p l t . s a v e f i g ( ”P&L−Log−Return−S e r i e s . png ” , bbox i n c h e s =” t i g h t ” )
p l t . show ( )
print ( PortfolioPlot )
d e f Askt oPlot ( ) :
Graphs = i n p u t ( ’ Do you want t o s e e t h e P l o t s ? ’ )
i f Graphs == ’ y ’ :
p r i n t ( PlotSeriesandPLD ( SymbolList , S e r i e s , P r o f i t a n d L o s s D ) )
else :
p r i n t ( ’ No p l o t s r e q u i r e d f o r t h i s s e s s i o n . ’ )
return ’ ’
p r i n t ( As ktoPlo t ( ) )
12
Marginal VaR and CVaR.
13
ModListTotReturns s =
ModListTotReturns s . r e s h a p e ( 2 0 0 , i n t ( l e n ( SymbolList s ) ) )
#p r i n t ( ModListTotReturns s )
Weights s = np . a r r a y ( ModPortfolioW s , f l o a t )
P r o f i t a n d L o s s D s = np . dot ( ModListTotReturns s , Weights s )
PLDsorted s = np . s o r t ( P r o f i t a n d L o s s D s )
# VaR
PLVaR0 s = PLDsorted s [ 0 ]
PLVaR1 s = PLDsorted s [ 1 ]
# CVaR
VaRs s =[PLVaR0 s , PLVaR1 s ]
PLCVaR s = s t a t i s t i c s . mean ( VaRs s )
ResultVaR = PLVaR1 s − PLVaR1
ResultCVaR = PLCVaR s − PLCVaR
# r e p r ( ResultVaR )
p r i n t ( ’ The Marginal VaR ( 9 9%) o f ’ + t i c k e r + ’ i s ’ + ”%.3 f%
%” % (100 ∗ ResultVaR ) )
p r i n t ( ’ The Marginal CVaR ( 9 9%) o f ’ + t i c k e r + ’ i s ’ + ”%.3 f
%%” % (100 ∗ ResultCVaR ) )
return ’ ’
def AskforMarginalMeasures s ( ) :
q u e s t i o n = i n p u t ( ’ Do you want t o compute t h e MVaRs? ’ )
i f q u e s t i o n ==’y ’ :
MarginalMeasures s ( SymbolList , PortfolioW , L i s t T o t R e t u r n s )
else :
p r i n t ( ’ No MarginalMeasures r e q u i r e d f o r t h i s s e s s i o n . ’ )
return ’ ’
p r i n t ( AskforMarginalMeasures s ( ) )
# Here t h e r e a r e t h e f u n c t i o n s
14
3.3 Figures
15
16
The CSV file can be downloaded Here.
17
3.4 Outputs
The C o r r e l a t i o n Matrix i s :
[ [ 1. 0.4481005 0.36122859]
[ 0.4481005 1. 0.28031843]
[ 0.36122859 0.28031843 1. ]]
The C o v a r i a n c e Matrix i s :
[ [ 0.00033067 0.00016365 0.00016117]
[ 0.00016365 0.00040335 0.00013814]
[ 0.00016117 0.00013814 0.00060204]]
The P o r t f o l i o Mean i s :
0 . 0 7 4%
The P o r t f o l i o V a r i a n c e i s :
0 . 0 2 4%
The P o r t f o l i o V o l a t i l i t y i s :
1 . 5 6 2%
P a r a m e t r i c VaR computation
Enter t h e time p e r i o d : 1
Enter t h e c o n f i d e n c e l e v e l ( ex : 2 . 3 3 , 1 . 6 5 ) : 2 . 3 3
18
Do you want t h e EWMA V o l a t i l i t y o r t h e H i s t o r i c a l one ( y ) ? y
−3.6394%
[0.6666666666666666 , 0.3333333333333333]
4 Conclusion
This work would be further improved with the introduction of Monte
Carlo (MC) computations. As of today, in this paper only Parametric
and Historical methods are showed.
19