Evy555
Evy555

Reputation: 229

Writing a python program that will pull Yahoo Finance stock quotes into Excel

I have created a program that is able to pull monthly stock info from Yahoo Finance and print out a list of the information. I know my methodology for getting the info isn't the best yet, but the part I am stuck on is taking the stock info and writing it to a csv file. What I have so far rights each individual character into a csv file.

import requests
from urllib2 import urlopen
import csv
import pandas as pd
from pandas import DataFrame
import datetime
import pandas.io.data

YahooUrl = 'http://ichart.yahoo.com/table.csv?s='
start_month = 1 - 1
start_day = 1
start_year = 2010

end_month = 12 - 1
end_day = 31
end_year = 2014

Start_ApiMonth = '&a=%s' %(start_month)
Start_ApiDay = '&b=%s' %(start_day)
Start_ApiYear = '&c=%s' %(start_year)

End_ApiMonth = '&d=%s' %(end_month)
End_ApiDay = '&e=%s' %(end_day)
End_ApiYear = '&f=%s' %(end_year)

interval = 'm'

ApiInterval = '&g=%s' %(interval)

ApiStatic = '&ignore=.csv'

Ticker = raw_input("What is the ticker > ")

Website = urlopen(YahooUrl + Ticker + Start_ApiMonth + Start_ApiDay +         Start_ApiYear + End_ApiMonth + End_ApiDay + End_ApiYear + ApiInterval +  ApiStatic)
Info = Website.read()

output = open('output.csv','wb')
wr = csv.writer(output, dialect='excel')
for item in Info:
    wr.writerow(item)
print Info

Upvotes: 0

Views: 3709

Answers (1)

mhawke
mhawke

Reputation: 87054

read() returns a string, hence Info is a string. Iteration over a string results in iterating over each of the characters that comprise the string:

>>> for c in 'abcd':
...     print c
a
b
c
d

Therefore your code will write each character to the csv file on its own line.

The data that you are receiving is actually already in CSV format. Here are the first few lines for stock YHOO:

Date,Open,High,Low,Close,Volume,Adj Close
2014-12-01,51.43,51.68,48.290001,50.509998,16328900,50.509998
2014-11-03,46.049999,52.619999,45.740002,51.740002,25212400,51.740002

So it should simply be a matter of saving the file:

with open('{}.csv'.format(Ticker),'wb') as output:
    output.write(Website.read())

This will write the data to a file named with the stock name followed by .csv extension, e.g. YHOO.csv


Update

The following code shows how to download and merge data for multiple stocks. The output file now needs an additional field to identify the stock - Stock ID. This is inserted as the first CSV field for the header and detail rows. The header is emitted once only.

import requests

yahoo_url = 'http://ichart.yahoo.com/table.csv'
params = {'a': 0, 'b': 1, 'c': 2010, 'd': 11, 'e': 31, 'f': 2014, 'g': 'm', 'ignore': '.csv'}
stock_ids = ['AAPL', 'GOOG', 'YHOO']
with open('output.csv', 'wb') as output:
    header_written = False
    for stock_id in stock_ids:
        params['s'] = stock_id
        r = requests.get(yahoo_url, params=params)
        lines = r.iter_lines()
        header = next(lines)
        if not header_written:
            output.write('Stock ID,{}\n'.format(header))
            header_written = True
        output.writelines('{},{}\n'.format(stock_id, line) for line in lines)

Upvotes: 2

Related Questions