O'Reilly logo

Python for Finance by Yuxing Yan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Graphical representation of the portfolio diversification effect

In finance, we could remove firm-specific risk by combining different stocks in our portfolio. First, let us look at a hypothetical case by assuming that we have 5 years' annual returns of two stocks as follows:

Year

Stock A

Stock B

2009

0.102

0.1062

2010

-0.02

0.23

2011

0.213

0.045

2012

0.12

0.234

2013

0.13

0.113

We form an equal-weighted portfolio using those two stocks. Using the mean() and std() functions contained in NumPy, we can estimate their means, standard deviations, and correlation coefficients as follows:

>>>import numpy as np
>>>A=[0.102,-0.02, 0.213,0.12,0.13]
>>>B=[0.1062,0.23, 0.045,0.234,0.113]
>>>port_EW=(np.array(ret_A)+np.array(ret_B))/2.
>>>round(np.mean(A),3),round(np.mean(B),3),round(np.mean(port_EW),3) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required