Output:
Chunk ID: 41005d
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1023
Output:
206:    for position in bundle.snapshot.positions:
255:        for position in bundle.snapshot.positions:
269:    component_total = snapshot.securities_total_chf + snapshot.cash_total_chf
287:        "position_count": len(snapshot.positions),
288:        "cash_count": len(snapshot.cash),
295:        "cash_chf": _money(snapshot.cash_total_chf),
599:        component_total = snapshot.securities_total_chf + snapshot.cash_total_chf
610:                _money(snapshot.cash_total_chf),
616:                len(snapshot.positions),
617:                len(snapshot.cash),
720:        for position in snapshot.positions:
745:                """INSERT INTO postfinance_snapshot_positions(snapshot_position_id,snapshot_id,source_row_reference,instrument_id,asset_class,quantity,provider_average_cost_original,provider_cost_total_original,price_original,price_currency,value_chf,weight_pct,computed_cost_basis_original,computed_cost_basis_status,provenance_json,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
795:        for cash in snapshot.cash:
797:                "INSERT INTO postfinance_snapshot_cash(snapshot_cash_id,snapshot_id,currency,amount_original,fx_rate_to_chf,value_chf,created_at) VALUES(?,?,?,?,?,?,?)",
908:               FROM postfinance_snapshot_positions p
                    status,
                    json.dumps(
                        {
                            "provider": "official_account_overview",
                            "calculated": "documented_trade_fifo",
                            "estimated": False,
                        },
                        sort_keys=True,
                    ),
                    now,
                ),
            )
            conn.execute(
                """INSERT INTO positions_snapshot(position_snapshot_id,snapshot_date,account_id,platform_id,instrument_id,quantity,average_cost_original,cost_basis_original,market_price_original,market_value_original,market_fx_rate_to_chf,market_value_chf,portfolio_weight_pct,category,data_quality_status,source_type,source_reference,created_at) SELECT ?,?,?,a.platform_id,?,?,?,?,?,?,?,?,?,?,?,?,?,? FROM accounts a WHERE a.account_id=?""",
                (
                    _id("position"),
                    snapshot.valuation_at[:10],
                    accounts["etrading_depot"],
                    instrument_id,
                    _text(position.quantity),
                    _text(position.provider_average_cost_original),
                    _text(position.provider_cost_total_original),
                    _text(position.market_price_original),
                    _text(position.quantity * position.market_price_original),
                    None,
                    _money(position.market_value_chf),
                    _text(position.weight_pct),
                    position.asset_class,
                    "verified",
                    "postfinance_official_import",
                    snapshot_id,
                    now,
                    accounts["etrading_depot"],
                ),
            )
        for cash in snapshot.cash:
            conn.execute(
                "INSERT INTO postfinance_snapshot_cash(snapshot_cash_id,snapshot_id,currency,amount_original,fx_rate_to_chf,value_chf,created_at) VALUES(?,?,?,?,?,?,?)",
                (
                    _id("pfcash"),
                    snapshot_id,
                    cash.currency,
                    _text(cash.amount_original),
                    _text(cash.fx_rate_to_chf),
                    _money(cash.source_value_chf),
                    now,
                ),
            )
            conn.execute(
                "INSERT INTO cash_balances(cash_balance_id,account_id,balance_date,currency,amount_original,fx_rate_to_chf,amount_chf,source_type,quality_status,notes,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?)",
                (
                    _id("cash"),
                    accounts["etrading_cash"],
                    snapshot.valuation_at[:10],
                    cash.currency,
                    _text(cash.amount_original),


sed -n '815,850p' src/jarvis_finance/services/postfinance_service.py


Output:
Chunk ID: c548ee
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 379
Output:
                    _text(cash.amount_original),
                    _text(cash.fx_rate_to_chf),
                    _money(cash.source_value_chf),
                    "postfinance_official_import",
                    "verified",
                    "Official PostFinance account overview",
                    now,
                ),
            )
        conn.execute(
            "INSERT INTO account_value_snapshots(snapshot_id,account_id,valuation_date,total_value_chf,currency,source_type,quality_status,notes,created_at,valuation_at,source_reference,is_active) VALUES(?,?,?,?,'CHF','postfinance_official_import','ok','Official PostFinance account overview',?,?,?,1)",
            (
                _id("acctval"),
                accounts["etrading_depot"],
                snapshot.valuation_at[:10],
                _money(snapshot.total_value_chf),
                now,
                snapshot.valuation_at,
                snapshot_id,
            ),
        )
        conn.commit()
    except IntegrityError as exc:
        conn.rollback()
        duplicate = conn.execute(
            "SELECT batch_id,audit_id FROM postfinance_import_batches WHERE bundle_sha256=?",
            (bundle.bundle_hash,),
        ).fetchone()
        if duplicate:
            return {
                "status": "confirmed",
                "batch_id": duplicate["batch_id"],
                "audit_id": duplicate["audit_id"],
                "idempotent": True,
            }
        for ref, created in archive_refs:


grep -n "def _money\|def _text" -n src/jarvis_finance/services/postfinance_service.py && grep -R "get_postfinance_summary" -n tests | head -20


Output:
Chunk ID: dffb2a
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 152
Output:
47:def _text(value: Decimal | None) -> str | None:
51:def _money(value: Decimal) -> str:
grep: tests/__pycache__/test_postfinance_sprint13.cpython-311-pytest-9.1.1.pyc: binary file matches
grep: tests/__pycache__/test_postfinance_sprint13.cpython-311.pyc: binary file matches
grep: tests/__pycache__/test_postfinance_sprint13.cpython-311-pytest-9.0.2.pyc: binary file matches
tests/test_postfinance_sprint13.py:292:    safe_summary = service.get_postfinance_summary(conn)
tests/test_postfinance_sprint13.py:626:    assert service.get_postfinance_summary(conn)["latest_snapshot"]["total_chf"] == "321149.23"


sed -n '40,58p' src/jarvis_finance/services/postfinance_service.py


Output:
Chunk ID: 01fe26
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 131
Output:

def _hash(*values: object) -> str:
    return sha256(
        json.dumps(values, sort_keys=True, separators=(",", ":"), default=str).encode()
    ).hexdigest()

def _text(value: Decimal | None) -> str | None:
    return format(value, "f") if value is not None else None

def _money(value: Decimal) -> str:
    return format(value.quantize(Decimal("0.01")), "f")

def _decode(value: str, label: str) -> bytes:
    try:
        return base64.b64decode(value, validate=True)
    except (binascii.Error, ValueError) as exc:


sed -n '1888,1906p' src/jarvis_finance/storage/migrations.py && sed -n '900,950p' src/jarvis_finance/services/portfolio_analytics.py


Output:
Chunk ID: 3d4f2a
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1131
Output:
        CREATE INDEX IF NOT EXISTS idx_benchmark_snapshots_policy_time
            ON benchmark_snapshots(policy_id, benchmark_reference, as_of, fetched_at);

        CREATE TABLE IF NOT EXISTS portfolio_analysis_snapshots (
            analysis_snapshot_id TEXT PRIMARY KEY,
            run_id TEXT NOT NULL UNIQUE REFERENCES market_data_runs(run_id),
            as_of TEXT NOT NULL,
            base_currency TEXT NOT NULL DEFAULT 'CHF',
            total_value_chf TEXT,
            price_coverage_pct TEXT NOT NULL,
            fx_coverage_pct TEXT NOT NULL,
            benchmark_coverage_pct TEXT NOT NULL,
            quality_status TEXT NOT NULL CHECK(quality_status IN ('complete','partial','unavailable')),
            reason_codes_json TEXT NOT NULL DEFAULT '[]'
                CHECK(json_valid(reason_codes_json) AND json_type(reason_codes_json)='array'),
            summary_json TEXT NOT NULL DEFAULT '{}'
                CHECK(json_valid(summary_json) AND json_type(summary_json)='object'),
            created_at TEXT NOT NULL
        );
    points = []
    final_twr: Decimal | None = None
    for value in dates:
        if value == dates[0]:
            twr: Decimal | None = ZERO
        else:
            perf = build_portfolio_performance(conn, from_date=dates[0], to_date=value, base_currency="CHF")
            summary = perf.get("summary")
            twr_raw = summary.get("twr") if isinstance(summary, dict) else None
            twr = _decimal(twr_raw, ZERO) if twr_raw is not None else None
        if twr is None:
            continue
        final_twr = twr
        benchmark_norm = _decimal(benchmark_rows[value]["value_chf"]) / benchmark_start * HUNDRED
        points.append({"date": value, "portfolio": _fmt((ONE + twr) * HUNDRED), "benchmark": _fmt(benchmark_norm)})
    if len(points) < 2 or final_twr is None:
        return {"status": "partial", "twr_pct": None, "benchmark_pct": None, "difference_pct": None,
                "return_type": benchmark_rows[dates[-1]]["return_type"], "normalized": points,
                "reason_codes": ["portfolio_performance_unavailable"]}
    benchmark_pct = (_decimal(benchmark_rows[dates[-1]]["value_chf"]) / benchmark_start - ONE) * HUNDRED
    twr_pct = final_twr * HUNDRED
    return {"status": "current", "twr_pct": _fmt(twr_pct), "benchmark_pct": _fmt(benchmark_pct),
            "difference_pct": _fmt(twr_pct - benchmark_pct), "return_type": benchmark_rows[dates[-1]]["return_type"],
            "normalized": points, "reason_codes": []}

def build_portfolio_analytics(conn: Connection, *, period: str = "1y") -> dict[str, Any]:
    """Read-only projection. It performs no provider call and no database write."""

    latest = conn.execute("SELECT * FROM portfolio_analysis_snapshots ORDER BY as_of DESC,created_at DESC LIMIT 1").fetchone()
    postfinance_confirmed = bool(conn.execute("SELECT 1 FROM portfolio_ingestion_batches WHERE source_key='postfinance_etrading' LIMIT 1").fetchone())
    notice = None if postfinance_confirmed else "PostFinance-Vorschau noch nicht bestätigt – diese Positionen sind in der Analyse noch nicht enthalten."
    if not latest:
        return {
            "as_of": None, "status": "unavailable", "freshness": "unavailable", "notice": notice,
            "coverage": {"price_pct": "0.00", "fx_pct": "0.00", "benchmark_pct": "0.00"},
            "valuation": {"total_chf": None},
            "performance": {"status": "unavailable", "twr_pct": None, "benchmark_pct": None,
                            "difference_pct": None, "return_type": None, "normalized": [],
                            "reason_codes": ["no_market_snapshot"]},
            "risk": {"status": "unavailable", "largest_position": None, "top5_pct": None, "cash_pct": None,
                     "asset_classes": [], "currencies": [], "policy_breaches": [], "volatility_pct": None,
                     "max_drawdown_pct": None, "reason_codes": ["no_market_snapshot"]},
            "missing_instruments": [], "reason_codes": ["no_market_snapshot"],
        }
    run = conn.execute("SELECT * FROM market_data_runs WHERE run_id=?", (latest["run_id"],)).fetchone()
    summary = json.loads(latest["summary_json"] or "{}")
    as_of_date = date.fromisoformat(latest["as_of"])
    age = (datetime.now(timezone.utc).date() - as_of_date).days
    latest_reasons = json.loads(latest["reason_codes_json"] or "[]")
    freshness = "stale" if {"stale_price", "stale_fx"}.intersection(latest_reasons) else ("current" if age <= 3 else "stale")


sed -n '1,220p' src/jarvis_finance/ledger/positions.py


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

from dataclasses import dataclass, field
from datetime import datetime, timezone
from decimal import Decimal, ROUND_HALF_UP
from sqlite3 import Connection

from jarvis_finance.audit.log import record_audit_event
from jarvis_finance.imports.common import stable_id, utc_now
from jarvis_finance.quality.alerts import create_alert
from jarvis_finance.fx.rates import latest_fx_rate

from .cost_basis import WeightedAverageLot

MONEY = Decimal("0.01")

def _d(value: object, default: str = "0") -> Decimal:
    if value is None or str(value).strip() == "":
        return Decimal(default)
    return Decimal(str(value))

def _money(value: Decimal | None) -> Decimal | None:
    if value is None:
        return None
    return value.quantize(MONEY, rounding=ROUND_HALF_UP)

@dataclass
class Position:
    account_id: str
    instrument_id: str
    quantity: Decimal = Decimal("0")
    cost_basis_original: Decimal = Decimal("0")
    cost_basis_chf: Decimal = Decimal("0")
    average_cost_original: Decimal | None = None
    average_cost_chf: Decimal | None = None
    realized_pnl_chf: Decimal = Decimal("0")
    income_chf: Decimal = Decimal("0")
    fees_chf: Decimal = Decimal("0")
    taxes_chf: Decimal = Decimal("0")
    market_price_original: Decimal | None = None
    market_value_original: Decimal | None = None
    market_value_chf: Decimal | None = None
    unrealized_pnl_chf: Decimal | None = None
    total_return_chf: Decimal | None = None
    data_quality_status: str = "ok"
    valuation_status: str = "not_valuable"
    valuation_timestamp_status: str = "missing_timestamp"
    hedge_status: str = "unknown"
    instrument_status: str = "unknown"
    valuation_policy: str = "live_price"
    corporate_action_status: str = "not_checked"
    quality_warnings: list[str] = field(default_factory=list)

@dataclass
class PositionCalculationResult:
    positions: dict[tuple[str, str], Position] = field(default_factory=dict)
    as_of_date: str | None = None

def _latest_market_price(conn: Connection, instrument_id: str, as_of_date: str | None):
    if as_of_date:
        return conn.execute(
            """
            SELECT close, currency, price_timestamp, price_date, corporate_action_status FROM market_prices
            WHERE instrument_id=? AND price_date <= ? AND quality_status IN ('fresh','ok')
            ORDER BY price_date DESC, created_at DESC LIMIT 1
            """,
            (instrument_id, as_of_date),
        ).fetchone()
    return conn.execute(
        """
        SELECT close, currency, price_timestamp, price_date, corporate_action_status FROM market_prices
        WHERE instrument_id=? AND quality_status IN ('fresh','ok')
        ORDER BY price_date DESC, created_at DESC LIMIT 1
        """,
        (instrument_id,),
    ).fetchone()

def _add_warning(
    conn: Connection,
    pos: Position,
    rule_id: str,
    message: str,
    *,
    persist: bool = True,
) -> None:
    if rule_id not in pos.quality_warnings:
        pos.quality_warnings.append(rule_id)
    pos.data_quality_status = "incomplete"
    if persist:
        create_alert(
            conn,
            priority="kritisch" if rule_id == "missing_fx" else "warnung",
            category="ledger",
            entity_type="instrument",
            entity_id=pos.instrument_id,
            rule_id=rule_id,
            message=message,
            evidence={"account_id": pos.account_id, "instrument_id": pos.instrument_id},
        )

def _timestamp_status(price_ts: str | None, fx_ts: str | None, *, max_delta_hours: int = 24) -> str:
    if not price_ts or not fx_ts:
        return "missing_timestamp"
    try:
        p = datetime.fromisoformat(price_ts.replace("Z", "+00:00"))
        f = datetime.fromisoformat(fx_ts.replace("Z", "+00:00"))
        if p.tzinfo is None:
            p = p.replace(tzinfo=timezone.utc)
        if f.tzinfo is None:
            f = f.replace(tzinfo=timezone.utc)
    except ValueError:
        return "missing_timestamp"
    delta_hours = abs((p - f).total_seconds()) / 3600
    if delta_hours <= 1:
        return "aligned"
    if delta_hours <= max_delta_hours:
        return "acceptable"
    return "stale_mismatch"

def _instrument_metadata(conn: Connection, instrument_id: str) -> dict[str, object]:
    row = conn.execute("SELECT * FROM instruments WHERE instrument_id=?", (instrument_id,)).fetchone()
    if not row:
        return {"hedge_status": "unknown", "instrument_status": "unknown", "valuation_policy": "live_price", "corporate_action_status": "not_checked"}
    return dict(row)

def calculate_positions(
    conn: Connection,
    *,
    as_of_date: str | None = None,
    max_price_fx_time_delta_hours: int = 24,
    persist_alerts: bool = True,
) -> PositionCalculationResult:
    def add_warning(pos: Position, rule_id: str, message: str) -> None:
        _add_warning(conn, pos, rule_id, message, persist=persist_alerts)

    result = PositionCalculationResult(as_of_date=as_of_date)
    lots: dict[tuple[str, str], WeightedAverageLot] = {}
    params: tuple[object, ...] = ()
    where = "WHERE instrument_id IS NOT NULL AND COALESCE(is_voided, 0) = 0"
    if as_of_date:
        where += " AND trade_date <= ?"
        params = (as_of_date,)
    rows = conn.execute(
        f"""
        SELECT * FROM transactions
        {where}
        ORDER BY account_id, instrument_id, trade_date, created_at, transaction_id
        """,
        params,
    ).fetchall()
    for row in rows:
        key = (row["account_id"], row["instrument_id"])
        pos = result.positions.setdefault(key, Position(row["account_id"], row["instrument_id"]))
        lot = lots.setdefault(key, WeightedAverageLot())
        t = row["transaction_type"]
        qty = _d(row["quantity"])
        gross = _d(row["gross_amount_original"])
        fee = _d(row["fee_original"])
        tax = _d(row["tax_original"])
        fx = _d(row["fx_rate_to_chf"], "1") if row["fx_rate_to_chf"] is not None else None
        if fx is None or row["fx_status"] == "missing":
            add_warning(pos, "missing_fx", "Historic FX is missing; precise CHF total return cannot be calculated.")
        if t in {"initial_position_snapshot", "buy"}:
            if qty > 0:
                cost_original = gross + fee
                cost_chf = (gross + fee) * fx if fx is not None else Decimal("0")
                lot.buy(qty, cost_original, cost_chf)
                pos.fees_chf += fee * fx if fx is not None else Decimal("0")
                pos.taxes_chf += tax * fx if fx is not None else Decimal("0")
        elif t in {"partial_sell", "full_sell"}:
            if qty > 0:
                proceeds_chf = (gross - fee - tax) * fx if fx is not None else Decimal("0")
                lot.sell(qty, proceeds_chf)
                pos.fees_chf += fee * fx if fx is not None else Decimal("0")
                pos.taxes_chf += tax * fx if fx is not None else Decimal("0")
        elif t in {"dividend", "etf_distribution"}:
            income_original = _d(row["net_amount_original"]) if row["net_amount_original"] is not None else gross - fee - tax
            if fx is not None:
                pos.income_chf += income_original * fx
                pos.fees_chf += fee * fx
                pos.taxes_chf += tax * fx
        if t == "initial_position_snapshot":
            add_warning(pos, "snapshot_only", "Initial snapshot lacks full transaction history; performance is incomplete.")
            if gross == 0 or fx is None:
                add_warning(pos, "cost_basis_uncertain", "Cost basis is uncertain for this initial snapshot.")
    for key, lot in lots.items():
        pos = result.positions[key]
        meta = _instrument_metadata(conn, pos.instrument_id)
        pos.hedge_status = str(meta.get("hedge_status") or "unknown")
        pos.instrument_status = str(meta.get("instrument_status") or "unknown")
        pos.valuation_policy = str(meta.get("valuation_policy") or "live_price")
        pos.corporate_action_status = str(meta.get("corporate_action_status") or "not_checked")
        if pos.hedge_status == "unknown":
            add_warning(pos, "hedge_status_unknown", "Currency hedge status is unknown; FX attribution is incomplete.")
        if pos.instrument_status in {"delisted", "suspended", "merged", "inactive"} and pos.valuation_policy in {"live_price", "exclude_from_auto_price_update"}:
            add_warning(pos, "delisted_or_suspended", "Instrument status excludes or limits automatic valuation.")
        if pos.corporate_action_status in {"suspected", "confirmed"} or meta.get("split_or_corporate_action_review_required"):
            add_warning(pos, "corporate_action_suspected", "Corporate action review is required before high-confidence valuation.")
        pos.quantity = lot.quantity.normalize()
        pos.cost_basis_original = _money(lot.cost_basis_original) or Decimal("0")
        pos.cost_basis_chf = _money(lot.cost_basis_chf) or Decimal("0")
        pos.average_cost_original = lot.average_cost_original
        pos.average_cost_chf = lot.average_cost_chf
        pos.realized_pnl_chf = _money(lot.realized_pnl_chf) or Decimal("0")
        pos.income_chf = _money(pos.income_chf) or Decimal("0")
        pos.fees_chf = _money(pos.fees_chf) or Decimal("0")
        pos.taxes_chf = _money(pos.taxes_chf) or Decimal("0")
        market = _latest_market_price(conn, pos.instrument_id, as_of_date)
        if market is None:
            add_warning(pos, "missing_market_price", "Market price is missing; unrealized P&L cannot be calculated.")
        else:


grep -R "create_postfinance_ledger_import_v1\|postfinance_schema" -n src/jarvis_finance/storage src/jarvis_finance | head -50


Output:
Chunk ID: 2b1e9b
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 258
Output:
grep: src/jarvis_finance/storage/__pycache__/migrations.cpython-311.pyc: binary file matches
grep: src/jarvis_finance/storage/__pycache__/postfinance_schema.cpython-311.pyc: binary file matches
grep: src/jarvis_finance/storage/__pycache__/migrations.cpython-311.pyc: binary file matches
grep: src/jarvis_finance/storage/__pycache__/postfinance_schema.cpython-311.pyc: binary file matches
src/jarvis_finance/storage/migrations.py:8:from .postfinance_schema import create_postfinance_ledger_import_v1
src/jarvis_finance/storage/migrations.py:2127:    create_postfinance_ledger_import_v1(conn)
src/jarvis_finance/storage/postfinance_schema.py:6:def create_postfinance_ledger_import_v1(conn: Connection) -> None:
src/jarvis_finance/storage/migrations.py:8:from .postfinance_schema import create_postfinance_ledger_import_v1
src/jarvis_finance/storage/migrations.py:2127:    create_postfinance_ledger_import_v1(conn)
src/jarvis_finance/storage/postfinance_schema.py:6:def create_postfinance_ledger_import_v1(conn: Connection) -> None:


sed -n '2110,2135p' src/jarvis_finance/storage/migrations.py


Output:
Chunk ID: c0dbd2
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 305
Output:
    _create_budget_phase11_tables(conn)
    _create_budget_phase14_tables(conn)
    _create_budget_phase15_tables(conn)
    _create_budget_phase18_tables(conn)
    _create_budget_phase19_tables(conn)
    _create_budget_import_production_v1_tables(conn)
    _create_budget_categories_ux_fix_tables(conn)
    _create_budget_planning_forecast_v1_tables(conn)
    _create_budget_fixed_costs_subscriptions_v1_tables(conn)
    _create_budget_monthly_import_rule_learning_v1_tables(conn)
    _create_transfer_pairing_v2_tables(conn)
    _create_portfolio_policy_tables(conn)
    _create_portfolio_performance_tables(conn)
    _create_portfolio_ingestion_reconciliation_tables(conn)
    _create_daily_market_analytics_tables(conn)
    _create_postfinance_baseline_mapping_audit_v1(conn)
    _create_truewealth_verified_snapshot_v1(conn)
    create_postfinance_ledger_import_v1(conn)
    _create_grocery_optimizer_v1_tables(conn)
    _add_grocery_price_provider_v1_columns(conn)
    _create_grocery_matching_learning_v2_tables(conn)

def apply_migrations(conn: Connection) -> None:
    conn.executescript(INITIAL_SCHEMA_SQL)
    existing_initial = conn.execute("SELECT 1 FROM schema_migrations WHERE version = 1").fetchone()


grep -R "get_cash_overview\|get_positions(conn" -n src/jarvis_finance | head -100


Output:
Chunk ID: 9d6c89
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 367
Output:
grep: src/jarvis_finance/dashboard/__pycache__/data.cpython-312.pyc: binary file matches
grep: src/jarvis_finance/dashboard/__pycache__/data.cpython-311.pyc: binary file matches
grep: src/jarvis_finance/dashboard/views/__pycache__/page_03_equities_etfs.cpython-311.pyc: binary file matches
src/jarvis_finance/dashboard/views/page_13_equity_manage.py:366:        show_table(st, data.get_positions(conn))
src/jarvis_finance/dashboard/views/page_03_equities_etfs.py:23:        r for r in data.get_positions(conn)
src/jarvis_finance/dashboard/views/page_03_equities_etfs.py:32:    for row in data.get_cash_overview(conn):
src/jarvis_finance/dashboard/data.py:540:def get_cash_overview(conn: Connection) -> list[dict[str, str]]:
src/jarvis_finance/dashboard/data.py:559:def get_positions(conn: Connection) -> list[dict[str, str]]:
src/jarvis_finance/dashboard/data.py:678:    for row in get_positions(conn):
src/jarvis_finance/dashboard/data.py:709:    for row in get_cash_overview(conn):
src/jarvis_finance/dashboard/data.py:711:    for row in get_positions(conn):
src/jarvis_finance/dashboard/data.py:1171:    cash_rows = get_cash_overview(conn)
src/jarvis_finance/dashboard/data.py:1173:    positions = [r for r in get_positions(conn) if r.get("asset_class", "").lower() in {"stock", "equity", "etf"} and r.get("instrument_status", "").lower() != "inactive"]
src/jarvis_finance/services/equity_service.py:120:        row for row in dashboard_data.get_positions(conn)


sed -n '660,725p' src/jarvis_finance/dashboard/data.py && sed -n '1160,1190p' src/jarvis_finance/dashboard/data.py


Output:
Chunk ID: 3ac37b
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1505
Output:
            "hedge_status": row["hedge_status"] if row else pos.hedge_status,
            "instrument_status": row["instrument_status"] if row else pos.instrument_status,
            "valuation_policy": row["valuation_policy"] if row else pos.valuation_policy,
            "fx_status": "ok" if "missing_fx" not in pos.quality_warnings else "missing_fx",
            "market_price_status": "ok" if market_price is not None else "missing_market_price",
            "valuation_timestamp_status": pos.valuation_timestamp_status,
            "corporate_action_status": row["corporate_action_status"] if row else pos.corporate_action_status,
            "valuation_status": pos.valuation_status,
            "total_return_chf": dec_text(pos.total_return_chf, "0.01") if pos.total_return_chf is not None else "",
            "total_return_status": "complete" if pos.total_return_chf is not None else "incomplete",
            "quality_warnings": ",".join(pos.quality_warnings),
            "data_quality_status": pos.data_quality_status,
        })
    return rows

def get_portfolio_positions_user(conn: Connection) -> list[dict[str, str]]:
    rows: list[dict[str, str]] = []
    for row in get_positions(conn):
        if row.get("asset_class", "").lower() not in {"stock", "equity", "etf"}:
            continue
        rows.append({
            "name": row.get("name", ""),
            "ticker": row.get("ticker", ""),
            "isin": row.get("isin", ""),
            "depot": row.get("account_name", ""),
            "assettyp": "ETF" if row.get("asset_class", "").lower() == "etf" else "Aktie",
            "menge": row.get("quantity", ""),
            "kurs": row.get("market_price_original") or "Preis noch nicht verfügbar",
            "kurswaehrung": row.get("price_currency", ""),
            "marktwert_chf": chf_text(row.get("market_value_chf")) if row.get("market_value_chf") else "nicht bewertet",
            "einstand_chf": chf_text(row.get("cost_basis_chf")) if row.get("cost_basis_chf") else "unvollständig",
            "p_l_chf": chf_text(row.get("total_return_chf")) if row.get("total_return_chf") else "nicht berechenbar",
            "status": translate_status(row.get("price_status") or row.get("data_quality_status")),
        })
    return rows

def get_portfolio_asset_class_chart(conn: Connection) -> list[dict[str, str]]:
    summary = get_command_center_summary(conn)
    return [
        {"label": "Crypto", "value_chf": summary["crypto_total_chf"]},
        {"label": "Aktien/ETF", "value_chf": summary["equity_etf_total_chf"]},
        {"label": "Cash", "value_chf": summary["cash_total_chf"]},
    ]

def get_platform_value_chart(conn: Connection) -> list[dict[str, str]]:
    totals: dict[str, Decimal] = {}
    for row in get_cash_overview(conn):
        totals[row["platform"]] = totals.get(row["platform"], Decimal("0")) + d(row.get("amount_chf"))
    for row in get_positions(conn):
        totals[row["platform"]] = totals.get(row["platform"], Decimal("0")) + d(row.get("market_value_chf"))
    crypto_total = d(get_crypto_summary_cards(conn)["total_value_chf"])
    if crypto_total:
        totals["Crypto Wallets"] = totals.get("Crypto Wallets", Decimal("0")) + crypto_total
    return [{"label": k, "value_chf": dec_text(v, "0.01")} for k, v in sorted(totals.items(), key=lambda item: item[1], reverse=True)]

def get_ledger_transactions(conn: Connection, limit: int = 200) -> list[dict[str, str]]:
    return rowdicts(conn.execute(
        """
        SELECT t.trade_date, p.name AS platform, a.account_name, t.transaction_type,
               i.name AS instrument, i.ticker, t.quantity, t.gross_amount_original,
               t.net_amount_original, t.currency_original, t.fx_status, t.quality_status,
               t.source_type, t.source_id
    ordered = sorted(rows, key=lambda row: d(row.get("value_chf")), reverse=True)
    if len(ordered) <= limit:
        return ordered
    head = ordered[:limit]
    other = sum((d(row.get("value_chf")) for row in ordered[limit:]), Decimal("0"))
    if other > 0:
        head.append({"label": "Andere", "value_chf": dec_text(other, "0.01")})
    return head

def get_command_center_summary(conn: Connection) -> dict[str, str]:
    cash_rows = get_cash_overview(conn)
    crypto_summary = get_crypto_summary_cards(conn)
    positions = [r for r in get_positions(conn) if r.get("asset_class", "").lower() in {"stock", "equity", "etf"} and r.get("instrument_status", "").lower() != "inactive"]
    cash_total = sum(d(r["amount_chf"]) for r in cash_rows if r["amount_chf"])
    crypto_total = d(crypto_summary["total_value_chf"])
    stock_rows = [r for r in positions if r.get("asset_class", "").lower() in {"stock", "equity"}]
    etf_rows = [r for r in positions if r.get("asset_class", "").lower() == "etf"]
    stock_total = sum(d(r["market_value_chf"]) for r in stock_rows if r.get("market_value_chf"))
    etf_total = sum(d(r["market_value_chf"]) for r in etf_rows if r.get("market_value_chf"))
    equity_total = stock_total + etf_total
    missing_price_count = sum(1 for r in positions if not r.get("market_price_original"))
    missing_fx_count = sum(1 for r in positions if r.get("fx_status") == "missing_fx")
    incomplete_cost_count = sum(1 for r in positions if "cost_basis_uncertain" in (r.get("quality_warnings") or "") or not r.get("cost_basis_chf"))
    unvalued_count = missing_price_count + missing_fx_count
    latest_equity_price = max((r.get("price_date") or "" for r in positions), default="")
    alert_counts = conn.execute("SELECT priority, COUNT(*) AS c FROM alerts WHERE status='active' GROUP BY priority").fetchall()
    critical = sum(int(r["c"] or 0) for r in alert_counts if r["priority"] == "kritisch")
    quality = get_data_quality(conn)
    dq = "kritisch" if any(i["severity"] == "kritisch" and i["count"] != "0" for i in quality) else ("warnung" if any(i["severity"] == "warnung" and i["count"] != "0" for i in quality) else "ok")
    total = cash_total + crypto_total + equity_total


I did not identify any discrete, introduced issue that would clearly break existing behavior or the new PostFinance aggregation contract. The focused PostFinance sprint test suite also passes.