Book Image

Python for Finance - Second Edition

By : Yuxing Yan
5 (1)
Book Image

Python for Finance - Second Edition

5 (1)
By: Yuxing Yan

Overview of this book

This book uses Python as its computational tool. Since Python is free, any school or organization can download and use it. This book is organized according to various finance subjects. In other words, the first edition focuses more on Python, while the second edition is truly trying to apply Python to finance. The book starts by explaining topics exclusively related to Python. Then we deal with critical parts of Python, explaining concepts such as time value of money stock and bond evaluations, capital asset pricing model, multi-factor models, time series analysis, portfolio theory, options and futures. This book will help us to learn or review the basics of quantitative finance and apply Python to solve various problems, such as estimating IBM’s market risk, running a Fama-French 3-factor, 5-factor, or Fama-French-Carhart 4 factor model, estimating the VaR of a 5-stock portfolio, estimating the optimal portfolio, and constructing the efficient frontier for a 20-stock portfolio with real-world stock, and with Monte Carlo Simulation. Later, we will also learn how to replicate the famous Black-Scholes-Merton option model and how to price exotic options such as the average price call option.
Table of Contents (23 chapters)
Python for Finance Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface
Index

Data output


The simplest example is given here:

>>>f=open("c:/temp/out.txt","w")
>>>x="This is great"
>>>f.write(x)
>>>f.close()

For the next example, we download historical stock price data first, then write data to an output file:

import re
from matplotlib.finance import quotes_historical_yahoo_ochl
ticker='dell'
outfile=open("c:/temp/dell.txt","w")
begdate=(2013,1,1)
enddate=(2016,11,9)
p=quotes_historical_yahoo_ochl
(ticker,begdate,enddate,asobject=True,adjusted=True)
outfile.write(str(p))
outfile.close()

To retrieve the file, we have the following code:

>>>infile=open("c:/temp/dell.txt","r")
>>>x=infile.read()

One issue is that the preceding saved text file contains many unnecessary characters, such as [ and]. We could apply a substitution function called sub() contained in the Python module;see the simplest example given here:

>>> import re
>>>re.sub("a","9","abc")
>>>
'9bc'
>>>

In the preceding example, we will replace the letter a with9. Interested readers could try the following two lines of code for the preceding program:

p2= re.sub('[\(\)\{\}\.<>a-zA-Z]','', p)
outfile.write(p2)

It is a good idea to generate Python datasets with an extension of .pickle since we can retrieve such data quite efficiently. The following is the complete Python code to generate ffMonthly.pickle. Here, we show how to download price data and then estimate returns:

import numpy as np
import pandas as pd
file=open("c:/temp/ffMonthly.txt","r")
data=file.readlines()
f=[]
index=[]
for i in range(1,np.size(data)):
    t=data[i].split()
    index.append(int(t[0]))
    for j in range(1,5):
        k=float(t[j])
        f.append(k/100)
n=len(f)
f1=np.reshape(f,[n/4,4])
ff=pd.DataFrame(f1,index=index,columns=['Mkt_Rf','SMB','HML','Rf'])
ff.to_pickle("c:/temp/ffMonthly.pickle")