Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To: Python Pandas get current stock data

I've used:

data = DataReader("yhoo", "yahoo", datetime.datetime(2000, 1, 1),
                  datetime.datetime.today())

in pandas (python) to get history data of yahoo, but it cannot show today's price (the market has not yet closed) how can I resolve such problem, thanks in advance.

like image 596
perigee Avatar asked Jun 03 '13 18:06

perigee


2 Answers

import pandas
import pandas.io.data
import datetime
import urllib2
import csv

YAHOO_TODAY="http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=sd1ohgl1vl1"

def get_quote_today(symbol):
    response = urllib2.urlopen(YAHOO_TODAY % symbol)
    reader = csv.reader(response, delimiter=",", quotechar='"')
    for row in reader:
        if row[0] == symbol:
            return row

## main ##
symbol = "TSLA"

history = pandas.io.data.DataReader(symbol, "yahoo", start="2014/1/1")
print history.tail(2)

today = datetime.date.today()
df = pandas.DataFrame(index=pandas.DatetimeIndex(start=today, end=today, freq="D"),
                      columns=["Open", "High", "Low", "Close", "Volume", "Adj Close"],
                      dtype=float)

row = get_quote_today(symbol)
df.ix[0] = map(float, row[2:])

history = history.append(df)

print "today is %s" % today
print history.tail(2)

just to complete perigee's answer, it cost me quite some time to find a way to append the data.

             Open    High     Low   Close   Volume  Adj Close
Date
2014-02-04  180.7  181.60  176.20  178.73  4686300     178.73
2014-02-05  178.3  180.59  169.36  174.42  7268000     174.42

today is 2014-02-06

              Open    High     Low    Close   Volume  Adj Close
2014-02-05  178.30  180.59  169.36  174.420  7268000    174.420
2014-02-06  176.36  180.11  176.00  178.793  5199297    178.793
like image 106
Dyno Fu Avatar answered Oct 03 '22 01:10

Dyno Fu


Find a way to work around, just use urllib to fetch the data with:

    http://download.finance.yahoo.com/d/quotes.csv?s=yhoo&f=sd1ohgl1l1v

then add it to dataframe

like image 39
perigee Avatar answered Oct 03 '22 00:10

perigee