"""The year report of docs/spec.md section 6. Figures only: no presentation logic and no currency formatting. Every amount is integer ore, every BTC quantity is integer sats. """ import database import ledger import rates # The events of docs/spec.md section 3.1: a trade where BTC leaves the account, # a spend, and a loss. REALIZING_TYPES = ("trade", "spend", "loss") SATS_PER_BTC = rates.SATS_PER_BTC def _round_div(value, divisor): """Divide two integers, rounding halves up.""" if not divisor: return 0 return (2 * value + divisor) // (2 * divisor) def _tenths_percent(part, whole): """A percentage in tenths, or 0 when there is nothing to divide by.""" if not whole: return 0 return _round_div(part * 1000, whole) def _year_rows(conn, year): """The year's transactions with the cost basis each one consumed.""" return conn.execute( "SELECT t.id, t.market_id, t.type, t.taxable, t.leg_in_ore, t.leg_out_ore," " t.leg_out_sats, t.value_ore, t.fee_ore," " COALESCE(SUM(c.cost_ore), 0) AS cost_ore" " FROM transactions t LEFT JOIN lot_consumptions c ON c.tx_id = t.id" " WHERE t.date >= ? AND t.date <= ?" " GROUP BY t.id ORDER BY t.date, t.id", ("%04d-01-01" % year, "%04d-12-31" % year), ).fetchall() def _settings(conn): rows = conn.execute("SELECT key, value FROM settings").fetchall() return {row["key"]: row["value"] for row in rows} # The types that carry both a kroner amount and a sats amount, and so have a # bitcoin price (docs/spec.md section 7.3). The rest give None. PRICE_TYPES = ("trade", "income", "spend", "loss", "gift_received") def btc_price_ore(tx): """The bitcoin price of docs/spec.md section 7.3, in ore per whole BTC. The kroner amount is the leg that carries it, or `value_ore` where no leg does; the fee is left out. Returns None when the type has no price. """ tx_type = tx["type"] if tx_type not in PRICE_TYPES: return None if tx_type in ("income", "gift_received"): nok_ore = tx["value_ore"] sats = tx["leg_in_sats"] elif tx_type in ("spend", "loss"): nok_ore = tx["value_ore"] sats = tx["leg_out_sats"] else: nok_ore = tx["leg_out_ore"] if nok_ore is None: nok_ore = tx["leg_in_ore"] sats = tx["leg_in_sats"] if sats is None: sats = tx["leg_out_sats"] if not nok_ore or not sats: return None return _round_div(nok_ore * SATS_PER_BTC, sats) def report(year, conn=None): """Return the year report: per-account rows, totals, tax and reconciliation.""" year = int(year) own = conn is None if own: conn = database.connect() try: settings = _settings(conn) method = settings.get("lot_method", "FIFO") tax_rate = int(settings.get("tax_rate_percent", "22")) wealth_enabled = settings.get("wealth_tax_enabled", "0") == "1" wealth_threshold = int(settings.get("wealth_tax_threshold_ore", "0")) wealth_rate = int(settings.get("wealth_tax_rate_percent", "0")) deduct_admin = settings.get("deduct_admin_costs", "0") == "1" end_date = "%04d-12-31" % year price = rates.get_rate(year, conn) price_row = conn.execute( "SELECT source FROM prices WHERE asset = 'BTC' AND date = ?", (rates.year_end_date(year),), ).fetchone() source = price_row["source"] if price_row else settings.get( "year_end_price_source", "" ) markets = [dict(row) for row in conn.execute( "SELECT id, name, taxable, custody_market_id, sort_order FROM markets" " ORDER BY sort_order, name" ).fetchall()] by_id = {market["id"]: market for market in markets} holdings = ledger.holdings_at(end_date, conn) figures = { market["id"]: {"gevinst_ore": 0, "tap_ore": 0, "brukt_ore": 0} for market in markets } income_ore = 0 admin_cost_ore = 0 for row in _year_rows(conn, year): market = by_id.get(row["market_id"]) if market is None: continue # A transaction counts towards the totals only when its account is # taxable and the transaction itself is ticked as taxable. A # non-taxable account keeps its own figures for information only, # and never enters a total. counted = bool(market["taxable"]) and bool(row["taxable"]) informational = counted or not market["taxable"] if row["type"] == "income": value = (row["value_ore"] or 0) - (row["fee_ore"] or 0) if counted: income_ore += value elif row["type"] == "admin_cost": value = row["leg_out_ore"] or row["cost_ore"] if counted: admin_cost_ore += value elif ( row["type"] in REALIZING_TYPES and row["leg_out_sats"] and informational ): if row["type"] == "loss": proceeds = 0 elif row["type"] == "spend": proceeds = (row["value_ore"] or 0) - (row["fee_ore"] or 0) else: proceeds = (row["leg_in_ore"] or 0) - (row["fee_ore"] or 0) cost_ore = row["cost_ore"] figure = figures[row["market_id"]] figure["brukt_ore"] += cost_ore gain = proceeds - cost_ore if gain >= 0: figure["gevinst_ore"] += gain else: figure["tap_ore"] += -gain taxable_markets = [market for market in markets if market["taxable"]] total_sats = sum(holdings.get(market["id"], 0) for market in taxable_markets) accounts = [] for market in taxable_markets: sats = holdings.get(market["id"], 0) figure = figures[market["id"]] accounts.append({ "market_id": market["id"], "name": market["name"], "sats": sats, "share_percent": _tenths_percent(sats, total_sats) / 10, "formue_ore": _round_div(sats * price, SATS_PER_BTC) if price else 0, "gevinst_ore": figure["gevinst_ore"], "tap_ore": figure["tap_ore"], "brukt_ore": figure["brukt_ore"], "gevinst_percent": _tenths_percent(figure["gevinst_ore"], figure["brukt_ore"]) / 10, }) formue_ore = sum(account["formue_ore"] for account in accounts) gevinst_ore = sum(account["gevinst_ore"] for account in accounts) tap_ore = sum(account["tap_ore"] for account in accounts) brukt_ore = sum(account["brukt_ore"] for account in accounts) netto_ore = gevinst_ore - tap_ore - (admin_cost_ore if deduct_admin else 0) skatt_ore = _round_div(max(netto_ore, 0) * tax_rate, 100) if wealth_enabled: formuesskatt_ore = _round_div( max(formue_ore - wealth_threshold, 0) * wealth_rate, 100 ) else: formuesskatt_ore = 0 non_taxable = [ { "market_id": market["id"], "name": market["name"], "sats": holdings.get(market["id"], 0), "gevinst_ore": figures[market["id"]]["gevinst_ore"], "tap_ore": figures[market["id"]]["tap_ore"], } for market in markets if not market["taxable"] ] dependants = {} for market in markets: custodian = market["custody_market_id"] if custodian: dependants.setdefault(custodian, []).append(market["id"]) custody_totals = [ { "market_id": market["id"], "name": market["name"], "sats": holdings.get(market["id"], 0) + sum(holdings.get(other, 0) for other in dependants[market["id"]]), } for market in markets if market["id"] in dependants ] return { "year": year, "year_end_price_ore": price, "year_end_price_source": source, "accounts": accounts, "totals": { "formue_ore": formue_ore, "gevinst_ore": gevinst_ore, "tap_ore": tap_ore, "brukt_ore": brukt_ore, "netto_ore": netto_ore, "inntekt_ore": income_ore, "skatt_ore": skatt_ore, "formuesskatt_ore": formuesskatt_ore, "admin_cost_ore": admin_cost_ore, "lot_method": method, }, "non_taxable": non_taxable, "custody_totals": custody_totals, "skattemelding": { "formue": formue_ore, "gevinst": gevinst_ore, "tap": tap_ore, "inntekt": income_ore, "accounts": [account["name"] for account in accounts], "note": "Berre skattepliktige kontoar er med. Kontoar du fører for " "andre er haldne utanfor.", }, } finally: if own: conn.close()