Output:
Chunk ID: ee7ec6
Wall time: 0.0001 seconds
Process exited with code 0
Original token count: 3658
Output:
                )
                price_writes += 1
            quotes[(position.account_id, position.instrument_id)] = (position, quote, quote_as_of, mapping)

        currencies = sorted({quote.currency.upper() for _, quote, _, _ in quotes.values()})
        rates: dict[str, Decimal] = {}
        rate_dates: dict[str, date] = {}
        fx = fx_provider or FrankfurterFxProvider()
        fx_writes = 0
        for currency in currencies:
            provider_name = "identity" if currency == "CHF" else getattr(fx, "name", "fx_provider")
            rate, rate_as_of = _fetch_fx_rate(fx, currency, effective)
            if rate is None or rate_as_of is None:
                reasons.add("fx_rate_missing")
                continue
            rates[currency] = rate
            rate_dates[currency] = rate_as_of
            rate_age = _business_day_age(rate_as_of, effective)
            rate_quality = "fresh" if 0 <= rate_age <= 2 else "stale"
            if rate_quality == "stale":
                reasons.add("stale_fx")
            existing_rate = conn.execute(
                """SELECT rate FROM fx_rates
                    WHERE base_currency=? AND quote_currency='CHF' AND rate_date=?
                      AND provider=? AND rate_type='close'""",
                (currency, rate_as_of.isoformat(), provider_name),
            ).fetchone()
            if not existing_rate or _decimal(existing_rate["rate"]) != rate:
                upsert_fx_rate(
                    conn, base_currency=currency, quote_currency="CHF", rate_date=rate_as_of.isoformat(),
                    rate=rate, provider=provider_name, rate_type="close", quality_status=rate_quality,
                    fetched_at=now, run_id=run_id,
                )
                fx_writes += 1
        conn.commit()

        values: list[dict[str, Any]] = []
        account_values: dict[str, Decimal] = defaultdict(lambda: ZERO)
        account_missing: set[str] = set()
        for (_, instrument_id), (position, quote, quote_as_of, _) in quotes.items():
            rate = rates.get(quote.currency.upper())
            close = quote.close
            if rate is None or close is None:
                missing.append({"instrument_id": instrument_id, "reason_code": "fx_rate_missing"})
                account_missing.add(position.account_id)
                continue
            value_original = position.quantity * close
            value_chf = value_original * rate
            account_values[position.account_id] += value_chf
            values.append({
                "account_id": position.account_id, "instrument_id": instrument_id, "isin": position.isin,
                "name": position.name, "asset_class": position.asset_class,
                "currency": quote.currency.upper(), "quantity": _fmt(position.quantity),
                "close": _fmt(close), "fx_rate_to_chf": _fmt(rate), "value_chf": _fmt(value_chf),
                "as_of": quote_as_of.isoformat(), "quality_status": "fresh" if 0 <= _business_day_age(quote_as_of, effective) <= 2 else "stale",
                "provider": quote.provider, "provider_symbol": quote.provider_symbol,
                "provider_market": quote.provider_market,
                **({"price_input_provenance": cached_price_inputs[instrument_id]} if instrument_id in cached_price_inputs else {}),
            })
        missing_ids = {item["instrument_id"] for item in missing}
        for position in positions:
            if position.instrument_id in missing_ids:
                account_missing.add(position.account_id)
        for account_id, amount in _latest_cash_by_account(conn).items():
            account_values[account_id] += amount
        for item in missing:
            position = position_details.get(item["instrument_id"])
            if position:
                item["label"] = position.name
                item["isin"] = position.isin or ""

        valuation_stored = 0
        for item in values:
            version = int(conn.execute(
                "SELECT COALESCE(MAX(snapshot_version),0)+1 FROM portfolio_valuation_snapshots WHERE scope_kind='instrument' AND scope_id=? AND valuation_at=?",
                (item["instrument_id"], effective.isoformat()),
            ).fetchone()[0])
            value_original = _decimal(item["quantity"]) * _decimal(item["close"])
            is_stale = item["quality_status"] == "stale"
            conn.execute(
                """INSERT OR REPLACE INTO portfolio_valuation_snapshots(
                    snapshot_id,scope_kind,scope_id,account_id,value_original,currency,base_currency,
                    fx_rate_to_base,fx_direction,valuation_at,source,captured_at,snapshot_version,
                    source_reference,quality_status,reason_codes_json)
                    VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
                (stable_id("instrument-valuation", run_id, item["account_id"], item["instrument_id"]),
                 "instrument", item["instrument_id"], item["account_id"], _fmt(value_original), item["currency"],
                 "CHF", item["fx_rate_to_chf"], "original_to_base", effective.isoformat(), SOURCE_KEY,
                 now, version, run_id, "partial" if is_stale else "complete",
                 json.dumps(["stale_price"] if is_stale else [])),
            )
            valuation_stored += 1
        for account_id, total in sorted(account_values.items()):
            version = int(conn.execute(
                "SELECT COALESCE(MAX(snapshot_version),0)+1 FROM portfolio_valuation_snapshots WHERE scope_kind='account' AND scope_id=? AND valuation_at=?",
                (account_id, effective.isoformat()),
            ).fetchone()[0])
            conn.execute(
                """INSERT OR REPLACE INTO portfolio_valuation_snapshots(
                    snapshot_id,scope_kind,scope_id,account_id,value_original,currency,base_currency,
                    fx_rate_to_base,fx_direction,valuation_at,source,captured_at,snapshot_version,
                    source_reference,quality_status,reason_codes_json)
                    VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
                (stable_id("portfolio-valuation", run_id, account_id), "account", account_id, account_id,
                 _fmt(total), "CHF", "CHF", "1", "original_to_base", effective.isoformat(), SOURCE_KEY,
                 now, version, run_id, "partial" if account_id in account_missing else "complete",
                 json.dumps(["missing_instrument"] if account_id in account_missing else [])),
            )
            valuation_stored += 1

        benchmark_mapping, benchmark_issue = _benchmark_mapping(conn, policy)
        benchmark_total = 1 if policy and policy.get("benchmarks") else 0
        benchmark_stored = 0
        if benchmark_issue:
            reasons.add(benchmark_issue)
        elif benchmark_mapping and policy:
            try:
                provider = providers.get(benchmark_mapping["provider"]) or equity_price_provider_by_name(benchmark_mapping["provider"])
                quote = provider.get_price(benchmark_mapping["provider_symbol"], price_date=effective.isoformat())
            except Exception:
                quote = None
            benchmark_quote_date = _quote_date(quote, effective) if quote else effective
            expected_benchmark_currency = str(benchmark_mapping["currency"] or "").upper()
            if quote and benchmark_quote_date > effective:
                reasons.add("benchmark_future_price")
                quote = None
            elif quote and _business_day_age(benchmark_quote_date, effective) > 2:
                reasons.add("benchmark_stale_price")
                quote = None
            elif quote and expected_benchmark_currency and str(quote.currency or "").upper() != expected_benchmark_currency:
                reasons.add("benchmark_currency_mismatch")
                quote = None
            elif quote and not exchange_matches(str(benchmark_mapping["provider_market"] or ""), quote.provider_market):
                reasons.add("benchmark_exchange_mismatch")
                quote = None
            if not quote or quote.close is None or quote.close <= ZERO:
                reasons.add("benchmark_quote_missing")
            elif quote.currency.upper() not in rates:
                benchmark_currency = quote.currency.upper()
                try:
                    benchmark_rate, benchmark_rate_as_of = _fetch_fx_rate(fx, benchmark_currency, effective)
                except Exception:
                    benchmark_rate = None
                    benchmark_rate_as_of = None
                if benchmark_rate is None or benchmark_rate_as_of is None:
                    reasons.add("benchmark_fx_missing")
                else:
                    rates[benchmark_currency] = benchmark_rate
                    rate_dates[benchmark_currency] = benchmark_rate_as_of
                    if benchmark_currency not in currencies:
                        currencies.append(benchmark_currency)
                    existing_benchmark_rate = conn.execute(
                        """SELECT rate FROM fx_rates
                            WHERE base_currency=? AND quote_currency='CHF' AND rate_date=?
                              AND provider=? AND rate_type='close'""",
                        (
                            benchmark_currency,
                            benchmark_rate_as_of.isoformat(),
                            "identity" if benchmark_currency == "CHF" else getattr(fx, "name", "fx_provider"),
                        ),
                    ).fetchone()
                    if not existing_benchmark_rate or _decimal(existing_benchmark_rate["rate"]) != benchmark_rate:
                        upsert_fx_rate(
                            conn, base_currency=benchmark_currency, quote_currency="CHF", rate_date=benchmark_rate_as_of.isoformat(),
                            rate=benchmark_rate, provider="identity" if benchmark_currency == "CHF" else getattr(fx, "name", "fx_provider"),
                            rate_type="close", quality_status="fresh", fetched_at=now, run_id=run_id,
                        )
                        fx_writes += 1
            if quote and quote.close is not None and quote.close > ZERO and quote.currency.upper() in rates:
                return_type = "etf_proxy" if benchmark_mapping["asset_class"] == "etf" else ("total_return" if quote.adjusted_close is not None else "price_return")
                if return_type == "total_return":
                    assert quote.adjusted_close is not None
                    benchmark_level = quote.adjusted_close
                else:
                    benchmark_level = quote.close
                benchmark_value = benchmark_level * rates[quote.currency.upper()]
                conn.execute(
                    """INSERT OR REPLACE INTO benchmark_snapshots(
                        benchmark_snapshot_id,run_id,policy_id,benchmark_reference,provider,provider_symbol,
                        price_currency,close,adjusted_close,fx_rate_to_chf,value_chf,return_type,as_of,source_as_of,fetched_at,
                        quality_status,reason_codes_json) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
                    (stable_id("benchmark", run_id, policy["policy_id"], benchmark_mapping["reference"]), run_id,
                     policy["policy_id"], benchmark_mapping["reference"], quote.provider,
                     benchmark_mapping["provider_symbol"], quote.currency.upper(), _fmt(quote.close),
                     _fmt(quote.adjusted_close), _fmt(rates[quote.currency.upper()]), _fmt(benchmark_value),
                     return_type, effective.isoformat(), benchmark_quote_date.isoformat(), now, "fresh", "[]"),
                )
                benchmark_stored = 1

        price_total = len(positions)
        price_stored = price_writes
        fx_total = len(currencies)
        fx_stored = fx_writes
        current_prices = sum(1 for _, _, quote_as_of, _ in quotes.values() if 0 <= _business_day_age(quote_as_of, effective) <= 2)
        price_coverage = _pct(current_prices, price_total)
        fx_covered_positions = sum(
            1 for _, quote, _, _ in quotes.values()
            if quote.currency.upper() in rates and 0 <= _business_day_age(rate_dates[quote.currency.upper()], effective) <= 2
        )
        fx_coverage = _pct(fx_covered_positions, price_total)
        benchmark_coverage = _pct(benchmark_stored, benchmark_total) if benchmark_total else ZERO
        if price_total == 0:
            quality = "unavailable"
            reasons.add("no_confirmed_positions")
        elif price_coverage == HUNDRED and fx_coverage == HUNDRED and (benchmark_total == 0 or benchmark_coverage == HUNDRED):
            quality = "complete"
        else:
            quality = "partial"
        risk = _risk_summary(conn, values, account_values, missing)
        analysis_id = stable_id("portfolio-analysis", run_id)
        conn.execute(
            """INSERT OR REPLACE INTO portfolio_analysis_snapshots(
                analysis_snapshot_id,run_id,as_of,base_currency,total_value_chf,price_coverage_pct,
                fx_coverage_pct,benchmark_coverage_pct,quality_status,reason_codes_json,summary_json,created_at)
                VALUES(?,?,?,?,?,?,?,?,?,?,?,?)""",
            (analysis_id, run_id, effective.isoformat(), "CHF", _fmt(sum(account_values.values(), ZERO)),
             _fmt(price_coverage), _fmt(fx_coverage), _fmt(benchmark_coverage), quality,
             json.dumps(sorted(reasons)), json.dumps({"positions": values, "risk": risk}, sort_keys=True), now),
        )
        audit_id = record_audit_event(
            conn, source=SOURCE_KEY, action="daily_market_valuation_completed", entity_type="market_data_run",
            entity_id=run_id, old_values={}, new_values={"as_of": effective.isoformat(), "status": quality,
            "price_coverage_pct": _fmt(price_coverage), "fx_coverage_pct": _fmt(fx_coverage),
            "benchmark_coverage_pct": _fmt(benchmark_coverage), "price_inputs_accepted": len(quotes),
            "price_rows_written": price_writes, "fx_inputs_accepted": len(rates), "fx_rows_written": fx_writes,
            "cached_price_inputs": cached_price_inputs, "reason_codes": sorted(reasons)}, created_by="system",
        )
        conn.execute(
            """UPDATE market_data_runs SET status=?,completed_at=?,price_total=?,price_stored=?,fx_total=?,fx_stored=?,
               benchmark_total=?,benchmark_stored=?,valuation_stored=?,missing_instruments_json=?,reason_codes_json=?,audit_id=?
               WHERE run_id=?""",


sed -n '1,80p' src/jarvis_finance/storage/postfinance_schema.py && grep -n "postfinance_snapshot_positions" -n src/jarvis_finance/storage/postfinance_schema.py | head -20


Output:
Chunk ID: e01036
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1116
Output:
from __future__ import annotations

from sqlite3 import Connection

def create_postfinance_ledger_import_v1(conn: Connection) -> None:
    """Create immutable PostFinance source, ledger, snapshot and cost-basis tables."""
    position_columns = {row[1] for row in conn.execute("PRAGMA table_info(positions_snapshot)")}
    if "source_type" not in position_columns:
        conn.execute("ALTER TABLE positions_snapshot ADD COLUMN source_type TEXT")
    if "source_reference" not in position_columns:
        conn.execute("ALTER TABLE positions_snapshot ADD COLUMN source_reference TEXT")
    conn.executescript(
        """
        CREATE TABLE IF NOT EXISTS postfinance_account_roles (
            role TEXT PRIMARY KEY CHECK(role IN ('efinance','etrading_depot','etrading_cash')),
            account_id TEXT NOT NULL REFERENCES accounts(account_id),
            source_reference_hash TEXT,
            created_at TEXT NOT NULL,
            UNIQUE(account_id, role)
        );
        CREATE TABLE IF NOT EXISTS postfinance_import_batches (
            batch_id TEXT PRIMARY KEY,
            bundle_sha256 TEXT NOT NULL UNIQUE CHECK(length(bundle_sha256)=64),
            zip_sha256 TEXT NOT NULL CHECK(length(zip_sha256)=64),
            overview_sha256 TEXT NOT NULL CHECK(length(overview_sha256)=64),
            parser_id TEXT NOT NULL,
            parser_version TEXT NOT NULL,
            db_revision TEXT NOT NULL,
            archive_reference TEXT NOT NULL,
            snapshot_at TEXT NOT NULL,
            status TEXT NOT NULL CHECK(status='confirmed'),
            audit_id TEXT NOT NULL,
            confirmed_at TEXT NOT NULL,
            confirmed_by TEXT NOT NULL DEFAULT 'user'
        );
        CREATE TABLE IF NOT EXISTS postfinance_documents (
            document_hash TEXT PRIMARY KEY CHECK(length(document_hash)=64),
            filename_hash TEXT NOT NULL CHECK(length(filename_hash)=64),
            semantic_identity TEXT NOT NULL UNIQUE CHECK(length(semantic_identity)=64),
            semantic_reference_hash TEXT NOT NULL CHECK(length(semantic_reference_hash)=64),
            document_type TEXT NOT NULL,
            document_date TEXT,
            account_reference_hash TEXT,
            account_role TEXT NOT NULL CHECK(account_role IN ('efinance','etrading_depot','etrading_cash')),
            page_count INTEGER NOT NULL CHECK(page_count > 0),
            archive_reference TEXT NOT NULL,
            parser_version TEXT NOT NULL,
            created_at TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS postfinance_batch_documents (
            batch_id TEXT NOT NULL REFERENCES postfinance_import_batches(batch_id),
            document_hash TEXT NOT NULL REFERENCES postfinance_documents(document_hash),
            PRIMARY KEY(batch_id, document_hash)
        );
        CREATE TABLE IF NOT EXISTS postfinance_snapshots (
            snapshot_id TEXT PRIMARY KEY,
            batch_id TEXT NOT NULL UNIQUE REFERENCES postfinance_import_batches(batch_id),
            account_id TEXT NOT NULL REFERENCES accounts(account_id),
            snapshot_at TEXT NOT NULL,
            total_chf TEXT NOT NULL,
            securities_chf TEXT NOT NULL,
            cash_chf TEXT NOT NULL,
            stocks_chf TEXT NOT NULL,
            etfs_chf TEXT NOT NULL,
            component_total_chf TEXT NOT NULL,
            difference_chf TEXT NOT NULL,
            tolerance_chf TEXT NOT NULL,
            position_count INTEGER NOT NULL,
            cash_count INTEGER NOT NULL,
            open_orders INTEGER NOT NULL,
            reconciliation_status TEXT NOT NULL CHECK(reconciliation_status IN ('matched','within_tolerance')),
            created_at TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS postfinance_snapshot_positions (
            snapshot_position_id TEXT PRIMARY KEY,
            snapshot_id TEXT NOT NULL REFERENCES postfinance_snapshots(snapshot_id),
            source_row_reference TEXT NOT NULL,
            instrument_id TEXT NOT NULL REFERENCES instruments(instrument_id),
            asset_class TEXT NOT NULL CHECK(asset_class IN ('stock','etf')),
75:        CREATE TABLE IF NOT EXISTS postfinance_snapshot_positions (
176:        CREATE TRIGGER IF NOT EXISTS postfinance_snapshot_positions_immutable BEFORE UPDATE ON postfinance_snapshot_positions
178:        CREATE TRIGGER IF NOT EXISTS postfinance_snapshot_positions_no_delete BEFORE DELETE ON postfinance_snapshot_positions


sed -n '75,125p' src/jarvis_finance/storage/postfinance_schema.py


Output:
Chunk ID: 6fdf0e
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 701
Output:
        CREATE TABLE IF NOT EXISTS postfinance_snapshot_positions (
            snapshot_position_id TEXT PRIMARY KEY,
            snapshot_id TEXT NOT NULL REFERENCES postfinance_snapshots(snapshot_id),
            source_row_reference TEXT NOT NULL,
            instrument_id TEXT NOT NULL REFERENCES instruments(instrument_id),
            asset_class TEXT NOT NULL CHECK(asset_class IN ('stock','etf')),
            quantity TEXT NOT NULL,
            provider_average_cost_original TEXT,
            provider_cost_total_original TEXT,
            price_original TEXT NOT NULL,
            price_currency TEXT NOT NULL,
            value_chf TEXT NOT NULL,
            weight_pct TEXT NOT NULL,
            computed_cost_basis_original TEXT,
            computed_cost_basis_status TEXT NOT NULL CHECK(computed_cost_basis_status IN ('complete','partial','unavailable')),
            provenance_json TEXT NOT NULL CHECK(json_valid(provenance_json)),
            created_at TEXT NOT NULL,
            UNIQUE(snapshot_id, source_row_reference),
            UNIQUE(snapshot_id, instrument_id)
        );
        CREATE TABLE IF NOT EXISTS postfinance_snapshot_cash (
            snapshot_cash_id TEXT PRIMARY KEY,
            snapshot_id TEXT NOT NULL REFERENCES postfinance_snapshots(snapshot_id),
            currency TEXT NOT NULL,
            amount_original TEXT NOT NULL,
            fx_rate_to_chf TEXT NOT NULL,
            value_chf TEXT NOT NULL,
            created_at TEXT NOT NULL,
            UNIQUE(snapshot_id, currency)
        );
        CREATE TABLE IF NOT EXISTS postfinance_ledger_events (
            event_id TEXT PRIMARY KEY,
            event_fingerprint TEXT NOT NULL UNIQUE CHECK(length(event_fingerprint)=64),
            document_hash TEXT NOT NULL REFERENCES postfinance_documents(document_hash),
            semantic_reference_hash TEXT NOT NULL CHECK(length(semantic_reference_hash)=64),
            event_type TEXT NOT NULL CHECK(event_type IN ('buy','sell','dividend','interest','fee','internal_transfer','fx','split','corporate_action')),
            account_role TEXT NOT NULL CHECK(account_role IN ('efinance','etrading_depot','etrading_cash')),
            account_id TEXT NOT NULL REFERENCES accounts(account_id),
            occurred_on TEXT NOT NULL,
            settlement_on TEXT,
            direction TEXT NOT NULL CHECK(direction IN ('in','out','neutral')),
            instrument_id TEXT REFERENCES instruments(instrument_id),
            quantity TEXT,
            price_original TEXT,
            gross_original TEXT,
            fee_original TEXT NOT NULL DEFAULT '0',
            tax_original TEXT NOT NULL DEFAULT '0',
            net_original TEXT,
            currency TEXT,
            fx_rate_to_chf TEXT,
            internal_transfer_group TEXT,


sed -n '80,170p' src/jarvis_finance/services/cash_service.py


Output:
Chunk ID: 2291b7
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 937
Output:
    created: list[str] = []
    existing_names = [item["account_name"] for item in CANONICAL_CASH_ACCOUNTS]
    duplicates = [
        row["account_name"]
        for row in conn.execute(
            f"""
            SELECT account_name, COUNT(*) AS n
            FROM accounts
            WHERE account_type='cash' AND account_name IN ({','.join('?' for _ in existing_names)})
            GROUP BY account_name HAVING COUNT(*) > 1
            """,
            existing_names,
        ).fetchall()
    ]
    for item in CANONICAL_CASH_ACCOUNTS:
        rows = conn.execute("SELECT account_id FROM accounts WHERE account_type='cash' AND account_name=?", (item["account_name"],)).fetchall()
        if len(rows) > 1:
            continue
        platform_id = _ensure_platform(conn, item["platform"])
        if rows:
            account_id = rows[0]["account_id"]
            conn.execute(
                "UPDATE accounts SET platform_id=?, currency='CHF', balance_mode=?, portfolio_bucket='cash', updated_at=? WHERE account_id=?",
                (platform_id, item["balance_mode"], _now(), account_id),
            )
        else:
            account_id = _uuid("acct")
            conn.execute(
                """
                INSERT INTO accounts(account_id, platform_id, account_name, account_type, currency, balance_mode, portfolio_bucket, is_active, created_at)
                VALUES (?, ?, ?, 'cash', 'CHF', ?, 'cash', 1, ?)
                """,
                (account_id, platform_id, item["account_name"], item["balance_mode"], _now()),
            )
            created.append(item["account_name"])
            _audit(conn, action="cash_account_seed_confirm", entity_type="cash_account", entity_id=account_id, payload=item, note="Canonical cash account ensured", created_by=created_by)
    conn.commit()
    return {"created": len(created), "created_accounts": created, "duplicates": duplicates}

def _latest_snapshot(conn: Connection, account_id: str, snapshot_type: str):
    return conn.execute(
        """
        SELECT * FROM cash_account_snapshots
        WHERE account_id=? AND snapshot_type=?
        ORDER BY balance_date DESC, created_at DESC
        LIMIT 1
        """,
        (account_id, snapshot_type),
    ).fetchone()

def _cash_movements_after_anchor(conn: Connection, account_id: str, anchor_date: str | None) -> Decimal:
    if not anchor_date:
        return Decimal("0")
    row = conn.execute(
        """
        SELECT COALESCE(SUM(CAST(net_amount_chf AS TEXT)), '0') AS movement
        FROM transactions
        WHERE account_id=? AND COALESCE(is_voided,0)=0 AND COALESCE(is_confirmed,1)=1
          AND source_type LIKE '%csv%'
          AND trade_date > ?
        """,
        (account_id, anchor_date),
    ).fetchone()
    return Decimal(str(row["movement"] or "0"))

def _calculated_balance(conn: Connection, account_id: str) -> Decimal:
    anchor = _latest_snapshot(conn, account_id, "csv_anchor_balance")
    if anchor:
        return Decimal(str(anchor["amount_chf"])) + _cash_movements_after_anchor(conn, account_id, anchor["balance_date"])
    rows = conn.execute(
        "SELECT amount_chf FROM cash_balances WHERE account_id=?",
        (account_id,),
    ).fetchall()
    if rows:
        return sum(
            (
                Decimal(str(row["amount_chf"]))
                for row in rows
                if row["amount_chf"] is not None
            ),
            Decimal("0"),
        )
    # Legacy/demo datasets can have a transaction ledger without materialized
    # cash_balances. Keep the shared read model compatible without overriding an
    # explicit snapshot projection.
    ledger = calculate_cash_balances(conn, persist_alerts=False)
    return sum(
        (


sed -n '190,280p' src/jarvis_finance/services/portfolio_analytics.py


Output:
Chunk ID: 0bc4e4
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1096
Output:
        "market_price_id": str(row["market_price_id"]),
        "provider": str(row["provider"]),
        "provider_symbol": str(row["provider_symbol"]),
        "provider_market": str(row["provider_market"] or ""),
        "price_date": actual_price_date.isoformat(),
        "original_run_id": str(row["run_id"]) if row["run_id"] else None,
        "fetched_at": str(row["fetched_at"]) if row["fetched_at"] else None,
        "created_at": str(row["created_at"]) if row["created_at"] else None,
    }
    return quote, provenance

def confirmed_canonical_positions(conn: Connection, *, as_of: str | None = None) -> list[ConfirmedPosition]:
    """Return only active, confirmed ledger positions. Preview and ingestion staging tables are never read."""

    rows = conn.execute(
        """
        SELECT t.account_id, t.instrument_id, i.isin, i.name, lower(i.asset_class) AS asset_class,
               upper(COALESCE(i.trading_currency, i.currency, '')) AS instrument_currency,
               t.transaction_type, t.quantity
        FROM transactions t
        JOIN instruments i ON i.instrument_id=t.instrument_id
        JOIN accounts a ON a.account_id=t.account_id
        WHERE t.instrument_id IS NOT NULL
          AND COALESCE(t.is_confirmed, 0)=1
          AND COALESCE(t.is_voided, 0)=0
          AND i.is_active=1 AND a.is_active=1
          AND COALESCE(i.instrument_status,'active') NOT IN ('inactive','delisted','suspended','merged')
          AND COALESCE(i.valuation_policy,'')!='exclude_from_auto_price_update'
          AND lower(i.asset_class) IN ('stock','equity','etf')
          AND lower(t.transaction_type) IN ('initial_position_snapshot','buy','sell','partial_sell','full_sell')
          AND t.trade_date<=?
        ORDER BY t.account_id, t.instrument_id, t.trade_date, t.created_at
        """,
        (as_of or datetime.now(timezone.utc).date().isoformat(),),
    ).fetchall()
    grouped: dict[tuple[str, str], dict[str, Any]] = {}
    for row in rows:
        key = (str(row["account_id"]), str(row["instrument_id"]))
        item = grouped.setdefault(key, dict(row) | {"quantity_total": ZERO})
        quantity = _decimal(row["quantity"])
        item["quantity_total"] += -abs(quantity) if str(row["transaction_type"]).lower() in SELL_TYPES else quantity
    official = latest_official_postfinance_positions(conn, as_of=as_of)
    post_snapshot_deltas = post_snapshot_postfinance_quantity_deltas(
        conn,
        official,
        as_of=as_of,
    )
    trading_cash_id = postfinance_account_roles(conn).get("etrading_cash")
    official_instruments = {key[1] for key in official}
    for key in list(grouped):
        if key[0] == trading_cash_id and key[1] in official_instruments:
            grouped.pop(key)
    for key, override in official.items():
        item = grouped.get(key)
        if item is None:
            instrument = conn.execute(
                """SELECT isin,name,lower(asset_class) asset_class,
                          upper(COALESCE(trading_currency,currency,'')) instrument_currency
                   FROM instruments WHERE instrument_id=? AND is_active=1""",
                (override.instrument_id,),
            ).fetchone()
            if not instrument:
                continue
            item = {
                "account_id": override.account_id,
                "instrument_id": override.instrument_id,
                "isin": instrument["isin"],
                "name": instrument["name"],
                "asset_class": instrument["asset_class"],
                "instrument_currency": instrument["instrument_currency"],
            }
            grouped[key] = item
        # The official snapshot is the baseline. Only confirmed trades after that
        # snapshot are replayed, so imported history is not counted twice.
        item["quantity_total"] = override.quantity + post_snapshot_deltas.get(
            override.instrument_id,
            ZERO,
        )
    return [
        ConfirmedPosition(
            account_id=item["account_id"],
            instrument_id=item["instrument_id"],
            isin=item["isin"],
            name=item["name"],
            asset_class=item["asset_class"],
            instrument_currency=item["instrument_currency"],
            quantity=item["quantity_total"],
        )
        for item in grouped.values()
        if item["quantity_total"] > ZERO


sed -n '280,310p' src/jarvis_finance/services/portfolio_analytics.py


Output:
Chunk ID: ed5cfe
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 311
Output:
        if item["quantity_total"] > ZERO
    ]

def _mapping(conn: Connection, position: ConfirmedPosition) -> tuple[dict[str, str] | None, str | None]:
    if not position.isin:
        return None, "mapping_required"
    rows = conn.execute(
        """
        SELECT provider, provider_symbol, provider_market,
               upper(COALESCE(trading_currency, currency, '')) AS mapping_currency
        FROM instrument_price_mappings
        WHERE instrument_id=? AND mapping_status='mapped'
          AND provider_symbol IS NOT NULL AND trim(provider_symbol)!=''
        ORDER BY updated_at DESC, mapping_id
        """,
        (position.instrument_id,),
    ).fetchall()
    if len(rows) != 1:
        return None, "mapping_required"
    row = dict(rows[0])
    if row["mapping_currency"] and position.instrument_currency and row["mapping_currency"] != position.instrument_currency:
        return None, "currency_mismatch"
    return {key: str(value or "") for key, value in row.items()}, None

def _active_policy(conn: Connection) -> dict[str, Any] | None:
    row = conn.execute("SELECT * FROM portfolio_policies WHERE is_active=1 ORDER BY version DESC LIMIT 1").fetchone()
    if not row:
        return None
    result = dict(row)


python - <<'PY'
import ast
expr="str(row.get('valuation_as_of') or row.get('price_date') or '') or None if row_fallback_allowed else str(analysis.get('as_of')) if analysis else None"
print(ast.dump(ast.parse(expr, mode='eval'), indent=2))
PY


Output:
Chunk ID: f6149f
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 341
Output:
Expression(
  body=IfExp(
    test=Name(id='row_fallback_allowed', ctx=Load()),
    body=BoolOp(
      op=Or(),
      values=[
        Call(
          func=Name(id='str', ctx=Load()),
          args=[
            BoolOp(
              op=Or(),
              values=[
                Call(
                  func=Attribute(
                    value=Name(id='row', ctx=Load()),
                    attr='get',
                    ctx=Load()),
                  args=[
                    Constant(value='valuation_as_of')],
                  keywords=[]),
                Call(
                  func=Attribute(
                    value=Name(id='row', ctx=Load()),
                    attr='get',
                    ctx=Load()),
                  args=[
                    Constant(value='price_date')],
                  keywords=[]),
                Constant(value='')])],
          keywords=[]),
        Constant(value=None)]),
    orelse=IfExp(
      test=Name(id='analysis', ctx=Load()),
      body=Call(
        func=Name(id='str', ctx=Load()),
        args=[
          Call(
            func=Attribute(
              value=Name(id='analysis', ctx=Load()),
              attr='get',
              ctx=Load()),
            args=[
              Constant(value='as_of')],
            keywords=[])],
        keywords=[]),
      orelse=Constant(value=None))))


sed -n '1,110p' src/jarvis_finance/services/equity_service.py


Output:
Chunk ID: 68391b
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1248
Output:
from __future__ import annotations

import json
from collections.abc import Mapping
from decimal import Decimal
from sqlite3 import Connection

from fastapi import HTTPException

from jarvis_finance.api.schemas.positions import EquityPortfolioSummary, EquityPosition
from jarvis_finance.dashboard import data as dashboard_data
from jarvis_finance.services.api_helpers import optional_decimal_text

def _asset_class_label(value: object) -> str:
    return "ETF" if str(value or "").lower() == "etf" else "Aktie"

def _account_label(row: dict[str, str]) -> str:
    platform = str(row.get("platform") or "").strip()
    account = str(row.get("account_name") or "").strip()
    if "postfinance" in platform.lower():
        if not account or "manual" in account.lower():
            return "PostFinance E-Trading"
        return account if "postfinance" in account.lower() or "e-trading" in account.lower() else f"PostFinance · {account}"
    return account or platform

def _latest_analysis(conn: Connection) -> tuple[dict[str, object] | None, dict[tuple[str, str], dict[str, object]], dict[str, str]]:
    row = conn.execute(
        """SELECT pas.*,mdr.completed_at,mdr.missing_instruments_json
             FROM portfolio_analysis_snapshots pas
             JOIN market_data_runs mdr ON mdr.run_id=pas.run_id
            ORDER BY pas.as_of DESC,pas.created_at DESC LIMIT 1"""
    ).fetchone()
    if not row:
        return None, {}, {}
    try:
        payload = json.loads(row["summary_json"] or "{}")
    except json.JSONDecodeError:
        payload = {}
    values = {
        (str(item.get("account_id") or ""), str(item.get("instrument_id") or "")): item
        for item in payload.get("positions", [])
        if isinstance(item, dict)
    }
    try:
        missing_rows = json.loads(row["missing_instruments_json"] or "[]")
    except json.JSONDecodeError:
        missing_rows = []
    missing = {
        str(item.get("instrument_id") or ""): str(item.get("reason_code") or "price_missing")
        for item in missing_rows
        if isinstance(item, dict)
    }
    return dict(row), values, missing

def _status_reason(code: str) -> str:
    labels = {
        "fmp_endpoint_restricted": "Der primäre Provider beschränkt diesen historischen Kurs im aktuellen Tarif.",
        "plan_restricted": "Der Provider beschränkt diesen historischen Kurs im aktuellen Tarif.",
        "fmp_rate_limited": "Das Provider-Limit wurde erreicht. Der Lauf kann kontrolliert fortgesetzt werden.",
        "rate_limited": "Das Provider-Limit wurde erreicht. Der Lauf kann kontrolliert fortgesetzt werden.",
        "currency_mismatch": "Die Kurswährung stimmt nicht mit der bestätigten Instrumentwährung überein.",
        "exchange_mismatch": "Der Handelsplatz des Provider-Ergebnisses ist nicht bestätigt.",
        "future_price_rejected": "Der gelieferte Kurs liegt nach dem zulässigen Börsenstichtag.",
        "stale_price": "Der letzte bestätigte Kurs ist für den Börsenstichtag zu alt und wird nicht bewertet.",
        "mapping_required": "Die Provider-Zuordnung ist noch nicht eindeutig bestätigt.",
        "fx_rate_missing": "Für die CHF-Bewertung fehlt ein bestätigter FX-Kurs.",
    }
    return labels.get(code, "Für den Börsenstichtag konnte noch kein bestätigter Kurs geladen werden.")

def _position_status(row: Mapping[str, object]) -> str:
    """Compatibility status when no audited market-analysis snapshot exists yet."""

    if "quantity" in row and Decimal(str(row.get("quantity") or "0")) <= 0:
        return "Einstand unvollständig"
    market_value = row.get("market_value_chf")
    warnings = str(row.get("quality_warnings") or "")
    if market_value not in {None, ""}:
        if "missing_cost_basis" in warnings or "missing_fx" in warnings:
            return "Einstand unvollständig"
        return "Bewertet"
    if str(row.get("price_status") or "") != "ok":
        return "Kurs fehlt"
    if str(row.get("fx_status") or "") == "missing_fx":
        return "FX fehlt für Bewertung"
    return "Bewertung unvollständig"

def _mapping_details(conn: Connection, instrument_id: str) -> dict[str, str | None]:
    row = conn.execute(
        """SELECT provider,provider_symbol,provider_market,upper(COALESCE(trading_currency,currency,'')) currency
             FROM instrument_price_mappings
            WHERE instrument_id=? AND mapping_status='mapped'
            ORDER BY updated_at DESC,mapping_id LIMIT 1""",
        (instrument_id,),
    ).fetchone()
    return dict(row) if row else {"provider": None, "provider_symbol": None, "provider_market": None, "currency": None}

def list_equity_positions(conn: Connection) -> list[EquityPosition]:
    source_rows = [
        row for row in dashboard_data.get_positions(conn)
        if row.get("asset_class", "").lower() in {"stock", "equity", "etf"}
        and row.get("instrument_status", "").lower() != "inactive"
    ]
    analysis, values, missing = _latest_analysis(conn)


nl -ba src/jarvis_finance/services/equity_service.py | sed -n '112,150p'


Output:
Chunk ID: 66709c
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 526
Output:
   112	    for row in source_rows:
   113	        key = (str(row.get("account_id") or ""), str(row.get("instrument_id") or ""))
   114	        candidate = values.get(key)
   115	        row_is_audited = row.get("valuation_source") in {
   116	            "postfinance_official_import",
   117	            "audited_market_run",
   118	        }
   119	        candidate_is_newer = bool(
   120	            analysis
   121	            and candidate
   122	            and str(analysis.get("as_of") or "") > str(row.get("valuation_as_of") or row.get("price_date") or "")
   123	            and candidate.get("quality_status") == "fresh"
   124	        )
   125	        raw = (
   126	            candidate.get("value_chf")
   127	            if candidate_is_newer and candidate
   128	            else row.get("market_value_chf") if analysis is None or row_is_audited else None
   129	        )
   130	        effective_values[key] = Decimal(str(raw)) if raw not in {None, ""} else None
   131	    complete = bool(source_rows) and all(value is not None for value in effective_values.values())
   132	    total = sum((value or Decimal("0") for value in effective_values.values()), Decimal("0"))
   133	    positions: list[EquityPosition] = []
   134	    for row in source_rows:
   135	        account_id = str(row.get("account_id") or "")
   136	        instrument_id = str(row.get("instrument_id") or "")
   137	        snapshot_value = values.get((account_id, instrument_id))
   138	        value = (
   139	            snapshot_value
   140	            if analysis
   141	            and snapshot_value
   142	            and snapshot_value.get("quality_status") == "fresh"
   143	            and str(analysis.get("as_of") or "") > str(row.get("valuation_as_of") or row.get("price_date") or "")
   144	            else None
   145	        )
   146	        row_fallback_allowed = analysis is None or row.get("valuation_source") in {
   147	            "postfinance_official_import",
   148	            "audited_market_run",
   149	        }
   150	        mapping = _mapping_details(conn, instrument_id)


grep -n "def get_cash_summary\|cash_chf" -n src/jarvis_finance/services/cash_service.py | head -30 && sed -n '450,520p' src/jarvis_finance/services/cash_service.py


Output:
Chunk ID: b141f1
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1036
Output:
475:def get_cash_summary(conn: Connection) -> CashSummary:
482:        cash_chf=decimal_text(total, 2),
                    calculated_balance_chf=decimal_text(calculated, 2),
                    manual_balance_chf=(
                        decimal_text(manual_amount, 2)
                        if manual_amount is not None
                        else None
                    ),
                    csv_anchor_balance_chf=(
                        decimal_text(anchor["amount_chf"], 2)
                        if anchor and currency == default_currency
                        else None
                    ),
                    used_value_chf=decimal_text(used, 2),
                    difference_chf=decimal_text(difference, 2),
                    last_manual_reconciliation=(
                        manual["balance_date"]
                        if manual and currency == default_currency
                        else None
                    ),
                    last_imported_booking=_last_imported_booking(conn, account_id),
                    status=status,
                )
            )
    return positions

def get_cash_summary(conn: Connection) -> CashSummary:
    # Read paths must never seed or refresh accounts; setup is an explicit Confirm action.
    positions = list_cash_positions(conn)
    total = sum(Decimal(p.used_value_chf) for p in positions)
    last_dates = [p.last_manual_reconciliation for p in positions if p.last_manual_reconciliation]
    return CashSummary(
        base_currency="CHF",
        cash_chf=decimal_text(total, 2),
        manual_accounts_count=sum(1 for p in positions if p.balance_mode == "manual"),
        csv_calculated_accounts_count=sum(1 for p in positions if p.balance_mode == "csv_calculated"),
        open_reconciliation_count=sum(1 for p in positions if p.status == "Abgleich offen"),
        last_reconciliation_at=max(last_dates) if last_dates else None,
        positions=positions,
    )

def preview_cash_snapshot(conn: Connection, request: CashSnapshotPreviewRequest) -> PreviewResponse:
    row = conn.execute("SELECT account_id, account_type FROM accounts WHERE account_id=?", (request.account_id,)).fetchone()
    if not row or row["account_type"] != "cash":
        raise HTTPException(status_code=404, detail="Cash account not found")
    if request.snapshot_type not in {"manual_balance", "csv_anchor_balance", "calculated_balance", "reconciliation"}:
        raise HTTPException(status_code=422, detail="Invalid snapshot_type")
    amount = _decimal(request.amount_chf, "amount_chf")
    return PreviewResponse(preview_id=_uuid("preview"), asset_class="cash", summary=f"{request.snapshot_type} CHF per {request.balance_date}", amount_chf=decimal_text(amount, 2), fx_status="not_needed", warnings=[])

def confirm_cash_snapshot(conn: Connection, request: CashSnapshotConfirmRequest) -> ConfirmResponse:
    if not request.confirm:
        raise HTTPException(status_code=400, detail="Explicit confirm required")
    preview_cash_snapshot(conn, request)
    amount = _decimal(request.amount_chf, "amount_chf")
    snapshot_id = _uuid("cashsnap")
    now = _now()
    source = "manual" if request.snapshot_type in {"manual_balance", "reconciliation"} else "csv_import" if request.snapshot_type == "csv_anchor_balance" else "system_calculated"
    audit_id = _audit(conn, action=f"cash_{request.snapshot_type}_confirm", entity_type="cash_account", entity_id=request.account_id, payload=request.model_dump(), note=request.note)
    conn.execute(
        """
        INSERT INTO cash_account_snapshots(snapshot_id, account_id, snapshot_type, balance_date, amount_original, currency, amount_chf, source, note, created_at, created_by, audit_id)
        VALUES (?, ?, ?, ?, ?, 'CHF', ?, ?, ?, ?, 'user', ?)
        """,
        (snapshot_id, request.account_id, request.snapshot_type, request.balance_date, decimal_text(amount, 2), decimal_text(amount, 2), source, request.note, now, audit_id),
    )
    conn.commit()
    return ConfirmResponse(status="confirmed", entity_id=snapshot_id, audit_id=audit_id, message="Kontostand gespeichert · Audit geschrieben")


[P1] Use same-day market analysis values

When a normal non-PostFinance position has a completed market-analysis snapshot for the same date as the dashboard price row, this strict `>` check is false because `analysis.as_of` and `valuation_as_of`/`price_date` are equal. Since row fallback is disabled whenever an analysis exists for non-audited rows, those freshly valued positions are treated as unvalued, making the equity summary partial/missing after a successful same-day market run.

The patch incorrectly drops fresh same-day audited market values for ordinary positions, which can break equity valuation summaries after successful market runs. This is a functional regression in a core read model.