Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Python for Finance

You're reading from   Python for Finance Apply powerful finance models and quantitative analysis with Python

Arrow left icon
Product type Paperback
Published in Jun 2017
Publisher
ISBN-13 9781787125698
Length 586 pages
Edition 2nd Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Yuxing Yan Yuxing Yan
Author Profile Icon Yuxing Yan
Yuxing Yan
Arrow right icon
View More author details
Toc

Table of Contents (17) Chapters Close

Preface 1. Python Basics FREE CHAPTER 2. Introduction to Python Modules 3. Time Value of Money 4. Sources of Data 5. Bond and Stock Valuation 6. Capital Asset Pricing Model 7. Multifactor Models and Performance Measures 8. Time-Series Analysis 9. Portfolio Theory 10. Options and Futures 11. Value at Risk 12. Monte Carlo Simulation 13. Credit Risk Analysis 14. Exotic Options 15. Volatility, Implied Volatility, ARCH, and GARCH 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")
You have been reading a chapter from
Python for Finance - Second Edition
Published in: Jun 2017
Publisher:
ISBN-13: 9781787125698
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 $19.99/month. Cancel anytime
Banner background image