|
import csv |
|
|
|
shares = {} # Per share/scrip info |
|
holding = {} # Held share |
|
bought = {} # Purshased shares to date |
|
sold = {} # Sold shares to date |
|
|
|
with open('tradebook.csv') as csvfile: |
|
for row in csv.reader(csvfile): |
|
scrip, nos, price, date = row[0], float(row[7]), float(row[8]), row[2] |
|
cost = nos*price |
|
try: |
|
share = shares[scrip] |
|
share[0].append((nos, price)) |
|
share[1] += cost |
|
if nos < 0: |
|
try: |
|
sold[scrip].append([nos, price, date]) |
|
except: |
|
sold[scrip] = [[nos, price, date]] |
|
while nos < 0: |
|
nos = holding[scrip][0][0] + nos |
|
if nos > 0: |
|
holding[scrip][0][0] = nos |
|
else: |
|
holding[scrip].pop(0) |
|
else: |
|
holding[scrip].append([nos, price, date]) |
|
bought[scrip].append([nos, price, date]) |
|
except: |
|
print("couldn't find: ", scrip) |
|
shares[scrip] = [[(nos, price, date)], cost] |
|
holding[scrip] = [[nos, price, date]] |
|
bought[scrip] = [[nos, price, date]] |
|
|
|
print(bought, sold, holding, sep="\n") |
|
|
|
def compute(shares, scrip): |
|
try: |
|
orders = shares[scrip] |
|
except: |
|
orders = [] |
|
return [sum([ord[0] for ord in orders]), sum([ord[0]*ord[1] for ord in orders])] |
|
|
|
with open('computed.csv', 'w') as csvfile: |
|
writer = csv.writer(csvfile) |
|
writer.writerow(['SCRIP', 'PERCEIVED COST', 'HELD','CURR INVESTMENT', 'ENTERED', 'AVG ENTRY COST', 'EXITED','AVG EXIT COST', 'ORDERS']) |
|
for scrip in sorted(shares.keys()): |
|
row = [scrip] |
|
share = shares[scrip] |
|
print(row, share) |
|
row.append(share[1]) |
|
row.extend(compute(holding, scrip)) |
|
row.extend(compute(bought, scrip)) |
|
row.extend(compute(sold, scrip)) |
|
for ord in share[0]: |
|
row.extend(ord) |
|
writer.writerow(row) |
|
|
|
with open('bought.csv', 'w') as csvfile: |
|
writer = csv.writer(csvfile) |
|
writer.writerow(['SCRIP', 'SHARES PURCHASED:']) |
|
for share in sorted(bought.keys()): |
|
row = [share] |
|
for pur in bought[share]: |
|
row.extend(pur) |
|
writer.writerow(row) |
|
|
|
with open('sold.csv', 'w') as csvfile: |
|
writer = csv.writer(csvfile) |
|
writer.writerow(['SCRIP', 'SHARES SOLD:']) |
|
for share in sorted(sold.keys()): |
|
row = [share] |
|
for sale in sold[share]: |
|
row.extend(sale) |
|
writer.writerow(row) |
|
|
|
with open('holding.csv', 'w') as csvfile: |
|
writer = csv.writer(csvfile) |
|
writer.writerow(['SCRIP', 'SHARES HELD:']) |
|
for share in sorted(holding.keys()): |
|
row = [share] |
|
for pur in holding[share]: |
|
row.extend(pur) |
|
writer.writerow(row) |