Ok, I'm stumped ccc. Since python dates use a 1-based month, (January is 1), the above will result in the variable month==0, which is how yahoo wants the data (yahoo uses 0 based month, yet 1 based day for whatever reason).
Manually creating a date object in January and using the above code works fine.
There is one bug and one quirk that I see:
The bug happens st the stroke of midnight on 12/31, in which case the first call to today, to get the month, will return December, but the next call to today, to get the year, will return next year. Thus you won't pull any data (yahoo will return html rather than csv when the dates are in the future)
The quirk is that techteejs proposal of pulling data from the start of the current month is not how most people look at stock data.... Last 30 days, sure, but on the first of the month you might not pull any data if the market is not open( for example, market is always closed on January first, so of you ran the script on January first, yahoo would return a file not found error html)
Here's a version that pulls last 30 days, and only calls today() once.
from datetime import datetime, date, timedelta
import urllib
enddate = date.today()
startdate = enddate + timedelta(-30)
STOCK_URL = 'http://ichart.finance.yahoo.com/table.csv'
PARAMS = {
'a': startdate.month-1,
'b': startdate.day,
'c': startdate.year,
'd': enddate.month-1,
'e': enddate.day,
'f': enddate.year,
'g': 'd',
'ignore': '.csv'
}
def pulldata(stock, filename):
params = PARAMS.copy()
params['s'] = stock
url = "%s?%s" % (STOCK_URL, urllib.urlencode(params))
return urllib.urlretrieve(url, filename)
filename, headers = pulldata("^RUT", "RUT-data.csv")