     1|from __future__ import annotations
     2|
     3|from dataclasses import dataclass, field
     4|from decimal import Decimal, InvalidOperation
     5|from sqlite3 import Connection
     6|
     7|from jarvis_finance.audit.log import record_audit_event
     8|from jarvis_finance.imports.common import stable_id, utc_now
     9|from jarvis_finance.market_data.catalog import CatalogEntryInput, upsert_catalog_entry
    10|from jarvis_finance.market_data.instruments import ensure_instrument_metadata_quality
    11|from jarvis_finance.ledger.positions import calculate_positions
    12|from jarvis_finance.quality.alerts import create_alert
    13|
    14|VALID_ASSET_CLASSES = {"stock", "etf"}
    15|VALID_CURRENCIES = {"CHF", "EUR", "USD"}
    16|VALID_CATEGORIES = {"Core", "Opportunity", "Unknown"}
    17|VALID_TRANSACTION_TYPES = {"buy", "partial_sell", "full_sell", "dividend", "etf_distribution", "fee", "manual_adjustment", "initial_snapshot", "initial_position_snapshot"}
    18|VALID_FX_STATUSES = {"ok", "not_needed", "missing", "manual_override", "manual_override_required"}
    19|
    20|
    21|@dataclass(frozen=True)
    22|class EquityManageResult:
    23|    instrument_id: str
    24|    account_id: str
    25|    transaction_id: str
    26|    warnings: list[str] = field(default_factory=list)
    27|
    28|
    29|def parse_decimal_text(value: str, *, field_name: str) -> Decimal:
    30|    text = str(value).strip()
    31|    if not text:
    32|        raise ValueError(f"{field_name} is required")
    33|    try:
    34|        dec = Decimal(text)
    35|    except (InvalidOperation, ValueError) as exc:
    36|        raise ValueError(f"{field_name} must be a Decimal string") from exc
    37|    if not dec.is_finite():
    38|        raise ValueError(f"{field_name} must be finite")
    39|    return dec
    40|
    41|
    42|def decimal_text(value: Decimal | None, places: str | None = None) -> str | None:
    43|    if value is None:
    44|        return None
    45|    if places is not None:
    46|        value = value.quantize(Decimal(places))
    47|    return format(value, "f")
    48|
    49|
    50|def _require_confirm(confirm: bool) -> None:
    51|    if not confirm:
    52|        raise ValueError("explicit confirm is required before saving")
    53|
    54|
    55|def _require_date(value: str) -> str:
    56|    text = str(value).strip()
    57|    parts = text.split("-")
    58|    if len(parts) != 3 or not all(part.isdigit() for part in parts):
    59|        raise ValueError("date must be ISO YYYY-MM-DD")
    60|    return text
    61|
    62|
    63|def _require_account(conn: Connection, account_id: str) -> str:
    64|    account_id = str(account_id).strip()
    65|    if not account_id:
    66|        raise ValueError("account is required")
    67|    row = conn.execute("SELECT account_id FROM accounts WHERE account_id=?", (account_id,)).fetchone()
    68|    if row is None:
    69|        raise ValueError("account not found")
    70|    return account_id
    71|
    72|
    73|def _require_instrument(conn: Connection, instrument_id: str) -> str:
    74|    instrument_id = str(instrument_id).strip()
    75|    row = conn.execute("SELECT instrument_id FROM instruments WHERE instrument_id=?", (instrument_id,)).fetchone()
    76|    if row is None:
    77|        raise ValueError("instrument not found")
    78|    return instrument_id
    79|
    80|
    81|

Use offset=81 to continue reading (showing 1-80 of 770 lines)


Explanation:
**Fixing syntax issues**

I’m noticing a syntax problem with the non-default after default in the `add_equity_initial_snapshot`. It looks like the cost default is coming before the snapshot with no default set, so I need to reorder it or decide if I should give the snapshot a default. It might be better to place the cost after the snapshot. Anyway, I need to patch this and then inspect the current page.


     1|from __future__ import annotations
     2|
     3|from decimal import Decimal
     4|
     5|from jarvis_finance.dashboard import data
     6|from jarvis_finance.dashboard.components.tables import show_table
     7|from jarvis_finance.equity.manage import add_equity_initial_snapshot, add_equity_transaction, add_manual_position_from_catalog, create_manual_catalog_entry, get_equity_management_options
     8|from jarvis_finance.fx.overrides import set_manual_fx_override
     9|from jarvis_finance.imports.instrument_candidates import confirm_candidate, defer_candidate, qwen_resolve_staged_candidates, reject_candidate, resolve_candidate
    10|from jarvis_finance.market_data.candidates import reject_mapping_candidate, select_mapping_candidate
    11|
    12|PAGE_TITLE = "Equity/ETF Manage"
    13|
    14|
    15|def _account_label(row: dict[str, str]) -> str:
    16|    return f"{row['platform_name']} / {row['account_name']} [{row['currency']} ]"
    17|
    18|
    19|def _instrument_label(row: dict[str, str]) -> str:
    20|    suffix = row.get("isin") or row.get("ticker") or row["instrument_id"]
    21|    return f"{row['name']} ({suffix})"
    22|
    23|
    24|def _selected(rows: list[dict[str, str]], label: str | None, label_fn) -> dict[str, str] | None:
    25|    if not label:
    26|        return None
    27|    for row in rows:
    28|        if label_fn(row) == label:
    29|            return row
    30|    return None
    31|
    32|
    33|def render(st, conn) -> None:
    34|    st.title("Equity/ETF Manage")
    35|    st.caption("Auditierbare manuelle Aktien-/ETF-Erfassung. Dashboard liest lokal; keine Broker-Dateien oder Live-APIs beim Rendern.")
    36|    st.warning("Keine stillen Überschreibungen: Initial Snapshots, Transaktionen und Korrekturen werden als bestätigte Ledger-Ereignisse mit Audit-Log gespeichert.")
    37|
    38|    options = get_equity_management_options(conn)
    39|    account_labels = [_account_label(row) for row in options["accounts"]]
    40|    instrument_labels = [_instrument_label(row) for row in options["instruments"]]
    41|    tabs = st.tabs(["Instrument Search / Add Position", "Mapping Review Queue", "Hinzufügen", "Kaufen", "Partial Sell", "Full Sell", "Dividende", "ETF-Ausschüttung", "Fee", "Korrigieren", "Review"])
    42|
    43|    with tabs[0]:
    44|        st.subheader("Instrument Search / Add Position")
    45|        st.caption("Lokaler Katalog zuerst; externe Lookups nur über freigegebene Provider. Mehrere Listings bleiben Auswahlpflicht.")
    46|        summary = data.get_instrument_catalog_summary(conn)
    47|        st.write(summary)
    48|        query = st.text_input("Suche nach ISIN, Symbol, Name, Provider-Symbol, Exchange oder Currency", key="catalog_search_query")
    49|        class_filter = st.selectbox("Filter", ["", "equity", "etf", "crypto", "cash"], key="catalog_search_class")
    50|        catalog_rows = data.get_instrument_catalog_entries(conn, query=query or None, asset_class=class_filter or None)
    51|        show_table(st, catalog_rows)
    52|        st.divider()
    53|        st.subheader("Katalogeintrag manuell anlegen")
    54|        c_asset = st.selectbox("Assetklasse", ["equity", "etf"], key="catalog_new_asset")
    55|        c_name = st.text_input("Name", key="catalog_new_name")
    56|        c_isin = st.text_input("ISIN", key="catalog_new_isin")
    57|        c_ticker = st.text_input("Ticker/Symbol", key="catalog_new_ticker")
    58|        c_exchange = st.text_input("Exchange", key="catalog_new_exchange")
    59|        c_currency = st.selectbox("Trading/Instrument Currency", ["CHF", "EUR", "USD"], key="catalog_new_currency")
    60|        c_provider = st.text_input("Provider", value="manual", key="catalog_new_provider")
    61|        c_provider_symbol = st.text_input("Provider-Symbol", key="catalog_new_provider_symbol")
    62|        c_hedge = st.selectbox("Hedge Status", ["unknown", "hedged", "unhedged"], key="catalog_new_hedge")
    63|        c_status = st.selectbox("Instrument Status", ["unknown", "active", "suspended", "delisted", "merged", "inactive"], key="catalog_new_status")
    64|        c_policy = st.selectbox("Valuation Policy", ["live_price", "last_known_price", "manual_value", "exclude_from_auto_price_update"], key="catalog_new_policy")
    65|        c_note = st.text_area("Katalog-Notiz (Pflicht)", key="catalog_new_note")
    66|        if st.button("Katalogeintrag speichern", key="catalog_new_save"):
    67|            try:
    68|                cid = create_manual_catalog_entry(conn, asset_class=c_asset, name=c_name, isin=c_isin, ticker=c_ticker, exchange=c_exchange, currency=c_currency, provider=c_provider, provider_symbol=c_provider_symbol, hedge_status=c_hedge, instrument_status=c_status, valuation_policy=c_policy, note=c_note)
    69|                st.success("Katalogeintrag gespeichert; Audit-Log geschrieben.")
    70|                st.write({"catalog_entry_id": cid})
    71|            except Exception as exc:
    72|                st.error(f"Katalogspeicherung abgelehnt: {exc}")
    73|        st.divider()
    74|        st.subheader("Position aus Katalog hinzufügen")
    75|        entry_labels = [f"{r.get('catalog_entry_id')} | {r.get('ticker') or ''} | {r.get('name')} | {r.get('isin') or ''} | {r.get('exchange') or ''} | {r.get('trading_currency') or ''}" for r in catalog_rows]
    76|        entry_label = st.selectbox("Katalog-Kandidat auswählen", entry_labels, key="catalog_position_entry") if entry_labels else None
    77|        pos_account_label = st.selectbox("Depot/Konto", account_labels, key="catalog_position_account") if account_labels else None
    78|        pos_type = st.selectbox("Positionstyp", ["initial_snapshot", "buy", "manual_adjustment"], key="catalog_position_type")
    79|        pos_qty = st.text_input("Menge als Decimal-Text", key="catalog_position_qty")
    80|        pos_date = st.date_input("Datum", key="catalog_position_date")
    81|        pos_currency = st.selectbox("Währung", ["CHF", "EUR", "USD"], key="catalog_position_currency")
    82|        pos_cost = st.text_input("Einstandspreis / Cost Basis optional", key="catalog_position_cost")
    83|        pos_fx_status = st.selectbox("FX-Status", ["not_needed", "missing", "manual_override", "manual_override_required"], key="catalog_position_fx_status")
    84|        pos_fx_rate = st.text_input("FX-Rate optional", key="catalog_position_fx_rate")
    85|        pos_fx_source = st.text_input("FX-Quelle optional", key="catalog_position_fx_source")
    86|        pos_note = st.text_area("Review-/Bestätigungsnotiz", key="catalog_position_note")
    87|        pos_confirm = st.checkbox("Ich bestätige diese einzelne Katalog-Position", key="catalog_position_confirm")
    88|        selected_pos_account = _selected(options["accounts"], pos_account_label, _account_label)
    89|        if st.button("Position aus Katalog speichern", key="catalog_position_save", type="primary"):
    90|            try:
    91|                if not entry_label or not selected_pos_account:
    92|                    raise ValueError("catalog entry and account are required")
    93|                result = add_manual_position_from_catalog(conn, catalog_entry_id=entry_label.split(" | ", 1)[0], account_id=selected_pos_account["account_id"], position_type=pos_type, quantity_text=pos_qty, trade_date=str(pos_date), currency=pos_currency, cost_basis_original_text=pos_cost or None, fx_status=pos_fx_status, fx_rate_to_chf_text=pos_fx_rate or None, fx_source=pos_fx_source or None, note=pos_note, confirm=bool(pos_confirm))
    94|                st.success("Position gespeichert und auditierbar erfasst.")
    95|                st.write({"instrument_id": result.instrument_id, "transaction_id": result.transaction_id, "warnings": result.warnings})
    96|            except Exception as exc:
    97|                st.error(f"Positionsspeicherung abgelehnt: {exc}")
    98|
    99|    with tabs[1]:
   100|        st.subheader("Mapping Review Queue: PostFinance / True Wealth")
   101|        st.caption("Review-only: Bestätigung schreibt nur Kandidatenstatus + Audit-Log. Kein Initial-Snapshot-Import aus dieser Ansicht.")
   102|        summary = data.get_instrument_import_candidate_summary(conn)
   103|        st.write(summary)
   104|        if st.button("Qwen Review-Hilfe auf sanitizte Kandidaten anwenden", key="instrument_candidate_qwen_resolve"):
   105|            try:
   106|                result = qwen_resolve_staged_candidates(conn)
   107|                st.success("Qwen Review-Hilfe ausgeführt; keine Buchung erstellt.")
   108|                st.write({"qwen_available": result.qwen_available, "model": result.model, "improved": result.improved, "manual_review_remaining": result.manual_review_remaining})
   109|            except Exception as exc:
   110|                st.error(f"Qwen Review-Hilfe abgelehnt: {exc}")
   111|        safe_rows = data.get_instrument_import_candidates(conn, status="exact_isin_match")
   112|        review_rows = [r for r in data.get_instrument_import_candidates(conn) if r.get("mapping_status") in {"needs_manual_review", "probable"}]
   113|        with st.expander("Gruppe 1: Sichere ISIN-Treffer — bereit zur Bestätigung", expanded=True):
   114|            st.caption("Anzeige ohne Mengen/Werte. Exact-ISIN bedeutet review-bereit, nicht importiert.")
   115|            show_table(st, safe_rows)
   116|            safe_labels = [f"{r['candidate_id']} | {r['platform']} | {r.get('proposed_ticker') or r.get('raw_ticker') or ''} | {r.get('proposed_isin') or r.get('raw_isin') or ''}" for r in safe_rows]
   117|            safe_selected = st.selectbox("Sicheren ISIN-Treffer auswählen", safe_labels, key="instrument_candidate_safe_select") if safe_labels else None
   118|            safe_note = st.text_area("Review-Notiz für sichere ISIN-Treffer", key="instrument_candidate_safe_note")
   119|            if st.button("Sicheren Treffer bestätigen", key="instrument_candidate_safe_confirm"):
   120|                try:
   121|                    if not safe_selected:
   122|                        raise ValueError("candidate is required")
   123|                    confirm_candidate(conn, safe_selected.split(" | ", 1)[0], note=safe_note or "Exact-ISIN Treffer manuell bestätigt")
   124|                    st.success("Kandidat bestätigt; Audit-Log geschrieben. Kein Portfolio-Import.")
   125|                except Exception as exc:
   126|                    st.error(f"Bestätigung abgelehnt: {exc}")
   127|            if st.button("Sicheren Treffer ablehnen", key="instrument_candidate_safe_reject"):
   128|                try:
   129|                    if not safe_selected:
   130|                        raise ValueError("candidate is required")
   131|                    reject_candidate(conn, safe_selected.split(" | ", 1)[0], note=safe_note or "Exact-ISIN Treffer abgelehnt")
   132|                    st.success("Kandidat abgelehnt; Audit-Log geschrieben.")
   133|                except Exception as exc:
   134|                    st.error(f"Ablehnung abgelehnt: {exc}")
   135|        with st.expander("Gruppe 2: Prüfung nötig — ISIN/Exchange/Währung ergänzen", expanded=True):
   136|            st.caption("Ticker allein bleibt blockiert. Mengen/Werte werden nicht angezeigt.")
   137|            show_table(st, review_rows)
   138|            labels = [f"{r['candidate_id']} | {r['platform']} | {r.get('proposed_ticker') or r.get('raw_ticker') or ''} | {r.get('proposed_isin') or r.get('raw_isin') or ''} | {r['mapping_status']}" for r in review_rows]
   139|            selected_label = st.selectbox("Kandidat auswählen", labels, key="instrument_candidate_select") if labels else None
   140|            review_note = st.text_area("Review-Notiz", key="instrument_candidate_note")
   141|            manual_isin = st.text_input("ISIN ergänzen/korrigieren", key="instrument_candidate_isin")
   142|            manual_ticker = st.text_input("Ticker korrigieren", key="instrument_candidate_ticker")
   143|            manual_exchange = st.text_input("Exchange setzen", key="instrument_candidate_exchange")
   144|            manual_currency = st.selectbox("Währung korrigieren", ["", "CHF", "EUR", "USD"], key="instrument_candidate_currency")
   145|            st.info("Als bestätigt speichern bedeutet nur: Status confirmed + Audit-Log. Produktiver Initial Snapshot bleibt blockiert bis explizite Freigabe.")
   146|            if st.button("Resolver erneut anwenden", key="instrument_candidate_resolve"):
   147|                try:
   148|                    if not selected_label:
   149|                        raise ValueError("candidate is required")
   150|                    result = resolve_candidate(conn, selected_label.split(" | ", 1)[0])
   151|                    st.success("Resolver ausgeführt; Status aktualisiert.")
   152|                    st.write(result)
   153|                except Exception as exc:
   154|                    st.error(f"Resolver abgelehnt: {exc}")
   155|            if st.button("Als bestätigt speichern", key="instrument_candidate_confirm"):
   156|                try:
   157|                    if not selected_label:
   158|                        raise ValueError("candidate is required")
   159|                    confirm_candidate(conn, selected_label.split(" | ", 1)[0], note=review_note, proposed_isin=manual_isin or None, proposed_ticker=manual_ticker or None, proposed_exchange=manual_exchange or None, proposed_currency=manual_currency or None)
   160|                    st.success("Kandidat bestätigt; Audit-Log geschrieben. Kein Portfolio-Import.")
   161|                except Exception as exc:
   162|                    st.error(f"Bestätigung abgelehnt: {exc}")
   163|            if st.button("Zurückstellen", key="instrument_candidate_defer"):
   164|                try:
   165|                    if not selected_label:
   166|                        raise ValueError("candidate is required")
   167|                    defer_candidate(conn, selected_label.split(" | ", 1)[0], note=review_note or "später prüfen")
   168|                    st.success("Kandidat zurückgestellt; Audit-Log geschrieben.")
   169|                except Exception as exc:
   170|                    st.error(f"Zurückstellen abgelehnt: {exc}")
   171|            if st.button("Ablehnen", key="instrument_candidate_reject"):
   172|                try:
   173|                    if not selected_label:
   174|                        raise ValueError("candidate is required")
   175|                    reject_candidate(conn, selected_label.split(" | ", 1)[0], note=review_note)
   176|                    st.success("Kandidat abgelehnt; Audit-Log geschrieben.")
   177|                except Exception as exc:
   178|                    st.error(f"Ablehnung abgelehnt: {exc}")
   179|        st.caption("Finaler Initial-Snapshot-Import bleibt absichtlich außerhalb dieser Review-Aktion und braucht separate Freigabe.")
   180|
   181|    with tabs[2]:
   182|        st.subheader("Aktie/ETF als Initial Snapshot hinzufügen")
   183|        account_label = st.selectbox("Depot/Konto", account_labels, key="equity_add_account") if account_labels else None
   184|        asset_class = st.selectbox("Assetklasse", ["stock", "ETF"], key="equity_add_class")
   185|        name = st.text_input("Name", key="equity_add_name")
   186|        isin = st.text_input("ISIN (primäre Identifikation)", key="equity_add_isin")
   187|        ticker = st.text_input("Ticker optional", key="equity_add_ticker")
   188|        exchange = st.text_input("Exchange optional", key="equity_add_exchange")
   189|        currency = st.selectbox("Währung", ["CHF", "EUR", "USD"], key="equity_add_currency")
   190|        quantity = st.text_input("Menge als Decimal-Text", key="equity_add_qty")
   191|        cost_basis = st.text_input("Einstandspreis / Cost Basis Originalwährung", key="equity_add_cost")
   192|        fx_rate = st.text_input("FX-Kurs zu CHF (bei EUR/USD)", key="equity_add_fx")
   193|        fx_source = st.text_input("FX-Quelle", key="equity_add_fx_source")
   194|        fx_status = st.selectbox("FX-Status", ["ok", "missing"], key="equity_add_fx_status")
   195|        snapshot_date = st.date_input("Snapshot-Datum", key="equity_add_date")
   196|        category = st.selectbox("Kategorie", ["Core", "Opportunity", "Unknown"], key="equity_add_category")
   197|        note = st.text_area("Notiz (Pflicht bei unvollständiger Historie)", key="equity_add_note")
   198|        with st.expander("ETF-spezifische Felder"):
   199|            ter = st.text_input("TER optional", key="equity_add_ter")
   200|            distribution_policy = st.text_input("ausschüttend/thesaurierend optional", key="equity_add_distribution")
   201|            index_name = st.text_input("Index optional", key="equity_add_index")
   202|            fund_domicile = st.text_input("Fondsdomizil optional", key="equity_add_domicile")
   203|            benchmark = st.text_input("Benchmark optional", key="equity_add_benchmark")
   204|        confirm = st.checkbox("Ich bestätige diese einzelne Änderung", key="equity_add_confirm")
   205|        selected_account = _selected(options["accounts"], account_label, _account_label)
   206|        st.write({"Aktion": "initial_position_snapshot", "Name": name, "ISIN": isin or "<fehlt>", "Ticker": ticker or "<fehlt>", "Währung": currency, "Datum": str(snapshot_date), "Hinweis": "Keine Massenänderung; Speicherung erst nach Bestätigung."})
   207|        if st.button("Bestätigt speichern", key="equity_add_save", type="primary"):
   208|            try:
   209|                if not selected_account:
   210|                    raise ValueError("account is required")
   211|                result = add_equity_initial_snapshot(
   212|                    conn,
   213|                    account_id=selected_account["account_id"],
   214|                    asset_class=asset_class,
   215|                    name=name,
   216|                    isin=isin,
   217|                    ticker=ticker,
   218|                    exchange=exchange,
   219|                    currency=currency,
   220|                    quantity_text=quantity,
   221|                    cost_basis_original_text=cost_basis,
   222|                    snapshot_date=str(snapshot_date),
   223|                    category=category,
   224|                    note=note,
   225|                    fx_rate_to_chf_text=fx_rate or None,
   226|                    fx_source=fx_source or None,
   227|                    fx_status=fx_status,
   228|                    ter_text=ter or None,
   229|                    distribution_policy=distribution_policy or None,
   230|                    index_name=index_name or None,
   231|                    fund_domicile=fund_domicile or None,
   232|                    benchmark=benchmark or None,
   233|                    confirm=bool(confirm),
   234|                )
   235|                st.success("Initial Snapshot gespeichert und auditierbar erfasst.")
   236|                st.write({"instrument_id": result.instrument_id, "transaction_id": result.transaction_id, "warnings": result.warnings})
   237|            except Exception as exc:
   238|                st.error(f"Speichern abgelehnt: {exc}")
   239|
   240|    def transaction_form(tab, title: str, tx_type: str) -> None:
   241|        with tab:
   242|            st.subheader(title)
   243|            account_label = st.selectbox("Depot/Konto", account_labels, key=f"equity_{tx_type}_account") if account_labels else None
   244|            instrument_label = st.selectbox("Instrument", instrument_labels, key=f"equity_{tx_type}_instrument") if instrument_labels else None
   245|            date_value = st.date_input("Datum", key=f"equity_{tx_type}_date")
   246|            qty_default = "0" if tx_type in {"dividend", "etf_distribution", "fee"} else ""
   247|            quantity = st.text_input("Menge als Decimal-Text", value=qty_default, key=f"equity_{tx_type}_qty")
   248|            gross = st.text_input("Brutto/Cost/Proceeds Originalwährung", key=f"equity_{tx_type}_gross")
   249|            currency = st.selectbox("Währung", ["CHF", "EUR", "USD"], key=f"equity_{tx_type}_currency")
   250|            fx_rate = st.text_input("FX-Kurs zu CHF (bei EUR/USD)", key=f"equity_{tx_type}_fx")
   251|            fx_source = st.text_input("FX-Quelle", key=f"equity_{tx_type}_fx_source")
   252|            fx_status = st.selectbox("FX-Status", ["ok", "missing"], key=f"equity_{tx_type}_fx_status")
   253|            note = st.text_area("Notiz / Grund", key=f"equity_{tx_type}_note")
   254|            confirm = st.checkbox("Ich bestätige diese Änderung", key=f"equity_{tx_type}_confirm")
   255|            selected_account = _selected(options["accounts"], account_label, _account_label)
   256|            selected_instrument = _selected(options["instruments"], instrument_label, _instrument_label)
   257|            st.write({"Aktion": tx_type, "Instrument": instrument_label, "Datum": str(date_value), "FX-Status": fx_status})
   258|            if st.button("Bestätigt speichern", key=f"equity_{tx_type}_save"):
   259|                try:
   260|                    if not selected_account or not selected_instrument:
   261|                        raise ValueError("account and instrument are required")
   262|                    result = add_equity_transaction(
   263|                        conn,
   264|                        account_id=selected_account["account_id"],
   265|                        instrument_id=selected_instrument["instrument_id"],
   266|                        transaction_type=tx_type,
   267|                        trade_date=str(date_value),
   268|                        quantity_text=quantity,
   269|                        gross_amount_original_text=gross,
   270|                        currency=currency,
   271|                        fx_rate_to_chf_text=fx_rate or None,
   272|                        fx_source=fx_source or None,
   273|                        fx_status=fx_status,
   274|                        note=note,
   275|                        confirm=bool(confirm),
   276|                    )
   277|                    st.success("Transaktion gespeichert und auditierbar erfasst.")
   278|                    st.write({"transaction_id": result.transaction_id, "warnings": result.warnings})
   279|                except Exception as exc:
   280|                    st.error(f"Speichern abgelehnt: {exc}")
   281|
   282|    transaction_form(tabs[3], "Kauf erfassen", "buy")
   283|    transaction_form(tabs[4], "Teilverkauf erfassen", "partial_sell")
   284|    transaction_form(tabs[5], "Vollverkauf erfassen", "full_sell")
   285|    transaction_form(tabs[6], "Dividende erfassen", "dividend")
   286|    transaction_form(tabs[7], "ETF-Ausschüttung erfassen", "etf_distribution")
   287|    transaction_form(tabs[8], "Fee erfassen", "fee")
   288|    transaction_form(tabs[9], "Korrektur als manual_adjustment", "manual_adjustment")
   289|
   290|    with tabs[10]:
   291|        st.subheader("Aktuelle Equity/ETF Übersicht")
   292|        show_table(st, data.get_positions(conn))
   293|        st.divider()
   294|        st.subheader("Instrument Price Mapping Review")
   295|        st.caption("Runtime-Review: Kandidaten ansehen und manuell bestätigen. Keine Live-API und keine Positionsänderung beim Rendern.")
   296|        review_rows = data.get_instrument_mapping_review(conn)
   297|        show_table(st, review_rows)
   298|        candidates_all = data.get_instrument_mapping_candidates(conn)
   299|        provider_filter = st.selectbox("Filter Provider", [""] + sorted({c.get("candidate_provider", "") for c in candidates_all if c.get("candidate_provider")}), key="mapping_candidate_provider_filter") if candidates_all else ""
   300|        exchange_filter = st.selectbox("Filter Exchange", [""] + sorted({c.get("candidate_exchange", "") for c in candidates_all if c.get("candidate_exchange")}), key="mapping_candidate_exchange_filter") if candidates_all else ""
   301|        currency_filter = st.selectbox("Filter Währung", [""] + sorted({c.get("candidate_currency", "") for c in candidates_all if c.get("candidate_currency")}), key="mapping_candidate_currency_filter") if candidates_all else ""
   302|        confidence_filter = st.selectbox("Filter Confidence", ["", "high", "medium", "low"], key="mapping_candidate_confidence_filter") if candidates_all else ""
   303|        hedge_filter = st.selectbox("Filter Hedge-Status", [""] + sorted({c.get("candidate_hedge_status", "") for c in candidates_all if c.get("candidate_hedge_status")}), key="mapping_candidate_hedge_filter") if candidates_all else ""
   304|        candidates = [c for c in candidates_all if (not provider_filter or c.get("candidate_provider") == provider_filter) and (not exchange_filter or c.get("candidate_exchange") == exchange_filter) and (not currency_filter or c.get("candidate_currency") == currency_filter) and (not confidence_filter or c.get("confidence") == confidence_filter) and (not hedge_filter or c.get("candidate_hedge_status") == hedge_filter)]
   305|        show_table(st, candidates)
   306|        candidate_labels = [f"{c['candidate_id']} | {c['candidate_provider']} | {c['candidate_provider_symbol']} | {c['candidate_exchange']} | {c['candidate_currency']} | score={c.get('ranking_score','')} | {c.get('ranking_mark','')} | {c['confidence']} | {c['review_status']}" for c in candidates]
   307|        selected_candidate_label = st.selectbox("Mapping-Kandidat auswählen", candidate_labels, key="mapping_candidate_select") if candidate_labels else None
   308|        mapping_note = st.text_area("Bestätigungsnotiz für Mapping-Auswahl", key="mapping_candidate_note")
   309|        st.info("Aktionen: Kandidat auswählen, Kandidat ablehnen, manuell erfassen über Tab 'Instrument Search / Add Position', oder später prüfen durch Nicht-Auswahl.")
   310|        if st.button("Ausgewählten Mapping-Kandidaten bestätigen", key="mapping_candidate_confirm"):
   311|            try:
   312|                if not selected_candidate_label:
   313|                    raise ValueError("candidate is required")
   314|                candidate_id = selected_candidate_label.split(" | ", 1)[0]
   315|                mapping_id = select_mapping_candidate(conn, candidate_id=candidate_id, note=mapping_note, created_by="dashboard")
   316|                st.success("Mapping-Kandidat bestätigt; Audit-Log geschrieben.")
   317|                st.write({"mapping_id": mapping_id})
   318|            except Exception as exc:
   319|                st.error(f"Mapping-Auswahl abgelehnt: {exc}")
   320|        if st.button("Ausgewählten Mapping-Kandidaten ablehnen", key="mapping_candidate_reject"):
   321|            try:
   322|                if not selected_candidate_label:
   323|                    raise ValueError("candidate is required")
   324|                candidate_id = selected_candidate_label.split(" | ", 1)[0]
   325|                reject_mapping_candidate(conn, candidate_id=candidate_id, note=mapping_note, created_by="dashboard")
   326|                st.success("Mapping-Kandidat abgelehnt; Audit-Log geschrieben.")
   327|            except Exception as exc:
   328|                st.error(f"Mapping-Ablehnung abgelehnt: {exc}")
   329|        st.caption("Manuell erfassen: neuen Katalogeintrag im Tab 'Instrument Search / Add Position' speichern. Keine Portfolio-Transaktion wird durch Mapping Review geändert.")
   330|        st.divider()
   331|        st.subheader("FX Override Review")
   332|        st.caption("Historische FX-Rates nur manuell mit Quelle/Notiz erfassen. Keine Rates ohne bewusste Speicherung.")
   333|        fx_rows = data.get_fx_override_requirements(conn)
   334|        show_table(st, fx_rows)
   335|        fx_labels = [f"{r['base_currency']}/{r['quote_currency']} {r['rate_date']} ({r['fx_status']})" for r in fx_rows]
   336|        fx_label = st.selectbox("FX-Paar/Datum", fx_labels, key="fx_override_select") if fx_labels else None
   337|        fx_rate = st.text_input("FX-Rate zu CHF", key="fx_override_rate")
   338|        fx_note = st.text_area("FX-Quelle/Notiz (Pflicht)", key="fx_override_note")
   339|        if st.button("Manual FX Override speichern", key="fx_override_save"):
   340|            try:
   341|                if not fx_label:
   342|                    raise ValueError("fx pair/date is required")
   343|                pair, date_part = fx_label.split(" ", 1)
   344|                base, quote = pair.split("/", 1)
   345|                rate_date = date_part.split(" ", 1)[0]
   346|                set_manual_fx_override(conn, base_currency=base, quote_currency=quote, rate_date=rate_date, rate=Decimal(fx_rate), note=fx_note, created_by="dashboard")
   347|                st.success("Manual FX Override gespeichert und auditierbar erfasst.")
   348|            except Exception as exc:
   349|                st.error(f"FX Override abgelehnt: {exc}")
   350|


Explanation:
**Adjusting implementation details**

I need to implement certain features for user mode, ensuring that IDs aren't visible on the page. Perhaps I can adjust tab0 to hide them as well. Testing will be essential to ensure everything runs smoothly. I should also take the time to understand the test fixtures better to prepare for effective testing. It's all about getting the details right to enhance the user experience!


     1|from __future__ import annotations
     2|
     3|from decimal import Decimal
     4|
     5|import pytest
     6|
     7|from jarvis_finance.equity.manage import (
     8|    add_equity_initial_snapshot,
     9|    add_equity_transaction,
    10|    get_equity_management_options,
    11|)
    12|from jarvis_finance.ledger.positions import calculate_positions
    13|from jarvis_finance.storage.database import connect_memory
    14|from jarvis_finance.storage.migrations import apply_migrations
    15|
    16|
    17|def setup_conn():
    18|    conn = connect_memory()
    19|    apply_migrations(conn)
    20|    return conn
    21|
    22|
    23|def seed_account(conn, platform_name: str = "Synthetic PostFinance") -> str:
    24|    platform_id = f"platform-{platform_name.lower().replace(' ', '-')}"
    25|    account_id = f"account-{platform_name.lower().replace(' ', '-')}"
    26|    conn.execute(
    27|        "INSERT INTO platforms(platform_id, name, platform_type, country, default_currency, created_at) VALUES (?, ?, 'broker', 'CH', 'CHF', '2026-01-01')",
    28|        (platform_id, platform_name),
    29|    )
    30|    conn.execute(
    31|        "INSERT INTO accounts(account_id, platform_id, account_name, account_type, currency, created_at) VALUES (?, ?, 'Synthetic Depot', 'brokerage', 'CHF', '2026-01-01')",
    32|        (account_id, platform_id),
    33|    )
    34|    conn.commit()
    35|    return account_id
    36|
    37|
    38|def audit_count(conn, action: str) -> int:
    39|    return conn.execute("SELECT COUNT(*) AS c FROM audit_log WHERE action=?", (action,)).fetchone()["c"]
    40|
    41|
    42|def test_add_stock_initial_snapshot_creates_instrument_transaction_and_audit() -> None:
    43|    conn = setup_conn()
    44|    account_id = seed_account(conn)
    45|
    46|    result = add_equity_initial_snapshot(
    47|        conn,
    48|        account_id=account_id,
    49|        asset_class="stock",
    50|        name="Synthetic Nestle",
    51|        isin="CH0038863350",
    52|        ticker="NESN",
    53|        exchange="SIX",
    54|        currency="CHF",
    55|        quantity_text="3.5",
    56|        cost_basis_original_text="350.00",
    57|        snapshot_date="2025-12-31",
    58|        category="Core",
    59|        note="synthetic incomplete history accepted",
    60|        confirm=True,
    61|    )
    62|
    63|    tx = conn.execute("SELECT * FROM transactions WHERE transaction_id=?", (result.transaction_id,)).fetchone()
    64|    instrument = conn.execute("SELECT * FROM instruments WHERE instrument_id=?", (result.instrument_id,)).fetchone()
    65|    assert tx["transaction_type"] == "initial_position_snapshot"
    66|    assert tx["quantity"] == "3.5"
    67|    assert tx["gross_amount_original"] == "350.00"
    68|    assert tx["fx_rate_to_chf"] == "1"
    69|    assert tx["fx_status"] == "ok"
    70|    assert instrument["isin"] == "CH0038863350"
    71|    assert instrument["asset_class"] == "stock"
    72|    assert instrument["position_category"] == "Core"
    73|    assert audit_count(conn, "equity_initial_position_snapshot") == 1
    74|    assert result.warnings == []
    75|
    76|
    77|def test_add_etf_initial_snapshot_prepares_optional_etf_fields() -> None:
    78|    conn = setup_conn()
    79|    account_id = seed_account(conn, "Synthetic True Wealth")
    80|
    81|    result = add_equity_initial_snapshot(
    82|        conn,
    83|        account_id=account_id,
    84|        asset_class="ETF",
    85|        name="Synthetic World ETF",
    86|        isin="IE00B4L5Y983",
    87|        ticker="SWLD",
    88|        exchange="LSE",
    89|        currency="USD",
    90|        quantity_text="10",
    91|        cost_basis_original_text="1000.00",
    92|        snapshot_date="2025-12-31",
    93|        category="Core",
    94|        note="synthetic ETF snapshot with known FX",
    95|        fx_rate_to_chf_text="0.91",
    96|        fx_source="synthetic fixture",
    97|        ter_text="0.20",
    98|        distribution_policy="accumulating",
    99|        index_name="MSCI World Synthetic",
   100|        fund_domicile="IE",
   101|        benchmark="Synthetic Benchmark",
   102|        confirm=True,
   103|    )
   104|
   105|    instrument = conn.execute("SELECT * FROM instruments WHERE instrument_id=?", (result.instrument_id,)).fetchone()
   106|    tx = conn.execute("SELECT * FROM transactions WHERE transaction_id=?", (result.transaction_id,)).fetchone()
   107|    assert instrument["ter"] == "0.20"
   108|    assert instrument["distribution_policy"] == "accumulating"
   109|    assert instrument["index_name"] == "MSCI World Synthetic"
   110|    assert instrument["fund_domicile"] == "IE"
   111|    assert instrument["benchmark"] == "Synthetic Benchmark"
   112|    assert tx["currency_original"] == "USD"
   113|    assert tx["fx_rate_to_chf"] == "0.91"
   114|    assert tx["gross_amount_chf"] == "910.0000"
   115|
   116|
   117|def test_usd_stock_requires_fx_or_explicit_missing_status_alert() -> None:
   118|    conn = setup_conn()
   119|    account_id = seed_account(conn, "Synthetic Raiffeisen")
   120|
   121|    result = add_equity_initial_snapshot(
   122|        conn,
   123|        account_id=account_id,
   124|        asset_class="stock",
   125|        name="Synthetic US Stock",
   126|        isin="US0378331005",
   127|        ticker="AAPL",
   128|        exchange="NASDAQ",
   129|        currency="USD",
   130|        quantity_text="2",
   131|        cost_basis_original_text="400.00",
   132|        snapshot_date="2025-12-31",
   133|        category="Opportunity",
   134|        note="synthetic missing FX accepted for review",
   135|        fx_status="missing",
   136|        confirm=True,
   137|    )
   138|
   139|    tx = conn.execute("SELECT * FROM transactions WHERE transaction_id=?", (result.transaction_id,)).fetchone()
   140|    assert tx["fx_status"] == "missing"
   141|    assert tx["gross_amount_chf"] is None
   142|    assert "missing_fx" in result.warnings
   143|    assert conn.execute("SELECT COUNT(*) AS c FROM alerts WHERE rule_id='missing_fx'").fetchone()["c"] == 1
   144|
   145|
   146|def test_sell_reduces_position_and_blocks_negative() -> None:
   147|    conn = setup_conn()
   148|    account_id = seed_account(conn)
   149|    snap = add_equity_initial_snapshot(
   150|        conn,
   151|        account_id=account_id,
   152|        asset_class="stock",
   153|        name="Synthetic Sellable",
   154|        isin="CH0000000001",
   155|        ticker="SYN",
   156|        exchange="SIX",
   157|        currency="CHF",
   158|        quantity_text="5",
   159|        cost_basis_original_text="500",
   160|        snapshot_date="2025-12-31",
   161|        category="Unknown",
   162|        note="synthetic initial",
   163|        confirm=True,
   164|    )
   165|
   166|    add_equity_transaction(
   167|        conn,
   168|        account_id=account_id,
   169|        instrument_id=snap.instrument_id,
   170|        transaction_type="partial_sell",
   171|        trade_date="2026-01-10",
   172|        quantity_text="2",
   173|        gross_amount_original_text="220",
   174|        currency="CHF",
   175|        note="synthetic partial sell",
   176|        confirm=True,
   177|    )
   178|    position = calculate_positions(conn).positions[(account_id, snap.instrument_id)]
   179|    assert position.quantity == Decimal("3")
   180|
   181|    with pytest.raises(ValueError, match="negative"):
   182|        add_equity_transaction(
   183|            conn,
   184|            account_id=account_id,
   185|            instrument_id=snap.instrument_id,
   186|            transaction_type="partial_sell",
   187|            trade_date="2026-01-11",
   188|            quantity_text="10",
   189|            gross_amount_original_text="1000",
   190|            currency="CHF",
   191|            note="synthetic oversell",
   192|            confirm=True,
   193|        )
   194|
   195|
   196|def test_dividend_does_not_change_quantity_and_manual_adjustment_requires_note() -> None:
   197|    conn = setup_conn()
   198|    account_id = seed_account(conn)
   199|    snap = add_equity_initial_snapshot(
   200|        conn,
   201|        account_id=account_id,
   202|        asset_class="ETF",
   203|        name="Synthetic Income ETF",
   204|        isin="IE0000000001",
   205|        ticker="INC",
   206|        exchange="SIX",
   207|        currency="CHF",
   208|        quantity_text="7",
   209|        cost_basis_original_text="700",
   210|        snapshot_date="2025-12-31",
   211|        category="Core",
   212|        note="synthetic initial",
   213|        confirm=True,
   214|    )
   215|
   216|    add_equity_transaction(
   217|        conn,
   218|        account_id=account_id,
   219|        instrument_id=snap.instrument_id,
   220|        transaction_type="dividend",
   221|        trade_date="2026-02-01",
   222|        quantity_text="0",
   223|        gross_amount_original_text="12.50",
   224|        currency="CHF",
   225|        note="synthetic dividend",
   226|        confirm=True,
   227|    )
   228|    assert calculate_positions(conn).positions[(account_id, snap.instrument_id)].quantity == Decimal("7")
   229|
   230|    with pytest.raises(ValueError, match="note"):
   231|        add_equity_transaction(
   232|            conn,
   233|            account_id=account_id,
   234|            instrument_id=snap.instrument_id,
   235|            transaction_type="manual_adjustment",
   236|            trade_date="2026-02-02",
   237|            quantity_text="1",
   238|            gross_amount_original_text="0",
   239|            currency="CHF",
   240|            note="",
   241|            confirm=True,
   242|        )
   243|
   244|
   245|def test_full_sell_requires_exact_current_quantity_and_zeros_position() -> None:
   246|    conn = setup_conn()
   247|    account_id = seed_account(conn)
   248|    snap = add_equity_initial_snapshot(
   249|        conn,
   250|        account_id=account_id,
   251|        asset_class="stock",
   252|        name="Synthetic Full Sell",
   253|        isin="CH0000000002",
   254|        ticker="FUL",
   255|        exchange="SIX",
   256|        currency="CHF",
   257|        quantity_text="4",
   258|        cost_basis_original_text="400",
   259|        snapshot_date="2025-12-31",
   260|        category="Unknown",
   261|        note="synthetic initial",
   262|        confirm=True,
   263|    )
   264|
   265|    with pytest.raises(ValueError, match="full_sell quantity"):
   266|        add_equity_transaction(
   267|            conn,
   268|            account_id=account_id,
   269|            instrument_id=snap.instrument_id,
   270|            transaction_type="full_sell",
   271|            trade_date="2026-01-10",
   272|            quantity_text="3",
   273|            gross_amount_original_text="330",
   274|            currency="CHF",
   275|            note="synthetic wrong full sell",
   276|            confirm=True,
   277|        )
   278|
   279|    add_equity_transaction(
   280|        conn,
   281|

Use offset=281 to continue reading (showing 1-280 of 304 lines)


   280|        conn,
   281|        account_id=account_id,
   282|        instrument_id=snap.instrument_id,
   283|        transaction_type="full_sell",
   284|        trade_date="2026-01-11",
   285|        quantity_text="4",
   286|        gross_amount_original_text="440",
   287|        currency="CHF",
   288|        note="synthetic full sell",
   289|        confirm=True,
   290|    )
   291|
   292|    position = calculate_positions(conn).positions[(account_id, snap.instrument_id)]
   293|    assert position.quantity == Decimal("0")
   294|    assert audit_count(conn, "equity_full_sell") == 1
   295|
   296|
   297|def test_equity_management_options_and_dashboard_page_import() -> None:
   298|    conn = setup_conn()
   299|    seed_account(conn, "Synthetic PostFinance")
   300|    options = get_equity_management_options(conn)
   301|    assert options["accounts"]
   302|    from jarvis_finance.dashboard.pages import PAGES
   303|
   304|    assert "Equity/ETF Manage" in [page.PAGE_TITLE for page in PAGES]
   305|


    80|
    81|def _normalize_asset_class(asset_class: str) -> str:
    82|    value = str(asset_class).strip().lower()
    83|    if value not in VALID_ASSET_CLASSES:
    84|        raise ValueError("asset_class must be stock or ETF")
    85|    return value
    86|
    87|
    88|def _require_currency(currency: str) -> str:
    89|    value = str(currency).strip().upper()
    90|    if value not in VALID_CURRENCIES:
    91|        raise ValueError("currency must be CHF, EUR or USD")
    92|    return value
    93|
    94|
    95|def _require_note(note: str, *, reason: str) -> str:
    96|    text = str(note or "").strip()
    97|    if not text:
    98|        raise ValueError(f"note is required for {reason}")
    99|    return text
   100|
   101|
   102|def _find_instrument(conn: Connection, *, isin: str, ticker: str, name: str, currency: str) -> str | None:
   103|    if isin:
   104|        row = conn.execute("SELECT instrument_id FROM instruments WHERE isin=?", (isin,)).fetchone()
   105|        if row:
   106|            return row["instrument_id"]
   107|    if ticker:
   108|        row = conn.execute("SELECT instrument_id FROM instruments WHERE upper(ticker)=upper(?) AND currency=?", (ticker, currency)).fetchone()
   109|        if row:
   110|            return row["instrument_id"]
   111|    row = conn.execute("SELECT instrument_id FROM instruments WHERE name=? AND currency=?", (name, currency)).fetchone()
   112|    return row["instrument_id"] if row else None
   113|
   114|
   115|def _ensure_instrument(
   116|    conn: Connection,
   117|    *,
   118|    asset_class: str,
   119|    name: str,
   120|    isin: str,
   121|    ticker: str,
   122|    exchange: str,
   123|    currency: str,
   124|    category: str,
   125|    note: str,
   126|    ter_text: str | None = None,
   127|    distribution_policy: str | None = None,
   128|    index_name: str | None = None,
   129|    fund_domicile: str | None = None,
   130|    benchmark: str | None = None,
   131|) -> str:
   132|    isin = str(isin or "").strip().upper()
   133|    ticker = str(ticker or "").strip().upper()
   134|    name = str(name or "").strip()
   135|    if not name:
   136|        raise ValueError("name is required")
   137|    if not isin and not ticker:
   138|        raise ValueError("ISIN or ticker is required")
   139|    if category not in VALID_CATEGORIES:
   140|        raise ValueError("category must be Core, Opportunity or Unknown")
   141|    ter = None
   142|    if ter_text not in {None, ""}:
   143|        ter = decimal_text(parse_decimal_text(str(ter_text), field_name="TER"))
   144|    existing = _find_instrument(conn, isin=isin, ticker=ticker, name=name, currency=currency)
   145|    now = utc_now()
   146|    if existing:
   147|        conn.execute(
   148|            """
   149|            UPDATE instruments
   150|            SET name=COALESCE(NULLIF(?, ''), name), ticker=COALESCE(NULLIF(?, ''), ticker),
   151|                exchange=COALESCE(NULLIF(?, ''), exchange), position_category=?, ter=COALESCE(?, ter),
   152|                distribution_policy=COALESCE(NULLIF(?, ''), distribution_policy), index_name=COALESCE(NULLIF(?, ''), index_name),
   153|                fund_domicile=COALESCE(NULLIF(?, ''), fund_domicile), benchmark=COALESCE(NULLIF(?, ''), benchmark),
   154|                updated_at=?
   155|            WHERE instrument_id=?
   156|            """,
   157|            (name, ticker, exchange, category, ter, distribution_policy or "", index_name or "", fund_domicile or "", benchmark or "", now, existing),
   158|        )
   159|        return existing
   160|    instrument_id = stable_id("instrument", isin or ticker or name, currency)
   161|    conn.execute(
   162|        """
   163|        INSERT INTO instruments(
   164|            instrument_id, asset_class, name, ticker, isin, exchange, currency,
   165|            notes, position_category, ter, distribution_policy, index_name, fund_domicile, benchmark, created_at
   166|        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
   167|        """,
   168|        (instrument_id, asset_class, name, ticker, isin, exchange, currency, note, category, ter, distribution_policy, index_name, fund_domicile, benchmark, now),
   169|    )
   170|    return instrument_id
   171|
   172|
   173|def _fx_values(conn: Connection, *, currency: str, gross: Decimal, fee: Decimal, tax: Decimal, fx_rate_text: str | None, fx_source: str | None, fx_status: str, entity_hint: str) -> tuple[str, str | None, str | None, str | None, str | None, list[str]]:
   174|    warnings: list[str] = []
   175|    if currency == "CHF":
   176|        fx = Decimal("1")
   177|        status = "ok"
   178|        source = fx_source or "CHF base currency"
   179|    else:
   180|        status = str(fx_status or "").strip().lower()
   181|        if fx_rate_text:
   182|            fx = parse_decimal_text(fx_rate_text, field_name="fx_rate_to_chf")
   183|            if fx <= 0:
   184|                raise ValueError("fx_rate_to_chf must be > 0")
   185|            status = "ok"
   186|            source = fx_source or "manual"
   187|        elif status in {"missing", "manual_override_required"}:
   188|            fx = None
   189|            source = fx_source or status
   190|            warnings.append("missing_fx")
   191|            create_alert(
   192|                conn,
   193|                priority="kritisch",
   194|                category="equity",
   195|                entity_type="instrument",
   196|                entity_id=entity_hint,
   197|                rule_id="missing_fx",
   198|                message="Historic FX is missing; CHF value is incomplete.",
   199|                evidence={"currency": currency},
   200|                fingerprint="missing_fx",
   201|            )
   202|        else:
   203|            raise ValueError("FX rate is required for foreign currency unless fx_status=missing/manual_override_required")
   204|    if fx is None:
   205|        return status or "missing", None, source, None, None, warnings
   206|    gross_chf = gross * fx
   207|    fee_chf = fee * fx
   208|    tax_chf = tax * fx
   209|    net_chf = gross_chf - fee_chf - tax_chf
   210|    return status or "ok", decimal_text(fx), source, decimal_text(gross_chf, "0.0001"), decimal_text(net_chf, "0.0001"), warnings
   211|
   212|
   213|def _insert_transaction(
   214|    conn: Connection,
   215|    *,
   216|    transaction_type: str,
   217|    account_id: str,
   218|    instrument_id: str,
   219|    trade_date: str,
   220|    quantity: Decimal | None,
   221|    gross: Decimal,
   222|    fee: Decimal,
   223|    tax: Decimal,
   224|    currency: str,
   225|    fx_rate_to_chf_text: str | None,
   226|    fx_source: str | None,
   227|    fx_status: str,
   228|    note: str,
   229|) -> tuple[str, list[str]]:
   230|    now = utc_now()
   231|    status, fx_text, fx_source_value, gross_chf, net_chf, warnings = _fx_values(
   232|        conn,
   233|        currency=currency,
   234|        gross=gross,
   235|        fee=fee,
   236|        tax=tax,
   237|        fx_rate_text=fx_rate_to_chf_text,
   238|        fx_source=fx_source,
   239|        fx_status=fx_status,
   240|        entity_hint=instrument_id,
   241|    )
   242|    tx_id = stable_id("tx", transaction_type, account_id, instrument_id, trade_date, decimal_text(quantity) if quantity is not None else "", decimal_text(gross), now)
   243|    conn.execute(
   244|        """
   245|        INSERT INTO transactions(
   246|            transaction_id, transaction_type, account_id, instrument_id, trade_date,
   247|            quantity, gross_amount_original, fee_original, tax_original, net_amount_original,
   248|            currency_original, fx_rate_to_chf, fx_source, fx_status, gross_amount_chf,
   249|            fee_chf, tax_chf, net_amount_chf, source_type, source_id, is_confirmed,
   250|            quality_status, notes, created_at
   251|        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'manual_dashboard', ?, 1, ?, ?, ?)
   252|        """,
   253|        (
   254|            tx_id,
   255|            transaction_type,
   256|            account_id,
   257|            instrument_id,
   258|            trade_date,
   259|            decimal_text(quantity) if quantity is not None else None,
   260|

Use offset=260 to continue reading (showing 80-259 of 770 lines)


   530|    if transaction_type in {"buy", "partial_sell", "full_sell", "initial_position_snapshot"} and qty <= 0:
   531|        raise ValueError("quantity must be > 0")
   532|    if transaction_type in {"dividend", "etf_distribution", "fee"}:
   533|        qty = Decimal("0")
   534|    if transaction_type in {"partial_sell", "full_sell"}:
   535|        current = calculate_positions(conn).positions.get((account_id, instrument_id))
   536|        current_qty = current.quantity if current else Decimal("0")
   537|        if qty > current_qty:
   538|            raise ValueError("sell would create negative position")
   539|        if transaction_type == "full_sell" and qty != current_qty:
   540|            raise ValueError("full_sell quantity must match current position")
   541|    tx_id, warnings = _insert_transaction(
   542|        conn,
   543|        transaction_type=transaction_type,
   544|        account_id=account_id,
   545|        instrument_id=instrument_id,
   546|        trade_date=trade_date,
   547|        quantity=qty,
   548|        gross=gross,
   549|        fee=fee,
   550|        tax=tax,
   551|        currency=currency,
   552|        fx_rate_to_chf_text=fx_rate_to_chf_text,
   553|        fx_source=fx_source,
   554|        fx_status=fx_status,
   555|        note=note,
   556|    )
   557|    record_audit_event(
   558|        conn,
   559|        source="equity_manage",
   560|        action=f"equity_{transaction_type}",
   561|        entity_type="transaction",
   562|        entity_id=tx_id,
   563|        new_values={"account_id": account_id, "instrument_id": instrument_id, "transaction_type": transaction_type},
   564|        user_text_note=note,
   565|        confirmed=True,
   566|        created_by="dashboard",
   567|    )
   568|    conn.commit()
   569|    return EquityManageResult(instrument_id=instrument_id, account_id=account_id, transaction_id=tx_id, warnings=warnings)
   570|
   571|
   572|def _ensure_instrument_from_catalog(conn: Connection, *, catalog_entry_id: str, note: str) -> str:
   573|    row = conn.execute("SELECT * FROM instrument_catalog_entries WHERE catalog_entry_id=?", (catalog_entry_id,)).fetchone()
   574|    if row is None:
   575|        raise ValueError("catalog entry not found")
   576|    asset_class = "etf" if row["asset_class"] == "etf" else "stock"
   577|    currency = _require_currency(row["instrument_currency"] or row["trading_currency"] or "CHF")
   578|    isin = (row["isin"] or "").strip().upper()
   579|    ticker = (row["ticker"] or "").strip().upper()
   580|    exchange = (row["exchange"] or "").strip().upper()
   581|    existing = None
   582|    if isin:
   583|        existing = conn.execute("SELECT instrument_id FROM instruments WHERE isin=? AND COALESCE(exchange,'')=? AND currency=?", (isin, exchange, currency)).fetchone()
   584|    if existing is None and ticker and exchange:
   585|        existing = conn.execute("SELECT instrument_id FROM instruments WHERE upper(ticker)=upper(?) AND COALESCE(exchange,'')=? AND currency=?", (ticker, exchange, currency)).fetchone()
   586|    if existing:
   587|        instrument_id = existing["instrument_id"]
   588|    else:
   589|        instrument_id = stable_id("instrument", isin or ticker or row["name"], exchange, currency)
   590|        conn.execute(
   591|            """
   592|            INSERT INTO instruments(
   593|                instrument_id, asset_class, name, ticker, isin, exchange, currency,
   594|                notes, is_currency_hedged, hedged_to_currency, hedge_status,
   595|                trading_currency, instrument_status, valuation_policy, created_at
   596|            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
   597|            """,
   598|            (
   599|                instrument_id, asset_class, row["name"], ticker, isin, exchange, currency, note,
   600|                (1 if row["is_currency_hedged"] else 0), row["hedged_to_currency"], row["hedge_status"] or "unknown",
   601|                row["trading_currency"], row["instrument_status"] or "unknown", row["valuation_policy"] or "live_price", utc_now(),
   602|            ),
   603|        )
   604|    if row["provider_symbol"]:
   605|        from jarvis_finance.market_data.mappings import confirm_instrument_price_mapping
   606|        confirm_instrument_price_mapping(
   607|            conn,
   608|            instrument_id=instrument_id,
   609|            provider=row["provider"] or "manual",
   610|            provider_symbol=row["provider_symbol"],
   611|            provider_market=row["provider_market"] or exchange,
   612|            confidence=row["source_confidence"] or "low",
   613|            note=note,
   614|            exchange=exchange,
   615|            currency=row["trading_currency"] or currency,
   616|            hedge_status=row["hedge_status"] if row["hedge_status"] != "unknown" else None,
   617|            hedged_to_currency=row["hedged_to_currency"],
   618|            instrument_status=row["instrument_status"] if row["instrument_status"] != "unknown" else None,
   619|            valuation_policy=row["valuation_policy"],
   620|            trading_currency=row["trading_currency"] or currency,
   621|            created_by="dashboard",
   622|        )
   623|    else:
   624|        create_alert(conn, priority="warnung", category="market_data", entity_type="instrument", entity_id=instrument_id, rule_id="missing_provider_symbol", message="Manual catalog position has no provider symbol; market price unavailable.", evidence={"catalog_entry_id": catalog_entry_id}, fingerprint="missing_provider_symbol")
   625|    ensure_instrument_metadata_quality(conn, instrument_id=instrument_id)
   626|    return instrument_id
   627|
   628|
   629|def add_manual_position_from_catalog(
   630|    conn: Connection,
   631|    *,
   632|    catalog_entry_id: str,
   633|    account_id: str,
   634|    position_type: str,
   635|    quantity_text: str,
   636|    trade_date: str,
   637|    currency: str,
   638|    note: str,
   639|    confirm: bool,
   640|    cost_basis_original_text: str | None = None,
   641|    fx_status: str = "missing",
   642|    fx_rate_to_chf_text: str | None = None,
   643|    fx_source: str | None = None,
   644|) -> EquityManageResult:
   645|    _require_confirm(confirm)
   646|    note = _require_note(note, reason="manual position add")
   647|    account_id = _require_account(conn, account_id)
   648|    position_type = str(position_type or "").strip()
   649|    if position_type == "initial_snapshot":
   650|        transaction_type = "initial_position_snapshot"
   651|    elif position_type in {"buy", "manual_adjustment"}:
   652|        transaction_type = position_type
   653|    else:
   654|        raise ValueError("position_type must be initial_snapshot, buy or manual_adjustment")
   655|    if fx_status not in VALID_FX_STATUSES:
   656|        raise ValueError("invalid fx_status")
   657|    currency = _require_currency(currency)
   658|    trade_date = _require_date(trade_date)
   659|    qty = parse_decimal_text(quantity_text, field_name="quantity")
   660|    if qty <= 0:
   661|        raise ValueError("quantity must be > 0")
   662|    warnings: list[str] = []
   663|    if cost_basis_original_text in {None, ""}:
   664|        gross = Decimal("0")
   665|        warnings.append("cost_basis_uncertain")
   666|    else:
   667|        gross = parse_decimal_text(str(cost_basis_original_text), field_name="cost basis")
   668|    instrument_id = _ensure_instrument_from_catalog(conn, catalog_entry_id=catalog_entry_id, note=note)
   669|    if transaction_type == "initial_position_snapshot":
   670|        existing_position = calculate_positions(conn).positions.get((account_id, instrument_id))
   671|        if existing_position and existing_position.quantity != 0:
   672|            raise ValueError("initial snapshot would overwrite an existing position; use manual_adjustment")
   673|    tx_id, tx_warnings = _insert_transaction(
   674|        conn,
   675|        transaction_type=transaction_type,
   676|        account_id=account_id,
   677|        instrument_id=instrument_id,
   678|        trade_date=trade_date,
   679|        quantity=qty,
   680|        gross=gross,
   681|        fee=Decimal("0"),
   682|        tax=Decimal("0"),
   683|        currency=currency,
   684|        fx_rate_to_chf_text=fx_rate_to_chf_text,
   685|        fx_source=fx_source,
   686|        fx_status="ok" if currency == "CHF" and fx_status == "not_needed" else fx_status,
   687|        note=note,
   688|    )
   689|    warnings.extend(tx_warnings)
   690|    if "cost_basis_uncertain" in warnings:
   691|        create_alert(conn, priority="warnung", category="equity", entity_type="transaction", entity_id=tx_id, rule_id="cost_basis_uncertain", message="Cost basis is missing for manual position; performance metrics are incomplete.", evidence={"instrument_id": instrument_id}, fingerprint="cost_basis_uncertain")
   692|    create_alert(conn, priority="warnung", category="market_data", entity_type="instrument", entity_id=instrument_id, rule_id="missing_market_price", message="Market price is missing for manually added instrument until mapping/price update is confirmed.", evidence={}, fingerprint="missing_market_price")
   693|    record_audit_event(
   694|        conn,
   695|        source="instrument_search_add_position",
   696|        action="manual_position_add",
   697|        entity_type="transaction",
   698|        entity_id=tx_id,
   699|        new_values={"account_id": account_id, "instrument_id": instrument_id, "transaction_type": transaction_type, "catalog_entry_id": catalog_entry_id},
   700|        user_text_note=note,
   701|        confirmed=True,
   702|        created_by="dashboard",
   703|    )
   704|    conn.commit()
   705|    return EquityManageResult(instrument_id=instrument_id, account_id=account_id, transaction_id=tx_id, warnings=warnings)
   706|
   707|
   708|def create_manual_catalog_entry(
   709|    conn: Connection,
   710|    *,
   711|    asset_class: str,
   712|    name: str,
   713|    isin: str = "",
   714|    ticker: str = "",
   715|    exchange: str = "",
   716|    currency: str,
   717|    provider: str = "manual",
   718|    provider_symbol: str = "",
   719|    hedge_status: str = "unknown",
   720|    instrument_status: str = "unknown",
   721|    valuation_policy: str = "live_price",
   722|    note: str,
   723|) -> str:
   724|    note = _require_note(note, reason="manual catalog entry")
   725|    return upsert_catalog_entry(
   726|        conn,
   727|        CatalogEntryInput(
   728|            asset_class="etf" if asset_class.lower() == "etf" else "equity",
   729|            name=name,
   730|            isin=isin,
   731|            ticker=ticker,
   732|            exchange=exchange,
   733|            trading_currency=currency,
   734|            instrument_currency=currency,
   735|            provider=provider or "manual",
   736|            provider_symbol=provider_symbol or None,
   737|            provider_market=exchange or None,
   738|            hedge_status=hedge_status,
   739|            instrument_status=instrument_status,
   740|            valuation_policy=valuation_policy,
   741|            source="manual",
   742|            source_confidence="medium" if isin and exchange else "low",
   743|        ),
   744|        note=note,
   745|        created_by="dashboard",
   746|    )
   747|
   748|
   749|def get_equity_management_options(conn: Connection) -> dict[str, list[dict[str, str]]]:
   750|    accounts = [
   751|        {
   752|            "account_id": row["account_id"],
   753|            "account_name": row["account_name"],
   754|            "platform_name": row["platform_name"],
   755|            "currency": row["currency"],
   756|        }
   757|        for row in conn.execute(
   758|            """
   759|            SELECT a.account_id, a.account_name, p.name AS platform_name, a.currency
   760|            FROM accounts a JOIN platforms p ON p.platform_id=a.platform_id
   761|            WHERE a.is_active=1
   762|            ORDER BY p.name, a.account_name
   763|            """
   764|        ).fetchall()
   765|    ]
   766|    instruments = [
   767|        {"instrument_id": row["instrument_id"], "name": row["name"], "isin": row["isin"] or "", "ticker": row["ticker"] or "", "currency": row["currency"]}
   768|        for row in conn.execute("SELECT instrument_id, name, isin, ticker, currency FROM instruments WHERE is_active=1 ORDER BY name").fetchall()
   769|    ]
   770|    return {"accounts": accounts, "instruments": instruments}
   771|


patch

    currency: str,
    quantity_text: str,
    cost_basis_original_text: str | None = None,
    snapshot_date: str,
    category: str = "Unknown",

    currency: str,
    quantity_text: str,
    snapshot_date: str,
    cost_basis_original_text: str | None = None,
    category: str = "Unknown",


--- a//home/agent/.hermes/repos/FinanceManager/src/jarvis_finance/equity/manage.py
+++ b//home/agent/.hermes/repos/FinanceManager/src/jarvis_finance/equity/manage.py
@@ -408,8 +408,8 @@
     exchange: str = "",
     currency: str,
     quantity_text: str,
+    snapshot_date: str,
     cost_basis_original_text: str | None = None,
-    snapshot_date: str,
     category: str = "Unknown",
     note: str,
     confirm: bool,

/home/agent/.hermes/repos/FinanceManager/src/jarvis_finance/equity/manage.py was last read with offset/limit pagination (partial view). Re-read the whole file before overwriting it.


Explanation:
**Analyzing Python note syntax**

I'm thinking about the issue with non-default notes after a default category in Python. It seems like the existing tests might have worked, but I suspect the syntax could be invalid. Maybe I need to make the note a default, so I should confirm it with parameters like `str = ""` and `confirm: bool = False` to avoid confusion. There's definitely something to clarify here!

    category: str = "Unknown",
    note: str = "",
    confirm: bool = False,

    category: str = "Unknown",
    note: str,
    confirm: bool,


--- a//home/agent/.hermes/repos/FinanceManager/src/jarvis_finance/equity/manage.py
+++ b//home/agent/.hermes/repos/FinanceManager/src/jarvis_finance/equity/manage.py
@@ -411,8 +411,8 @@
     snapshot_date: str,
     cost_basis_original_text: str | None = None,
     category: str = "Unknown",
-    note: str,
-    confirm: bool,
+    note: str = "",
+    confirm: bool = False,
     fx_rate_to_chf_text: str | None = None,
     fx_source: str | None = None,
     fx_status: str = "ok",


    asset_class: str,
    name: str,
    currency: str,
    isin: str = "",
    ticker: str = "",
    exchange: str = "",

    asset_class: str,
    name: str,
    isin: str = "",
    ticker: str = "",
    exchange: str = "",
    currency: str,


Found 2 matches for old_string. Provide more context to make it unique, or use replace_all=True.


def create_manual_catalog_entry(
    conn: Connection,
    *,
    asset_class: str,
    name: str,
    currency: str,
    isin: str = "",
    ticker: str = "",
    exchange: str = "",

def create_manual_catalog_entry(
    conn: Connection,
    *,
    asset_class: str,
    name: str,
    isin: str = "",
    ticker: str = "",
    exchange: str = "",
    currency: str,


--- a//home/agent/.hermes/repos/FinanceManager/src/jarvis_finance/equity/manage.py
+++ b//home/agent/.hermes/repos/FinanceManager/src/jarvis_finance/equity/manage.py
@@ -710,10 +710,10 @@
     *,
     asset_class: str,
     name: str,
+    currency: str,
     isin: str = "",
     ticker: str = "",
     exchange: str = "",
-    currency: str,
     provider: str = "manual",
     provider_symbol: str = "",
     hedge_status: str = "unknown",


Found 5 matches for old_string. Provide more context to make it unique, or use replace_all=True.


    valuation_policy: str = "live_price",
    note: str = "",
) -> str:

    valuation_policy: str = "live_price",
    note: str,
) -> str:


--- a//home/agent/.hermes/repos/FinanceManager/src/jarvis_finance/equity/manage.py
+++ b//home/agent/.hermes/repos/FinanceManager/src/jarvis_finance/equity/manage.py
@@ -719,7 +719,7 @@
     hedge_status: str = "unknown",
     instrument_status: str = "unknown",
     valuation_policy: str = "live_price",
-    note: str,
+    note: str = "",
 ) -> str:
     note = _require_note(note, reason="manual catalog entry")
     return upsert_catalog_entry(


from pathlib import Path
p=Path('/home/agent/.hermes/repos/FinanceManager/src/jarvis_finance/dashboard/views/page_13_equity_manage.py')
s=p.read_text()
s=s.replace('from jarvis_finance.equity.manage import add_equity_initial_snapshot, add_equity_transaction, add_manual_position_from_catalog, create_manual_catalog_entry, get_equity_management_options', 'from jarvis_finance.equity.manage import add_equity_initial_snapshot, add_equity_transaction, add_manual_position_from_catalog, create_manual_catalog_entry, ensure_standard_broker_accounts, get_equity_management_options, search_instrument_candidates')
start=s.index('    with tabs[0]:')
end=s.index('\n    with tabs[1]:')
new=r'''    with tabs[0]:
        st.subheader("Aktie/ETF hinzufügen")
        st.caption("Wizard: 1 Suchen → 2 Instrument auswählen → 3 Depot & Menge → 4 Einstand/Datum/Notiz → 5 Review → 6 Bestätigen.")
        st.info("DOCX-Brokerimporte sind hier bewusst nicht der Hauptpfad. Es wird nur auf Klick gesucht; kein Provider-/Live-API-Call beim Rendern.")
        ensure_standard_broker_accounts(conn)

        st.markdown("### 1. Instrument suchen")
        query = st.text_input("ISIN, Name oder Ticker", key="wizard_search_query")
        c1, c2, c3 = st.columns(3)
        with c1:
            class_filter = st.selectbox("Assetklasse", ["", "stock", "etf"], key="wizard_search_class")
            currency_filter = st.selectbox("Währung", ["", "CHF", "EUR", "USD"], key="wizard_search_currency")
        with c2:
            exchange_filter = st.text_input("Börse/Exchange optional", key="wizard_search_exchange")
            country_filter = st.text_input("Land optional", key="wizard_search_country")
        with c3:
            provider_filter = st.text_input("Provider optional", key="wizard_search_provider")
            external_lookup = st.checkbox("Provider-Suche explizit versuchen", key="wizard_search_external")
        if st.button("Suchen", key="wizard_search_button"):
            st.session_state["wizard_search_results"] = search_instrument_candidates(
                conn,
                query=query,
                asset_class=class_filter or None,
                exchange=exchange_filter or None,
                currency=currency_filter or None,
                country=country_filter or None,
                provider=provider_filter or None,
                include_external=bool(external_lookup),
            )
        search_state = st.session_state.get("wizard_search_results", {"results": [], "warnings": [], "selection_required": True})
        if search_state.get("warnings"):
            st.warning("; ".join(str(w) for w in search_state.get("warnings", [])))
        display_rows = [
            {
                "Name": r.get("name", ""),
                "ISIN": r.get("isin", ""),
                "Ticker": r.get("ticker", ""),
                "Exchange": r.get("exchange", ""),
                "Währung": r.get("currency", ""),
                "Assetklasse": r.get("asset_class", ""),
                "Datenquelle": r.get("data_source", ""),
                "Mapping-Status": r.get("mapping_status", ""),
                "Letzter Kurs": r.get("last_price", ""),
                "Kursdatum": r.get("price_date", ""),
            }
            for r in search_state.get("results", [])
        ]
        show_table(st, display_rows, empty_message="Noch keine Suche ausgeführt oder kein lokaler Treffer. Manuelle Anlage ist möglich.")

        st.markdown("### 2. Instrument auswählen oder manuell anlegen")
        result_labels = [f"{i+1}. {r.get('name')} | {r.get('isin') or 'ISIN fehlt'} | {r.get('ticker') or 'Ticker fehlt'} | {r.get('exchange') or 'Exchange fehlt'} | {r.get('currency') or 'Währung fehlt'}" for i, r in enumerate(search_state.get("results", []))]
        chosen_label = st.selectbox("Treffer bewusst auswählen", result_labels, key="wizard_selected_result") if result_labels else None
        selected_result = None
        if chosen_label:
            selected_result = search_state.get("results", [])[int(chosen_label.split('.', 1)[0]) - 1]
            st.success("Instrument ausgewählt. Ticker allein wurde nicht automatisch übernommen; Auswahl ist bewusst erfolgt.")
        with st.expander("Manuell anlegen, falls kein sauberer Treffer vorhanden ist"):
            c_asset = st.selectbox("Assetklasse", ["stock", "etf"], key="wizard_manual_asset")
            c_name = st.text_input("Name", key="wizard_manual_name")
            c_isin = st.text_input("ISIN stark empfohlen", key="wizard_manual_isin")
            c_ticker = st.text_input("Ticker", key="wizard_manual_ticker")
            c_exchange = st.text_input("Exchange", key="wizard_manual_exchange")
            c_currency = st.selectbox("Währung", ["CHF", "EUR", "USD"], key="wizard_manual_currency")
            c_note = st.text_area("Notiz / Quelle zur manuellen Anlage", key="wizard_manual_note")
            st.warning("Manuelle Anlage ohne ISIN erzeugt einen Data-Quality-Hinweis; ISIN und Ticker dürfen nicht beide leer sein.")
            if st.button("Manuelles Instrument speichern", key="wizard_manual_save"):
                try:
                    if not c_isin and not c_ticker:
                        raise ValueError("ISIN oder Ticker ist erforderlich")
                    create_manual_catalog_entry(conn, asset_class=c_asset, name=c_name, currency=c_currency, isin=c_isin, ticker=c_ticker, exchange=c_exchange, note=c_note)
                    st.success("Instrument im lokalen Katalog gespeichert. Bitte anschließend erneut suchen und bewusst auswählen.")
                except Exception as exc:
                    st.error(f"Manuelle Anlage abgelehnt: {exc}")

        st.markdown("### 3–4. Depot, Menge, Datum, Einstand und Notiz")
        pos_account_label = st.selectbox("Plattform/Depot", account_labels, key="wizard_position_account") if account_labels else None
        pos_type = st.selectbox("Buchung", ["initial_snapshot", "buy", "partial_sell", "full_sell", "dividend", "etf_distribution", "manual_adjustment"], key="wizard_position_type")
        pos_qty = st.text_input("Menge als Decimal-Text", key="wizard_position_qty")
        pos_date = st.date_input("Snapshot-/Buchungsdatum", key="wizard_position_date")
        default_currency = selected_result.get("currency") if selected_result else "CHF"
        pos_currency = st.selectbox("Originalwährung", ["CHF", "EUR", "USD"], index=["CHF", "EUR", "USD"].index(default_currency) if default_currency in {"CHF", "EUR", "USD"} else 0, key="wizard_position_currency")
        pos_cost = st.text_input("Einstand / Brutto optional — leer = Cost Basis ungewiss", key="wizard_position_cost")
        pos_fx_status = st.selectbox("FX-Status", ["not_needed", "ok", "missing", "manual_override", "manual_override_required"], key="wizard_position_fx_status")
        pos_fx_rate = st.text_input("FX-Kurs zu CHF optional", key="wizard_position_fx_rate")
        pos_fx_source = st.text_input("FX-Quelle optional", key="wizard_position_fx_source")
        pos_note = st.text_area("Notiz — Pflicht bei unvollständiger Historie oder manual_adjustment", key="wizard_position_note")

        st.markdown("### 5. Review")
        review = {
            "Instrument": selected_result.get("name") if selected_result else "noch nicht ausgewählt",
            "ISIN": selected_result.get("isin") if selected_result else "",
            "Ticker": selected_result.get("ticker") if selected_result else "",
            "Exchange": selected_result.get("exchange") if selected_result else "",
            "Depot": pos_account_label or "",
            "Buchung": pos_type,
            "Datum": str(pos_date),
            "Cost Basis": "ungewiss" if not pos_cost else "erfasst",
            "FX": pos_fx_status,
        }
        st.write(review)
        pos_confirm = st.checkbox("Ich bestätige: genau diese Position/Transaktion speichern", key="wizard_position_confirm")
        selected_pos_account = _selected(options["accounts"], pos_account_label, _account_label)
        st.markdown("### 6. Bestätigen")
        if st.button("Bestätigt speichern", key="wizard_position_save", type="primary"):
            try:
                if not selected_result or not selected_result.get("catalog_entry_id"):
                    raise ValueError("Instrument selection is required before saving")
                if not selected_pos_account:
                    raise ValueError("account is required")
                result = add_manual_position_from_catalog(
                    conn,
                    catalog_entry_id=selected_result["catalog_entry_id"],
                    account_id=selected_pos_account["account_id"],
                    position_type=pos_type,
                    quantity_text=pos_qty,
                    trade_date=str(pos_date),
                    currency=pos_currency,
                    cost_basis_original_text=pos_cost or None,
                    fx_status=pos_fx_status,
                    fx_rate_to_chf_text=pos_fx_rate or None,
                    fx_source=pos_fx_source or None,
                    note=pos_note,
                    confirm=bool(pos_confirm),
                )
                st.success("Gespeichert: Ledger-Ereignis und Audit-Log wurden erzeugt.")
                if result.warnings:
                    st.warning("Datenqualität: " + "; ".join(result.warnings))
            except Exception as exc:
                st.error(f"Speicherung abgelehnt: {exc}")
'''
s=s[:start]+new+s[end:]
# Hide ids in other result writes
s=s.replace('                st.write({"instrument_id": result.instrument_id, "transaction_id": result.transaction_id, "warnings": result.warnings})', '                if result.warnings:\n                    st.warning("Datenqualität: " + "; ".join(result.warnings))')
s=s.replace('                    st.write({"transaction_id": result.transaction_id, "warnings": result.warnings})', '                    if result.warnings:\n                        st.warning("Datenqualität: " + "; ".join(result.warnings))')
p.write_text(s)
print('patched page')


Output: patched page


    if position_type == "initial_snapshot":
        transaction_type = "initial_position_snapshot"
    elif position_type in {"buy", "partial_sell", "full_sell", "dividend", "etf_distribution", "manual_adjustment"}:
        transaction_type = position_type
    else:
        raise ValueError("position_type must be initial_snapshot, buy, partial_sell, full_sell, dividend, etf_distribution or manual_adjustment")

    if position_type == "initial_snapshot":
        transaction_type = "initial_position_snapshot"
    elif position_type in {"buy", "manual_adjustment"}:
        transaction_type = position_type
    else:
        raise ValueError("position_type must be initial_snapshot, buy or manual_adjustment")


--- a//home/agent/.hermes/repos/FinanceManager/src/jarvis_finance/equity/manage.py
+++ b//home/agent/.hermes/repos/FinanceManager/src/jarvis_finance/equity/manage.py
@@ -648,10 +648,10 @@
     position_type = str(position_type or "").strip()
     if position_type == "initial_snapshot":
         transaction_type = "initial_position_snapshot"
-    elif position_type in {"buy", "manual_adjustment"}:
+    elif position_type in {"buy", "partial_sell", "full_sell", "dividend", "etf_distribution", "manual_adjustment"}:
         transaction_type = position_type
     else:
-        raise ValueError("position_type must be initial_snapshot, buy or manual_adjustment")
+        raise ValueError("position_type must be initial_snapshot, buy, partial_sell, full_sell, dividend, etf_distribution or manual_adjustment")
     if fx_status not in VALID_FX_STATUSES:
         raise ValueError("invalid fx_status")
     currency = _require_currency(currency)


    qty = parse_decimal_text(quantity_text or "0", field_name="quantity")
    if transaction_type in {"initial_position_snapshot", "buy", "partial_sell", "full_sell", "manual_adjustment"} and qty <= 0:
        raise ValueError("quantity must be > 0")
    if transaction_type in {"dividend", "etf_distribution", "fee"}:
        qty = Decimal("0")

    qty = parse_decimal_text(quantity_text, field_name="quantity")
    if qty <= 0:
        raise ValueError("quantity must be > 0")


    trade_date = _require_date(trade_date)
    qty = parse_decimal_text(quantity_text or "0", field_name="quantity")
    if transaction_type in {"initial_position_snapshot", "buy", "partial_sell", "full_sell", "manual_adjustment"} and qty <= 0:
        raise ValueError("quantity must be > 0")
    if transaction_type in {"dividend", "etf_distribution", "fee"}:
        qty = Decimal("0")
    warnings: list[str] = []

    trade_date = _require_date(trade_date)
    qty = parse_decimal_text(quantity_text, field_name="quantity")
    if qty <= 0:
        raise ValueError("quantity must be > 0")
    warnings: list[str] = []


--- a//home/agent/.hermes/repos/FinanceManager/src/jarvis_finance/equity/manage.py
+++ b//home/agent/.hermes/repos/FinanceManager/src/jarvis_finance/equity/manage.py
@@ -656,9 +656,11 @@
         raise ValueError("invalid fx_status")
     currency = _require_currency(currency)
     trade_date = _require_date(trade_date)
-    qty = parse_decimal_text(quantity_text, field_name="quantity")
-    if qty <= 0:
+    qty = parse_decimal_text(quantity_text or "0", field_name="quantity")
+    if transaction_type in {"initial_position_snapshot", "buy", "partial_sell", "full_sell", "manual_adjustment"} and qty <= 0:
         raise ValueError("quantity must be > 0")
+    if transaction_type in {"dividend", "etf_distribution", "fee"}:
+        qty = Decimal("0")
     warnings: list[str] = []
     if cost_basis_original_text in {None, ""}:
         gross = Decimal("0")


    if transaction_type == "initial_position_snapshot":
        existing_position = calculate_positions(conn).positions.get((account_id, instrument_id))
        if existing_position and existing_position.quantity != 0:
            raise ValueError("initial snapshot would overwrite an existing position; use manual_adjustment")
    if transaction_type in {"partial_sell", "full_sell"}:
        current = calculate_positions(conn).positions.get((account_id, instrument_id))
        current_qty = current.quantity if current else Decimal("0")
        if qty > current_qty:
            raise ValueError("sell would create negative position")
        if transaction_type == "full_sell" and qty != current_qty:
            raise ValueError("full_sell quantity must match current position")


--- a//home/agent/.hermes/repos/FinanceManager/src/jarvis_finance/equity/manage.py
+++ b//home/agent/.hermes/repos/FinanceManager/src/jarvis_finance/equity/manage.py
@@ -672,6 +672,13 @@
         existing_position = calculate_positions(conn).positions.get((account_id, instrument_id))
         if existing_position and existing_position.quantity != 0:
             raise ValueError("initial snapshot would overwrite an existing position; use manual_adjustment")
+    if transaction_type in {"partial_sell", "full_sell"}:
+        current = calculate_positions(conn).positions.get((account_id, instrument_id))
+        current_qty = current.quantity if current else Decimal("0")
+        if qty > current_qty:
+            raise ValueError("sell would create negative position")
+        if transaction_type == "full_sell" and qty != current_qty:
+            raise ValueError("full_sell quantity must match current position")
     tx_id, tx_warnings = _insert_transaction(
         conn,
         transaction_type=transaction_type,


Explanation:
**Checking action audit details**

I need to focus on using the manual_position_add function, but I'm not sure if it’s specific enough for what I need. I should compile the necessary information to see if it aligns with the schema columns. It's essential to ensure I'm not missing any details here, as that could lead to confusion or errors down the line. I'll keep refining this until it feels right!


terminal

Output:
Listing 'src'...
Listing 'src/jarvis_finance'...
Listing 'src/jarvis_finance/audit'...
Listing 'src/jarvis_finance/cli'...
Listing 'src/jarvis_finance/config'...
Listing 'src/jarvis_finance/crypto'...
Listing 'src/jarvis_finance/dashboard'...
Listing 'src/jarvis_finance/dashboard/components'...
Listing 'src/jarvis_finance/dashboard/pages'...
Listing 'src/jarvis_finance/dashboard/views'...
Compiling 'src/jarvis_finance/dashboard/views/page_13_equity_manage.py'...
Listing 'src/jarvis_finance/equity'...
Compiling 'src/jarvis_finance/equity/manage.py'...
Listing 'src/jarvis_finance/fx'...
Listing 'src/jarvis_finance/imports'...
Listing 'src/jarvis_finance/ledger'...
Listing 'src/jarvis_finance/market'...
Listing 'src/jarvis_finance/market_data'...
Listing 'src/jarvis_finance/models'...
Listing 'src/jarvis_finance/quality'...
Listing 'src/jarvis_finance/reports'...
Listing 'src/jarvis_finance/reports/templates'...
Listing 'src/jarvis_finance/runtime'...
Listing 'src/jarvis_finance/storage'...
Listing 'src/jarvis_finance.egg-info'...
Listing 'tests'...
Listing 'tests/fixtures'...
Listing 'tests/integration'...
Listing 'tests/unit'...


def test_manual_instrument_search_and_wizard_safety_flow() -> None:
    conn = setup_conn()
    account_id = seed_account(conn, "Synthetic Manual Broker")
    first = create_manual_catalog_entry(
        conn,
        asset_class="stock",
        name="Synthetic Alpha AG",
        currency="CHF",
        isin="CH1111111111",
        ticker="ALP",
        exchange="SIX",
        note="synthetic catalog source",
    )
    create_manual_catalog_entry(
        conn,
        asset_class="stock",
        name="Synthetic Alpha US Listing",
        currency="USD",
        isin="US1111111111",
        ticker="ALP",
        exchange="NASDAQ",
        note="synthetic catalog source",
    )

    isin_result = search_instrument_candidates(conn, query="CH1111111111")
    assert len(isin_result["results"]) == 1
    assert isin_result["results"][0]["mapping_status"] == "exact_isin_match"

    name_result = search_instrument_candidates(conn, query="Synthetic Alpha")
    assert len(name_result["results"]) >= 2
    assert name_result["selection_required"] is True

    ticker_result = search_instrument_candidates(conn, query="ALP")
    assert len(ticker_result["results"]) >= 2
    assert ticker_result["selection_required"] is True
    assert conn.execute("SELECT COUNT(*) AS c FROM transactions").fetchone()["c"] == 0

    with pytest.raises(ValueError, match="confirm"):
        add_manual_position_from_catalog(
            conn,
            catalog_entry_id=first,
            account_id=account_id,
            position_type="initial_snapshot",
            quantity_text="1.25",
            trade_date="2025-12-31",
            currency="CHF",
            note="synthetic review must be confirmed",
            confirm=False,
        )

    result = add_manual_position_from_catalog(
        conn,
        catalog_entry_id=first,
        account_id=account_id,
        position_type="initial_snapshot",
        quantity_text="1.25",
        trade_date="2025-12-31",
        currency="CHF",
        cost_basis_original_text=None,
        note="synthetic manually reviewed initial snapshot",
        confirm=True,
    )
    tx = conn.execute("SELECT * FROM transactions WHERE transaction_id=?", (result.transaction_id,)).fetchone()
    assert tx["transaction_type"] == "initial_position_snapshot"
    assert tx["quantity"] == "1.25"
    assert tx["gross_amount_original"] == "0"
    assert "cost_basis_uncertain" in result.warnings
    assert conn.execute("SELECT COUNT(*) AS c FROM audit_log WHERE action='manual_position_add'").fetchone()["c"] == 1
    assert conn.execute("SELECT COUNT(*) AS c FROM alerts WHERE rule_id='cost_basis_uncertain'").fetchone()["c"] == 1

def test_manual_catalog_entry_and_foreign_fx_handling() -> None:
    conn = setup_conn()
    account_id = seed_account(conn, "Synthetic FX Broker")
    catalog_id = create_manual_catalog_entry(
        conn,
        asset_class="etf",
        name="Synthetic USD ETF",
        currency="USD",
        isin="IE2222222222",
        ticker="USDE",
        exchange="NYSE",
        note="synthetic manual ETF source",
    )
    result = add_manual_position_from_catalog(
        conn,
        catalog_entry_id=catalog_id,
        account_id=account_id,
        position_type="initial_snapshot",
        quantity_text="2",
        trade_date="2025-12-31",
        currency="USD",
        cost_basis_original_text="100.00",
        fx_rate_to_chf_text="0.90",
        fx_source="synthetic fx source",
        note="synthetic USD ETF with FX",
        confirm=True,
    )
    tx = conn.execute("SELECT * FROM transactions WHERE transaction_id=?", (result.transaction_id,)).fetchone()
    assert tx["currency_original"] == "USD"
    assert tx["fx_rate_to_chf"] == "0.90"
    assert tx["gross_amount_chf"] == "90.0000"

    missing_fx_catalog = create_manual_catalog_entry(
        conn,
        asset_class="stock",
        name="Synthetic EUR Stock",
        currency="EUR",
        isin="DE3333333333",
        ticker="EURS",
        exchange="XETRA",
        note="synthetic manual stock source",
    )
    missing = add_manual_position_from_catalog(
        conn,
        catalog_entry_id=missing_fx_catalog,
        account_id=account_id,
        position_type="buy",
        quantity_text="1",
        trade_date="2026-01-05",
        currency="EUR",
        cost_basis_original_text="50.00",
        fx_status="missing",
        note="synthetic missing FX accepted for review",
        confirm=True,
    )
    tx_missing = conn.execute("SELECT * FROM transactions WHERE transaction_id=?", (missing.transaction_id,)).fetchone()
    assert tx_missing["fx_status"] == "missing"
    assert tx_missing["gross_amount_chf"] is None
    assert "missing_fx" in missing.warnings

def test_manual_wizard_supports_buy_sell_dividend_and_no_dashboard_live_api_or_ids() -> None:
    conn = setup_conn()
    account_id = seed_account(conn, "Synthetic Trading Broker")
    catalog_id = create_manual_catalog_entry(
        conn,
        asset_class="stock",
        name="Synthetic Tradable",
        currency="CHF",
        isin="CH4444444444",
        ticker="TRD",
        exchange="SIX",
        note="synthetic tradable source",
    )
    snap = add_manual_position_from_catalog(conn, catalog_entry_id=catalog_id, account_id=account_id, position_type="initial_snapshot", quantity_text="5", trade_date="2025-12-31", currency="CHF", cost_basis_original_text="500", note="synthetic starting point", confirm=True)
    add_manual_position_from_catalog(conn, catalog_entry_id=catalog_id, account_id=account_id, position_type="buy", quantity_text="1", trade_date="2026-01-05", currency="CHF", cost_basis_original_text="110", note="synthetic buy", confirm=True)
    add_manual_position_from_catalog(conn, catalog_entry_id=catalog_id, account_id=account_id, position_type="partial_sell", quantity_text="2", trade_date="2026-01-10", currency="CHF", cost_basis_original_text="220", note="synthetic sell", confirm=True)
    add_manual_position_from_catalog(conn, catalog_entry_id=catalog_id, account_id=account_id, position_type="dividend", quantity_text="0", trade_date="2026-02-01", currency="CHF", cost_basis_original_text="4.50", note="synthetic dividend", confirm=True)
    assert calculate_positions(conn).positions[(account_id, snap.instrument_id)].quantity == Decimal("4")

    from pathlib import Path
    page = Path("src/jarvis_finance/dashboard/views/page_13_equity_manage.py").read_text()
    assert "search_instrument_candidates(" in page
    assert "Provider-Suche explizit" in page
    assert "instrument_id": not in page.split("with tabs[1]:", 1)[0]
    assert "catalog_entry_id": not in page.split("with tabs[1]:", 1)[0]


No linter for .txt files


Explanation:
**Fixing Python code**

I realized I wrote an invalid Python assertion: `assert "instrument_id": not`. That definitely needs correcting! I also need to remember to append content to the file after the imports, which means I have to import the necessary functions first. It looks like I'll have to patch the test file carefully. I want to ensure everything works well, so I’ll take my time with these changes to avoid further mistakes.

patch

from jarvis_finance.equity.manage import (
    add_equity_initial_snapshot,
    add_equity_transaction,
    get_equity_management_options,
)

from jarvis_finance.equity.manage import (
    add_equity_initial_snapshot,
    add_equity_transaction,
    add_manual_position_from_catalog,
    create_manual_catalog_entry,
    get_equity_management_options,
    search_instrument_candidates,
)


--- a//home/agent/.hermes/repos/FinanceManager/tests/unit/test_equity_manage.py
+++ b//home/agent/.hermes/repos/FinanceManager/tests/unit/test_equity_manage.py
@@ -7,7 +7,10 @@
 from jarvis_finance.equity.manage import (
     add_equity_initial_snapshot,
     add_equity_transaction,
+    add_manual_position_from_catalog,
+    create_manual_catalog_entry,
     get_equity_management_options,
+    search_instrument_candidates,
 )
 from jarvis_finance.ledger.positions import calculate_positions
 from jarvis_finance.storage.database import connect_memory

/home/agent/.hermes/repos/FinanceManager/tests/unit/test_equity_manage.py was last read with offset/limit pagination (partial view). Re-read the whole file before overwriting it.


from pathlib import Path
append=Path('/tmp/manual_tests.txt').read_text()
append=append.replace('    assert "instrument_id": not in page.split("with tabs[1]:", 1)[0]\n    assert "catalog_entry_id": not in page.split("with tabs[1]:", 1)[0]', '    wizard_source = page.split("with tabs[1]:", 1)[0]\n    assert "st.write({\\\"instrument_id\\\"" not in wizard_source\n    assert "st.write({\\\"catalog_entry_id\\\"" not in wizard_source')
p=Path('/home/agent/.hermes/repos/FinanceManager/tests/unit/test_equity_manage.py')
p.write_text(p.read_text()+append)
print('appended tests')


Output: appended tests


terminal

python -m compileall src tests && pytest -q tests/unit/test_equity_manage.py -q


Output:
Listing 'src'...
Listing 'src/jarvis_finance'...
Listing 'src/jarvis_finance/audit'...
Listing 'src/jarvis_finance/cli'...
Listing 'src/jarvis_finance/config'...
Listing 'src/jarvis_finance/crypto'...
Listing 'src/jarvis_finance/dashboard'...
Listing 'src/jarvis_finance/dashboard/components'...
Listing 'src/jarvis_finance/dashboard/pages'...
Listing 'src/jarvis_finance/dashboard/views'...
Listing 'src/jarvis_finance/equity'...
Listing 'src/jarvis_finance/fx'...
Listing 'src/jarvis_finance/imports'...
Listing 'src/jarvis_finance/ledger'...
Listing 'src/jarvis_finance/market'...
Listing 'src/jarvis_finance/market_data'...
Listing 'src/jarvis_finance/models'...
Listing 'src/jarvis_finance/quality'...
Listing 'src/jarvis_finance/reports'...
Listing 'src/jarvis_finance/reports/templates'...
Listing 'src/jarvis_finance/runtime'...
Listing 'src/jarvis_finance/storage'...
Listing 'src/jarvis_finance.egg-info'...
Listing 'tests'...
Listing 'tests/fixtures'...
Listing 'tests/integration'...
Listing 'tests/unit'...
Compiling 'tests/unit/test_equity_manage.py'...
..........                                                               [100%]


todo

Code-Struktur für manuelle Instrument-Suche/Add-Position prüfen

Resolver/Search-Service und manuelle Snapshot/Transaction-Funktionen implementieren

User-Mode Wizard im Dashboard ohne Live-API/technische IDs bauen

Tests für Suche, Wizard-Safety, Snapshots, FX/Audit/DQ ergänzen


Compile, pytest, Git-Safety, Commit und Push ausführen