10.12.2019 Views

Python for Finance

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Python Basics

In Chapter 3, Time Value of Money, we will discuss both means again.

We could say that NumPy is a basic module while SciPy is a more advanced one.

NumPy tries to retain all features supported by either of its predecessors, while most

new features belong in SciPy rather than NumPy. On the other hand, NumPy and

SciPy have many overlapping features in terms of functions for finance. For those

two types of definitions, see the following example:

>>> import scipy as sp

>>> ret=sp.array([0.1,0.05,-0.02])

>>>sp.mean(ret)

0.043333333333333342

>>>pow(sp.prod(ret+1),1./len(ret))-1

0.042163887067679262

Our second example is related to processing theFama-French 3 factor time series.

Since this example is more complex than the previous one, if a user feels it is difficult

to understand, he/she could simply skip this example. First, a ZIP file called F-F_

Research_Data_Factor_TXT.zip could be downloaded from Prof. French's Data

Library. After unzipping and removing the first fewlines and annual datasets, we

will have a monthly Fama-French factor time series. The first few lines and last few

lines are shown here:

DATE MKT_RFSMBHMLRF

192607 2.96 -2.30 -2.87 0.22

192608 2.64 -1.40 4.19 0.25

192609 0.36 -1.32 0.01 0.23

201607 3.95 2.90 -0.98 0.02

201608 0.49 0.94 3.18 0.02

201609 0.25 2.00 -1.34 0.02

Assume that the final file is called ffMonthly.txt under c:/temp/. The following

program is used to retrieve and process the data:

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)

[ 24 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!