Book Image

Python for Finance

By : Yuxing Yan
Book Image

Python for Finance

By: Yuxing Yan

Overview of this book

Table of Contents (20 chapters)
Python for Finance
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

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)
(0.109, 0.146, 0.127)
>>>round(np.std(A),3),round(np.std(B),3),round(np.std(port_EW),3)
(0.075, 0.074, 0.027)

In the preceding code...