summaryrefslogtreecommitdiff
path: root/bla.py
blob: d6fbeccc597dca38776d1f25e2819043d8d6004c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import csv
from collections import deque

class FIFOQueue:
    def __init__(self):
        self.queue = deque()

    def add(self, amount, price):
        self.queue.append((amount, price))

    def remove(self, amount):
        remaining = amount
        cost_basis = 0

        while remaining > 0:
            if not self.queue:
                raise ValueError(f"Insufficient assets in queue to process sale of {amount}.")
            quantity, price = self.queue[0]
            if quantity > remaining:
                cost_basis += remaining * price
                self.queue[0] = (quantity - remaining, price)
                remaining = 0
            else:
                cost_basis += quantity * price
                remaining -= quantity
                self.queue.popleft()

        return cost_basis

def process_ledger(file_path):
    fifo_queues = {}  # Separate FIFO queue per currency
    report = []

    with open(file_path, 'r') as file:
        reader = csv.DictReader(file)
        for row in reader:
            currency = row["asset"]
            # Use setdefault() for streamlined dictionary handling
            fifo_queues.setdefault(currency, FIFOQueue())

            if row["type"] == "trade" and row["amount"].startswith('-'):  # Sale
                amount = -float(row["amount"])
                cost_basis = fifo_queues[currency].remove(amount)
                sale_proceeds = amount * float(row["fee"])  # Adjust fee as needed
                profit_or_loss = sale_proceeds - cost_basis
                report.append((row["time"], currency, profit_or_loss))

            elif row["type"] == "trade" and not row["amount"].startswith('-'):  # Purchase
                amount = float(row["amount"])
                price = float(row["fee"])  # Adjust fee as needed
                fifo_queues[currency].add(amount, price)

    return report

# Usage
ledger_path = "kraken_ledger.csv"  # Replace with your file path
profit_and_loss_report = process_ledger(ledger_path)
for entry in profit_and_loss_report:
    print(entry)