|
| 1 | +"""Data loaders.""" |
| 2 | +from abc import abstractmethod |
| 3 | +from enum import StrEnum |
| 4 | + |
| 5 | +import pandas as pd |
| 6 | + |
| 7 | +NORMALISED_COL_NAMES_AVANZA = { |
| 8 | + "Datum": "transaction_date", |
| 9 | + "Konto": "account", |
| 10 | + "Typ av transaktion": "transaction_type", |
| 11 | + "Värdepapper/beskrivning": "name", |
| 12 | + "Antal": "no_traded", |
| 13 | + "Kurs": "price", |
| 14 | + "Belopp": "amount", |
| 15 | + "Courtage": "commission", |
| 16 | + "Valuta": "currency", |
| 17 | + "ISIN": "isin_code", |
| 18 | + "Resultat": "pnl", |
| 19 | +} |
| 20 | + |
| 21 | +NORMALISED_COL_NAMES_LYSA = { |
| 22 | + "Date": "transaction_date", |
| 23 | + "Type": "transaction_type", |
| 24 | + "Amount": "amount", |
| 25 | + "Counterpart/Fund": "name", |
| 26 | + "Volume": "no_traded", |
| 27 | + "Price": "price", |
| 28 | +} |
| 29 | + |
| 30 | +DTYPES_MAP = { |
| 31 | + "account": str, |
| 32 | + "transaction_type": str, |
| 33 | + "name": str, |
| 34 | + "no_traded": float, |
| 35 | + "price": float, |
| 36 | + "amount": float, |
| 37 | + "commission": float, |
| 38 | + "currency": str, |
| 39 | + "isin_code": str, |
| 40 | + "pnl": float, |
| 41 | +} |
| 42 | + |
| 43 | + |
| 44 | +class TransactionTypeValues(StrEnum): |
| 45 | + """Represent transaction types.""" |
| 46 | + |
| 47 | + BUY = "buy" |
| 48 | + SELL = "sell" |
| 49 | + |
| 50 | + |
| 51 | +class DataLoader: |
| 52 | + """Base data loader.""" |
| 53 | + |
| 54 | + df: pd.DataFrame | None = None |
| 55 | + |
| 56 | + def __init__(self) -> None: |
| 57 | + """Init class.""" |
| 58 | + self.load_csv() |
| 59 | + self.filter_transactions() |
| 60 | + self.ensure_dot() |
| 61 | + self.cleanup_df() |
| 62 | + self.convert_data_types() |
| 63 | + self.finalize_data_load() |
| 64 | + |
| 65 | + @abstractmethod |
| 66 | + def load_csv(self) -> None: |
| 67 | + """Load CSV.""" |
| 68 | + |
| 69 | + def filter_transactions(self) -> None: |
| 70 | + """Filter transactions.""" |
| 71 | + self.df = self.df.query( |
| 72 | + f"transaction_type == '{TransactionTypeValues.BUY}' or " |
| 73 | + f"transaction_type == '{TransactionTypeValues.SELL}'" |
| 74 | + ) |
| 75 | + |
| 76 | + def ensure_dot(self) -> None: |
| 77 | + """Make sure values have dot as decimal separator.""" |
| 78 | + df = self.df.copy() |
| 79 | + |
| 80 | + for col in ("no_traded", "price", "amount", "commission", "pnl"): |
| 81 | + if col in df.columns: |
| 82 | + df[col].replace(",", ".", regex=True, inplace=True) |
| 83 | + |
| 84 | + self.df = df |
| 85 | + |
| 86 | + def convert_data_types(self) -> None: |
| 87 | + """Convert data types.""" |
| 88 | + df = self.df.copy() |
| 89 | + for key, val in DTYPES_MAP.items(): |
| 90 | + if key in df.columns: |
| 91 | + df[key] = df[key].astype(val) |
| 92 | + |
| 93 | + self.df = df |
| 94 | + |
| 95 | + def cleanup_df(self) -> None: |
| 96 | + """Cleanup dataframe.""" |
| 97 | + df = self.df.copy() |
| 98 | + |
| 99 | + for col in ("commission", "pnl", "isin_code"): # Replace dashes with 0 |
| 100 | + if col in df.columns: |
| 101 | + try: |
| 102 | + df[col] = df[col].str.replace("-", "").replace("", 0) |
| 103 | + except AttributeError: |
| 104 | + pass |
| 105 | + |
| 106 | + self.df = df |
| 107 | + |
| 108 | + def finalize_data_load(self) -> None: |
| 109 | + """Post-process.""" |
| 110 | + df = self.df.copy() |
| 111 | + df["amount"] = abs(df["amount"]) |
| 112 | + |
| 113 | + self.df = df |
| 114 | + |
| 115 | + |
| 116 | +class LysaLoader(DataLoader): |
| 117 | + """Data loader for Lysa.""" |
| 118 | + |
| 119 | + def load_csv(self) -> None: |
| 120 | + """Load CSV.""" |
| 121 | + files = ["data/lysa-a.csv", "data/lysa-b.csv"] |
| 122 | + dfs = [pd.read_csv(file, sep=",") for file in files] |
| 123 | + df = pd.concat(dfs, ignore_index=True) |
| 124 | + |
| 125 | + df = df.rename(columns=NORMALISED_COL_NAMES_LYSA) |
| 126 | + df.set_index("transaction_date", inplace=True) |
| 127 | + |
| 128 | + df = df.applymap(lambda x: x.strip() if isinstance(x, str) else x) |
| 129 | + |
| 130 | + # Replace buy |
| 131 | + for event in ("Switch buy", "Buy"): |
| 132 | + df["transaction_type"] = df["transaction_type"].replace( |
| 133 | + event, TransactionTypeValues.BUY.value |
| 134 | + ) |
| 135 | + |
| 136 | + # Replace sell |
| 137 | + for event in ("Switch sell", "Sell"): |
| 138 | + df["transaction_type"] = df["transaction_type"].replace( |
| 139 | + event, TransactionTypeValues.SELL.value |
| 140 | + ) |
| 141 | + |
| 142 | + df["commission"] = 0.0 |
| 143 | + |
| 144 | + self.df = df |
| 145 | + |
| 146 | + |
| 147 | +class AvanzaLoader(DataLoader): |
| 148 | + """Data loader for Avanza.""" |
| 149 | + |
| 150 | + def load_csv(self) -> None: |
| 151 | + """Load CSV.""" |
| 152 | + df = pd.read_csv("data/avanza.csv", sep=";") |
| 153 | + df = df.rename(columns=NORMALISED_COL_NAMES_AVANZA) |
| 154 | + df.set_index("transaction_date", inplace=True) |
| 155 | + |
| 156 | + # Replace buy |
| 157 | + for event in ("Köp",): |
| 158 | + df["transaction_type"] = df["transaction_type"].replace( |
| 159 | + event, TransactionTypeValues.BUY.value |
| 160 | + ) |
| 161 | + |
| 162 | + # Replace sell |
| 163 | + for event in ("Sälj",): |
| 164 | + df["transaction_type"] = df["transaction_type"].replace( |
| 165 | + event, TransactionTypeValues.SELL.value |
| 166 | + ) |
| 167 | + |
| 168 | + self.df = df |
| 169 | + |
| 170 | + |
| 171 | +class MiscLoader(DataLoader): |
| 172 | + """Data loader for misc data.""" |
| 173 | + |
| 174 | + def load_csv(self) -> None: |
| 175 | + """Load CSV.""" |
| 176 | + df = pd.read_csv("data/other-a.csv", sep=";") |
| 177 | + df.set_index("transaction_date", inplace=True) |
| 178 | + |
| 179 | + for field in ["commission", "amount"]: |
| 180 | + df[field] = df[field].str.replace(",", "") |
| 181 | + |
| 182 | + self.df = df |
0 commit comments