82 lines
3.1 KiB
Python
82 lines
3.1 KiB
Python
#!/usr/bin/env python3
|
||
import csv, json, argparse, sys
|
||
from collections import defaultdict
|
||
from datetime import datetime
|
||
|
||
def read_csv(path):
|
||
with open(path, newline='') as f:
|
||
return list(csv.DictReader(f))
|
||
|
||
def date_in_range(ts, start, end):
|
||
# ts is like '2024-06-15 12:34:56+00'
|
||
d = datetime.fromisoformat(ts).date()
|
||
return start <= d <= end
|
||
|
||
def main():
|
||
p = argparse.ArgumentParser()
|
||
p.add_argument('--trades', required=True)
|
||
p.add_argument('--positions', required=True)
|
||
p.add_argument('--user-id', type=int, required=True)
|
||
p.add_argument('--start-date', required=True)
|
||
p.add_argument('--end-date', required=True)
|
||
p.add_argument('--output', required=True)
|
||
args = p.parse_args()
|
||
|
||
# ------------------------------------------------------------------
|
||
# Load trades, filter by date and event_type
|
||
# ------------------------------------------------------------------
|
||
trades = []
|
||
with open(args.trades) as f:
|
||
for row in csv.DictReader(f):
|
||
if row['event_type'] != 'fill':
|
||
continue
|
||
if not (args.start_date <= row['exec_timestamp'].split(' ')[0] <= args.end_date):
|
||
continue
|
||
trades.append(row)
|
||
|
||
total_fills = len(trades)
|
||
|
||
# total_pnl – only completed trades
|
||
total_pnl = sum(float(r['net_pnl']) for r in trades if r['completed_trade_id'])
|
||
|
||
# symbol_quantities (net qty per symbol)
|
||
symbol_qty = defaultdict(int)
|
||
for r in trades:
|
||
symbol_qty[r['symbol']] += int(r['qty']) # qty is already signed (+ for BUY, - for SELL)
|
||
|
||
# ------------------------------------------------------------------
|
||
# Position mismatch check
|
||
# ------------------------------------------------------------------
|
||
# Build a map: symbol → net_qty from positions for this user
|
||
pos_by_symbol = defaultdict(int)
|
||
with open(args.positions) as f:
|
||
reader = csv.DictReader(f)
|
||
for row in reader:
|
||
if int(row['user_id']) != args.user_id:
|
||
continue
|
||
pos_by_symbol[row['symbol']] += int(row['net_qty'])
|
||
|
||
mismatches = []
|
||
for symbol, trade_total in symbol_qty.items():
|
||
pos_total = pos_by_symbol.get(symbol, 0)
|
||
if abs(trade_total - pos_total) > 1:
|
||
mismatches.append(symbol)
|
||
|
||
# ------------------------------------------------------------------
|
||
# Assemble the final JSON
|
||
# ------------------------------------------------------------------
|
||
report = {
|
||
"user_id": args.user_id,
|
||
"date_range_start": args.start_date,
|
||
"date_range_end": args.end_date,
|
||
"total_fills": total_fills,
|
||
"total_pnl": round(total_pnl, 2),
|
||
"symbol_quantities": dict(symbol_qty),
|
||
"position_mismatches": mismatches
|
||
}
|
||
|
||
with open(args.output, 'w') as f:
|
||
json.dump(report, f, indent=2)
|
||
|
||
if __name__ == '__main__':
|
||
main() |