Created
September 10, 2020 16:14
-
-
Save demosdemon/689499260273fd5265e58e2a52c7515d to your computer and use it in GitHub Desktop.
Convert Betterment Cost Basis report into a format importable by Yahoo Finance Portfolios.
This file contains hidden or 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 sys | |
import argparse | |
import csv | |
import operator | |
import logging | |
import datetime | |
def get_trade_date(record): | |
purchase_date = record["PurchaseDate"] | |
purchase_date = datetime.datetime.strptime(purchase_date, "%m/%d/%Y").date() | |
return purchase_date.strftime("%Y%m%d") | |
def get_purchase_price(record): | |
cost_basis = float(record["CostBasis"]) | |
shares = float(record["Shares"]) | |
price = cost_basis / shares | |
return f"{price:.2f}" | |
FIELDS = ( | |
( | |
"Symbol", | |
operator.itemgetter("Symbol"), | |
), | |
( | |
"Trade Date", | |
get_trade_date, | |
), | |
( | |
"Purchase Price", | |
get_purchase_price, | |
), | |
( | |
"Quantity", | |
operator.itemgetter("Shares"), | |
), | |
( | |
"Comment", | |
lambda _: "Imported from Betterment.", | |
), | |
) | |
def map_record(record): | |
return {key: value(record) for (key, value) in FIELDS} | |
def read_input(path): | |
if path == "-": | |
fp = sys.stdin | |
if fp.isatty(): | |
logging.warning("reading from terminal") | |
else: | |
fp = open(path, "r") | |
reader = csv.DictReader(fp) | |
with fp: | |
yield from reader | |
def write_output(path, data): | |
if path == "-": | |
fp = sys.stdout | |
else: | |
fp = open(path, "w") | |
keys = list(map(operator.itemgetter(0), FIELDS)) | |
writer = csv.DictWriter(fp, keys) | |
with fp: | |
writer.writeheader() | |
writer.writerows(data) | |
def main(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument("input") | |
parser.add_argument("output") | |
args = parser.parse_args() | |
data = read_input(args.input) | |
data = map(map_record, data) | |
data = sorted( | |
data, | |
key=lambda record: ( | |
record["Trade Date"], | |
record["Symbol"], | |
record["Quantity"], | |
), | |
) | |
write_output(args.output, data) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment