-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathcsv_loader.py
More file actions
76 lines (67 loc) · 2.83 KB
/
Copy pathcsv_loader.py
File metadata and controls
76 lines (67 loc) · 2.83 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
from typing import List, Optional
import pendulum
from loguru import logger
from pit38.data_sources.csv_utils import open_csv_reader
from pit38.domain.transactions import Transaction, AssetValue, Action
from pit38.domain.currency_exchange_service.currencies import parse_currency, FiatValue, Currency, InvalidCurrencyException
class Loader:
@classmethod
def load(cls, file_path: str) -> List[Transaction]:
transactions = []
logger.info(f"Loading transactions from {file_path}...")
with open_csv_reader(file_path) as reader:
for row in reader:
transaction = cls._parse_row(row)
if transaction:
logger.debug(f"Parsed transaction: {transaction}")
transactions.append(transaction)
logger.info(f"Loaded {len(transactions)} transactions")
return transactions
@classmethod
def _parse_row(cls, row: dict) -> Optional[Transaction]:
try:
transaction = Transaction(
asset=cls._asset_value(row),
fiat_value=cls._fiat_value(row),
action=cls._action(row),
date=cls._datetime(row)
)
return transaction
except (ValueError, KeyError) as e:
logger.warning(f"Skipping invalid row: {row}. Error: {str(e)}")
return None
@classmethod
def _asset_value(cls, row: dict) -> AssetValue:
try:
amount = float(row["amount"])
symbol = row["symbol"]
if not symbol:
raise ValueError("Cryptocurrency symbol cannot be empty")
return AssetValue(amount, symbol)
except (ValueError, KeyError) as e:
raise ValueError(f"Failed to parse cryptocurrency value: {str(e)}")
@classmethod
def _fiat_value(cls, row: dict) -> FiatValue:
try:
amount = float(row["fiat_value"])
currency = parse_currency(row["currency"])
return FiatValue(amount, currency)
except (ValueError, KeyError) as e:
raise ValueError(f"Failed to parse fiat value: {str(e)}")
except InvalidCurrencyException as e:
raise ValueError(f"Failed to parse currency: {str(e)}")
@classmethod
def _action(cls, row: dict) -> Action:
try:
action = row["operation"]
if action not in Action.available_actions():
raise ValueError(f"Unknown operation: {action}")
return Action[action]
except (KeyError, ValueError) as e:
raise ValueError(f"Failed to parse operation type: {str(e)}")
@classmethod
def _datetime(cls, row: dict) -> pendulum.DateTime:
try:
return pendulum.parse(row["date"])
except (ValueError, KeyError) as e:
raise ValueError(f"Failed to parse date: {str(e)}")