10.12.2019 Views

Python for Finance

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Python Basics

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")

[ 26 ]

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

Saved successfully!

Ooh no, something went wrong!