Advertisement
Guest User

DailyData.py reformat WikiPosit output

a guest
Mar 29th, 2012
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.75 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. # dailydata.py
  4. # Reformat the daily dataset feed spot price history so that it can
  5. # be imported or copy and pasted into a spreadsheet.
  6. # The source data omits weekends and holidays.
  7. # After reformatting it, any missing days have data carried over from
  8. # the previous business day.
  9.  
  10. from datetime import datetime, timedelta
  11.  
  12. fname = "dataset.csv"
  13.  
  14. fobj = open(fname, 'r')
  15.  
  16. lastDate = None
  17. lastAmounts = None
  18.  
  19. for eachLine in fobj:
  20.     cols = eachLine.strip().rstrip(',').split(',')
  21.    
  22.     if len(cols) < 2:
  23.        # Blank probably, ingnore.
  24.        continue
  25.            
  26.     curDateStr = cols[0]
  27.        
  28.     try:
  29.        curDate = datetime.strptime(curDateStr, '%d-%b-%Y')    
  30.     except ValueError:
  31.        # Probably a header row.  Must start with date. Skip it.
  32.        continue
  33.        
  34.     # There should be just four columns (date, oil, gold, silver).
  35.     assert len(cols) == 4
  36.    
  37.     while (lastDate <> None and curDate > (lastDate + timedelta(days=1))):
  38.         # Missing a day.  Use the last amount again.
  39.         lastDate = lastDate + timedelta(days=1)
  40.        
  41.         print ("{}, {: >8},{: >8},{: >8}".format(lastDate.strftime('%d-%b-%Y'), *lastAmounts))
  42.        
  43.     curAmounts = []
  44.    
  45.     for i in range(3):
  46.         # For each of the data columns.
  47.         # [col 0 has date, so col 1 is first value column].
  48.        
  49.         if cols[i + 1] == 'na':
  50.             # Invalid data for the date.  Use previous day.
  51.             curAmounts.append(lastAmounts[i])
  52.         else:
  53.             curAmounts.append(float(cols[i + 1]))
  54.    
  55.     print ("{}, {: >8},{: >8},{: >8}".format(curDate.strftime('%d-%b-%Y'), *curAmounts))
  56.    
  57.     lastDate = curDate
  58.     lastAmounts = curAmounts
  59.    
  60. fobj.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement