Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # dailydata.py
- # Reformat the daily dataset feed spot price history so that it can
- # be imported or copy and pasted into a spreadsheet.
- # The source data omits weekends and holidays.
- # After reformatting it, any missing days have data carried over from
- # the previous business day.
- from datetime import datetime, timedelta
- fname = "dataset.csv"
- fobj = open(fname, 'r')
- lastDate = None
- lastAmounts = None
- for eachLine in fobj:
- cols = eachLine.strip().rstrip(',').split(',')
- if len(cols) < 2:
- # Blank probably, ingnore.
- continue
- curDateStr = cols[0]
- try:
- curDate = datetime.strptime(curDateStr, '%d-%b-%Y')
- except ValueError:
- # Probably a header row. Must start with date. Skip it.
- continue
- # There should be just four columns (date, oil, gold, silver).
- assert len(cols) == 4
- while (lastDate <> None and curDate > (lastDate + timedelta(days=1))):
- # Missing a day. Use the last amount again.
- lastDate = lastDate + timedelta(days=1)
- print ("{}, {: >8},{: >8},{: >8}".format(lastDate.strftime('%d-%b-%Y'), *lastAmounts))
- curAmounts = []
- for i in range(3):
- # For each of the data columns.
- # [col 0 has date, so col 1 is first value column].
- if cols[i + 1] == 'na':
- # Invalid data for the date. Use previous day.
- curAmounts.append(lastAmounts[i])
- else:
- curAmounts.append(float(cols[i + 1]))
- print ("{}, {: >8},{: >8},{: >8}".format(curDate.strftime('%d-%b-%Y'), *curAmounts))
- lastDate = curDate
- lastAmounts = curAmounts
- fobj.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement