Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Python for Finance. - Second Edition

You're reading from  Python for Finance. - Second Edition

Product type Book
Published in Jun 2017
Publisher
ISBN-13 9781787125698
Pages 586 pages
Edition 2nd Edition
Languages

Table of Contents (23) Chapters

Python for Finance Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface
Python Basics Introduction to Python Modules Time Value of Money Sources of Data Bond and Stock Valuation Capital Asset Pricing Model Multifactor Models and Performance Measures Time-Series Analysis Portfolio Theory Options and Futures Value at Risk Monte Carlo Simulation Credit Risk Analysis Exotic Options Volatility, Implied Volatility, ARCH, and GARCH Index

Constructing an optimal portfolio


In finance, we are dealing with a trade-off between risk and return. One of the widely used criteria is Sharpe ratio, which is defined as follows:

The following program would maximize the Sharpe ratio by changing the weights of the stocks in the portfolio. The whole program could be divided into several parts. The input area is very simple, just several tickers in addition to the beginning and ending dates. Then, we define four functions, convert daily returns into annual ones, estimate a portfolio variance, estimate the Sharpe ratio, and estimate the last (that is, nth) weight when n-1 weights are estimated from our optimization procedure:

from matplotlib.finance import quotes_historical_yahoo_ochl as getData
import numpy as np
import pandas as pd
import scipy as sp
from scipy.optimize import fmin
  1. Code for input area:

    ticker=('IBM','WMT','C')   # tickers
    begdate=(1990,1,1)         # beginning date 
    enddate=(2012,12,31)       # ending date
    rf=0.0003        ...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}