How To: Python Pandas get current stock data

perigee picture perigee · Jun 3, 2013 · Viewed 19.9k times · Source

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.

Answer

Dyno Fu picture Dyno Fu · Feb 6, 2014
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