Created
December 20, 2016 00:27
-
-
Save jmitchell/e863296b22eb0bd2566428f10ca04a39 to your computer and use it in GitHub Desktop.
Script to convert Dow Jones index CSV from Yahoo into prices over Q4 during presdential election years
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import csv | |
from collections import namedtuple | |
PriceRecord = namedtuple("PriceRecord", "date open high low close volume adjusted_close") | |
def parse_date(ymd): | |
return map(int, ymd.split('-')) | |
def fiscal_quarter(r): | |
year, month, _ = r.date | |
q = ((month-1) / 3) + 1 | |
return (q, year) | |
def from_quarter(rs, q, y): | |
for r in rs: | |
quarter, year = fiscal_quarter(r) | |
if quarter == q and year == y: | |
yield r | |
def by_pres_election_quarters(rs): | |
q = 4 | |
years = range(1988, 2017, 4) | |
doy = {} | |
for y in years: | |
for r in from_quarter(rs, q, y): | |
_, m, d = r.date | |
k = (m, d) | |
if not doy.has_key(k): | |
doy[k] = {} | |
doy[k][y] = r | |
print "Day of year,%s" % (','.join(map(str, years))) | |
for d,ys in doy.iteritems(): | |
row = [] | |
for y in years: | |
r = ys.get(y) | |
if r == None: | |
row.append('') | |
else: | |
row.append(r.high) | |
month, day = d | |
print "%s-%s,%s" % (month, day, ','.join(row)) | |
# assumes CSV has no header and rows are in ascending chronological order | |
with open('dji_prices.csv', 'rb') as f: | |
dji = csv.reader(f) | |
records = [] | |
for row in dji: | |
row[0] = parse_date(row[0]) | |
records.append(PriceRecord._make(row)) | |
by_pres_election_quarters(records) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment