Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(portfolio): integrate dated extraETF imports and allocation proposals

Haozhe Wu923f60e1d332
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cd5c53139..a54f2b40e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,8 @@ This project adheres to [Semantic Versioning](https://semver.org/).
### Maintenance — 2026-10-13
+- extraETF Investments imports now feed portfolio snapshots, with explicit row-count/freshness checks, EUR reference-rate valuation, preserved account/ISIN identity, and non-executing allocation proposals across Web, REST, CLI and the portfolio tool.
+
- Standalone validation preserves saved parameters and seeds across walk-forward, Monte Carlo and permutation tests (#1815).
- Custom OpenAI-compatible providers use tested credentials in the OS vault, canonical model settings and the `provider custom` CLI; existing channel settings remain available (#1264).
- Pixel Office shares a transactional manual task board across Web, CLI and the agent tool. Assignment does not imply execution, and ranks grant no trading permissions (#1616).
diff --git a/README.md b/README.md
index d3f4d90ed..0be344736 100644
--- a/README.md
+++ b/README.md
@@ -412,6 +412,28 @@ execution; organizational ranks grant no trading permissions. Record the actual
result when completing a task. See [Pixel Office](pixel-office/README.md) for CLI
and API examples.
+### Import an extraETF holdings export
+
+Open **Portfolio → Manage accounts → Import extraETF Investments**, choose the official Investments CSV, confirm the number of holdings in extraETF, and choose the maximum file age you accept. Add the imported source, save, and refresh. Transactions, dividends and X-Ray exports are not holdings and are refused. Imports are local file evidence, separate from broker connections; no extraETF login or browser scraping is used.
+
+```bash
+vibe-trading portfolio import-extraetf ~/Downloads/Investments.csv \
+ --label "extraETF export" --expected-positions 27 --max-age-days 7 --select
+vibe-trading portfolio refresh
+vibe-trading portfolio show
+```
+
+The row count and age above are examples to replace with your own. The entire import fails on an unreadable row, count mismatch, missing price, future file time or expired freshness policy. File mtime is labelled as file mtime, never as a price observation; copying a file can change it. `Portfolio ID` keeps accounts separate even when they hold the same ISIN. Imported totals are quantity × exported price and **exclude cash and other assets absent from the export**. Select disjoint sources: an extraETF view can include accounts already selected through broker connections.
+
+USD, CNY, HKD and EUR display values use [Frankfurter reference rates](https://frankfurter.dev/) with the rate date separate from fetch time; they are not intraday quotes. An unavailable currency fails valuation. Cached rates are labelled stale and cannot produce a rebalancing proposal. An ISIN identifies a security but not its trading venue: imported holdings remain excluded from historical risk-series tools until that identity is resolved.
+
+**Allocation proposal** accepts user-defined percentages totalling 100% and shows value changes for review. It creates no orders, quantities, taxes or fee estimates. The same operation is available through `POST /api/portfolio/rebalance`, `portfolio_summary(snapshot_id=..., target_weights=...)`, or:
+
+```bash
+# targets.json maps the snapshot's holdings canonical_id (or CASH) to fractions.
+vibe-trading portfolio rebalance --snapshot-id <snapshot-id> --targets targets.json
+```
+
### Portfolio connector compatibility
| Badge | Meaning |
diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.py
index 7e723f061..2861becfd 100644
--- a/agent/cli/_legacy.py
+++ b/agent/cli/_legacy.py
@@ -4198,6 +4198,10 @@ def _print_portfolio_snapshot(snapshot: dict[str, Any]) -> None:
rich_escape(str(row.get("last_success_at") or "never")),
)
console.print(accounts)
+ for row in snapshot.get("accounts", []):
+ if row.get("import_metadata"):
+ meta = row["import_metadata"]
+ console.print(f"extraETF file mtime: {rich_escape(meta['source_mtime'])}; expires: {rich_escape(meta['expires_at'])}; holdings only, no cash")
holdings = Table(title="Holdings (combined across sources)", box=box.SIMPLE_HEAVY, show_lines=False)
holdings.add_column("Symbol")
@@ -4325,6 +4329,40 @@ def _dispatch_portfolio(args: argparse.Namespace) -> int:
return cmd_portfolio_refresh()
if sub == "sources":
return cmd_portfolio_sources()
+ if sub == "import-extraetf":
+ from datetime import datetime, timezone
+ from src.portfolio.imports import MAX_IMPORT_BYTES
+ try:
+ path = Path(args.file).expanduser()
+ with path.open("rb") as handle:
+ data = handle.read(MAX_IMPORT_BYTES + 1)
+ modified = os.fstat(handle.fileno()).st_mtime
+ if len(data) > MAX_IMPORT_BYTES:
+ raise ValueError("extraETF export exceeds the 4 MiB import limit")
+ instance = _portfolio_service()
+ imported = instance.settings_store.import_store.create(
+ csv_text=data.decode("utf-8-sig"), label=args.label,
+ source_mtime=datetime.fromtimestamp(modified, timezone.utc).isoformat(),
+ expected_positions=args.expected_positions, max_age_days=args.max_age_days,
+ )
+ if args.select:
+ settings = instance.settings()
+ settings["sources"].append({"connection_id": imported["id"], "source_kind": "extraetf",
+ "label": imported["label"], "include_cash": False})
+ instance.save_settings(settings)
+ console.print_json(data=imported)
+ return 0
+ except (ValueError, OSError) as exc:
+ console.print(f"[red]{rich_escape(str(exc))}[/red]")
+ return 1
+ if sub == "rebalance":
+ try:
+ target = json.loads(Path(args.targets).read_text())
+ console.print_json(data=_portfolio_service().rebalance(args.snapshot_id, target))
+ return 0
+ except (ValueError, OSError) as exc:
+ console.print(f"[red]{rich_escape(str(exc))}[/red]")
+ return 1
console.print(f"[red]Unknown portfolio subcommand: {sub}[/red]")
return EXIT_USAGE_ERROR
@@ -5572,6 +5610,15 @@ def _build_parser() -> argparse.ArgumentParser:
portfolio_subparsers.add_parser(
"refresh", help="Read every enabled source now, store a new snapshot, and print it"
)
+ import_parser = portfolio_subparsers.add_parser("import-extraetf", help="Import a local Investments CSV; never executes trades")
+ import_parser.add_argument("file")
+ import_parser.add_argument("--label", required=True)
+ import_parser.add_argument("--expected-positions", required=True, type=int)
+ import_parser.add_argument("--max-age-days", required=True, type=int)
+ import_parser.add_argument("--select", action="store_true", help="Add this import to selected portfolio sources")
+ rebalance_parser = portfolio_subparsers.add_parser("rebalance", help="Value-only proposal for a pinned snapshot")
+ rebalance_parser.add_argument("--snapshot-id", required=True)
+ rebalance_parser.add_argument("--targets", required=True, help="JSON file mapping canonical_id (or CASH) to target fraction")
portfolio_subparsers.add_parser(
"sources", help="List local read-only connections and whether the portfolio uses them"
)
diff --git a/agent/src/api/portfolio_routes.py b/agent/src/api/portfolio_routes.py
index 74441e258..7a8749a30 100644
--- a/agent/src/api/portfolio_routes.py
+++ b/agent/src/api/portfolio_routes.py
@@ -9,7 +9,7 @@ from copy import deepcopy
from datetime import datetime, timezone
from fastapi import Depends, FastAPI, HTTPException, Query, Response
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, Field, StrictFloat, StrictInt
from src.api.security import require_auth, require_settings_write_auth
from src.portfolio.service import PortfolioService
@@ -36,6 +36,7 @@ _REFRESH_STATE = {
class PortfolioSourceRequest(BaseModel):
connection_id: str
+ source_kind: str = "connection"
label: str
enabled: bool = True
order: int = 0
@@ -47,6 +48,19 @@ class PortfolioSettingsRequest(BaseModel):
sources: list[PortfolioSourceRequest] = Field(default_factory=list, max_length=50)
+class ExtraEtfImportRequest(BaseModel):
+ csv_text: str = Field(max_length=4 * 1024 * 1024)
+ label: str = Field(min_length=1, max_length=80)
+ source_mtime: str
+ expected_positions: int = Field(strict=True, ge=0, le=20000)
+ max_age_days: int = Field(strict=True, ge=1, le=365)
+
+
+class RebalanceRequest(BaseModel):
+ snapshot_id: str
+ target_weights: dict[str, StrictFloat | StrictInt] = Field(max_length=20001)
+
+
def _set_refresh_progress(source_id: str, status: str, error: str | None) -> None:
"""Record one source's live refresh state for the polling endpoint.
@@ -248,6 +262,21 @@ def register_portfolio_routes(app: FastAPI) -> None:
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
+ @app.post("/api/portfolio/imports/extraetf", dependencies=[Depends(require_settings_write_auth)])
+ def import_extraetf(payload: ExtraEtfImportRequest):
+ try:
+ imported = service().settings_store.import_store.create(**payload.model_dump())
+ return {"status": "ok", "import": imported}
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+ @app.post("/api/portfolio/rebalance", dependencies=[Depends(require_auth)])
+ def portfolio_rebalance(payload: RebalanceRequest):
+ try:
+ return {"status": "ok", "proposal": service().rebalance(payload.snapshot_id, payload.target_weights)}
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
@app.get("/api/portfolio/history", dependencies=[Depends(require_auth)])
def portfolio_history(limit: int = Query(180, ge=1, le=2000)):
return {"status": "ok", "history": service().history(limit)}
diff --git a/agent/src/portfolio/config.py b/agent/src/portfolio/config.py
index 476d36157..bb7f21b97 100644
--- a/agent/src/portfolio/config.py
+++ b/agent/src/portfolio/config.py
@@ -13,6 +13,7 @@ from typing import Any
from src.config.paths import get_runtime_root
from src.portfolio.compatibility import profile_compatibility
from src.portfolio.fx import DISPLAY_RATE_CURRENCIES
+from src.portfolio.imports import PortfolioImportStore
from src.portfolio.iso4217 import is_iso_currency
from src.trading.connections import (
ConnectionStore,
@@ -27,13 +28,14 @@ _SOURCE_ID_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,79}$")
@dataclass(frozen=True)
class PortfolioSource:
- """One enabled or disabled local connection selected for aggregation."""
+ """One selected read-only connection or imported holdings source."""
connection_id: str
label: str
enabled: bool = True
order: int = 0
include_cash: bool = True
+ source_kind: str = "connection"
@property
def id(self) -> str:
@@ -95,6 +97,7 @@ def eligible_profiles() -> list[TradingProfile]:
def source_catalog(
settings: PortfolioSettings,
connection_store: ConnectionStore | None = None,
+ import_store: PortfolioImportStore | None = None,
) -> list[dict[str, Any]]:
"""Describe configured local connections without exposing secret values.
@@ -124,12 +127,24 @@ def source_catalog(
"portfolio_compatibility": profile_compatibility(profile),
}
)
+ for imported in (import_store or PortfolioImportStore()).list():
+ source = selected.get(imported["id"])
+ rows.append({
+ **imported, "connection_id": imported["id"], "connector": "extraetf",
+ "profile_id": "", "environment": "import", "transport": "file_import",
+ "readonly": True, "capabilities": [], "supports_reconnect": False,
+ "credential_fields": [], "credential_status": {}, "credentials_configured": True,
+ "notes": "Holdings export only; no account cash, no live quotes, no execution.",
+ "selected": source is not None, "source_id": source.id if source else None,
+ "portfolio_compatibility": None,
+ })
return rows
def parse_settings(
payload: dict[str, Any],
connection_store: ConnectionStore | None = None,
+ import_store: PortfolioImportStore | None = None,
) -> PortfolioSettings:
"""Validate untrusted Web settings against the local connection registry.
@@ -162,6 +177,7 @@ def parse_settings(
raise ValueError("at most 50 portfolio sources are allowed")
seen_ids: set[str] = set()
+ imported_portfolios: set[str] = set()
sources: list[PortfolioSource] = []
for index, raw in enumerate(raw_sources):
if not isinstance(raw, dict):
@@ -169,6 +185,25 @@ def parse_settings(
connection_id = str(raw.get("connection_id") or raw.get("id") or "").strip().lower()
if not _SOURCE_ID_RE.fullmatch(connection_id):
raise ValueError(f"invalid portfolio connection id: {connection_id or '?'}")
+ source_kind = raw.get("source_kind", "connection")
+ if source_kind not in {"connection", "extraetf"}:
+ raise ValueError("unknown portfolio source_kind")
+ if source_kind == "extraetf":
+ imported = (import_store or PortfolioImportStore()).get(connection_id)
+ if connection_id in seen_ids:
+ raise ValueError("portfolio source ids must be unique")
+ if raw.get("enabled", True):
+ groups = {row["portfolio_id"] for row in imported["positions"]}
+ if groups & imported_portfolios:
+ raise ValueError("selected extraETF exports contain overlapping Portfolio IDs; replace the older source")
+ imported_portfolios.update(groups)
+ label = str(raw.get("label") or imported["label"]).strip()
+ if not label or len(label) > 80 or any(ord(c) < 32 for c in label):
+ raise ValueError("portfolio source labels must contain 1 to 80 printable characters")
+ seen_ids.add(connection_id)
+ sources.append(PortfolioSource(connection_id, label, bool(raw.get("enabled", True)),
+ int(raw.get("order", index)), False, "extraetf"))
+ continue
legacy_profile_id = str(raw.get("profile_id") or "").strip().lower()
if legacy_profile_id:
legacy_profile = profile_by_id(legacy_profile_id)
@@ -224,6 +259,7 @@ class PortfolioSettingsStore:
self.path = path or (get_runtime_root() / CONFIG_FILENAME)
connection_path = self.path.with_name("connections.json") if path is not None else None
self.connection_store = connection_store or ConnectionStore(connection_path)
+ self.import_store = PortfolioImportStore(self.path.parent / "portfolio" / "imports.sqlite3")
def load(self) -> PortfolioSettings:
"""Read persisted settings, creating an empty file on first use.
@@ -242,7 +278,7 @@ class PortfolioSettingsStore:
raise ValueError(f"invalid portfolio settings: {exc}") from exc
if not isinstance(payload, dict):
raise ValueError("invalid portfolio settings: root must be an object")
- settings = parse_settings(payload, self.connection_store)
+ settings = parse_settings(payload, self.connection_store, self.import_store)
if any("profile_id" in source for source in payload.get("sources", [])):
self.save(settings)
return settings
@@ -264,9 +300,9 @@ class PortfolioSettingsStore:
ValueError: If validation fails; nothing is written in that case.
"""
validated = (
- parse_settings(settings, self.connection_store)
+ parse_settings(settings, self.connection_store, self.import_store)
if isinstance(settings, dict)
- else parse_settings(settings.to_dict(), self.connection_store)
+ else parse_settings(settings.to_dict(), self.connection_store, self.import_store)
)
self.path.parent.mkdir(parents=True, exist_ok=True)
descriptor, temporary = tempfile.mkstemp(prefix=".portfolio-", suffix=".json", dir=self.path.parent)
diff --git a/agent/src/portfolio/fx.py b/agent/src/portfolio/fx.py
index 9090929ad..1d6a723b8 100644
--- a/agent/src/portfolio/fx.py
+++ b/agent/src/portfolio/fx.py
@@ -8,6 +8,7 @@ closed with the missing currency named.
from __future__ import annotations
+from dataclasses import dataclass
from decimal import Decimal
from typing import Mapping
@@ -15,7 +16,7 @@ from src.portfolio.compatibility import PortfolioContractError
Rates = Mapping[str, Decimal]
-DISPLAY_RATE_CURRENCIES = frozenset({"USD", "CNY", "HKD"})
+DISPLAY_RATE_CURRENCIES = frozenset({"USD", "CNY", "HKD", "EUR"})
def _validated_rate(pair: str, value: Decimal) -> Decimal:
@@ -57,3 +58,25 @@ def from_usd(value_usd: Decimal, currency: str, rates: Rates) -> Decimal:
)
rate = _validated_rate(f"USD/{code}", rate)
return value_usd * rate
+
+
+@dataclass(frozen=True)
+class FxQuote:
+ """One coherent reference-rate observation and its separate retrieval time."""
+
+ rates: Rates
+ fetched_at: str
+ as_of: str | None = None
+ source: str = "injected"
+
+ def validated(self) -> FxQuote:
+ """Reject a malformed USD base or a non-finite/non-positive rate."""
+ rates = {code: _validated_rate(f"USD/{code}", value) for code, value in self.rates.items()}
+ if rates.get("USD") != 1 or not {"CNY", "HKD"} <= rates.keys():
+ raise PortfolioContractError("FX quote requires USD=1 and CNY/HKD rates")
+ return FxQuote(rates, self.fetched_at, self.as_of, self.source)
+
+ def to_dict(self) -> dict:
+ """Serialize rates without losing decimal precision."""
+ return {"rates": {k: str(v) for k, v in self.rates.items()},
+ "fetched_at": self.fetched_at, "as_of": self.as_of, "source": self.source}
diff --git a/agent/src/portfolio/imports.py b/agent/src/portfolio/imports.py
new file mode 100644
index 000000000..825d25cc6
--- /dev/null
+++ b/agent/src/portfolio/imports.py
@@ -0,0 +1,140 @@
+"""Immutable, opt-in extraETF holdings imports, separate from broker connections."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import sqlite3
+import uuid
+from datetime import datetime, timedelta, timezone
+from decimal import Decimal
+from pathlib import Path
+from typing import Any
+
+from src.config.paths import get_runtime_root
+from src.portfolio.extraetf import parse_export
+from src.portfolio.iso4217 import is_iso_currency
+
+MAX_IMPORT_BYTES = 4 * 1024 * 1024
+
+
+def aware_time(value: str) -> datetime:
+ """Parse an explicit timezone-bearing timestamp, refusing naive dates."""
+ try:
+ result = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except (ValueError, AttributeError) as exc:
+ raise ValueError("source_mtime must be an ISO timestamp with timezone") from exc
+ if result.tzinfo is None:
+ raise ValueError("source_mtime must include its timezone")
+ return result.astimezone(timezone.utc)
+
+
+class PortfolioImportStore:
+ """Store validated exports locally without credentials or inferred identities."""
+
+ def __init__(self, path: Path | None = None) -> None:
+ self.path = path or get_runtime_root() / "portfolio" / "imports.sqlite3"
+
+ def _connect(self) -> sqlite3.Connection:
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ self.path.parent.chmod(0o700)
+ db = sqlite3.connect(self.path)
+ self.path.chmod(0o600)
+ db.execute("CREATE TABLE IF NOT EXISTS imports (id TEXT PRIMARY KEY, payload TEXT NOT NULL)")
+ return db
+
+ def create(
+ self, *, csv_text: str, label: str, source_mtime: str,
+ expected_positions: int, max_age_days: int, now: datetime | None = None,
+ ) -> dict[str, Any]:
+ """Validate an entire export before persisting any part of it.
+
+ Args:
+ csv_text: Original user-exported Investments CSV, never transactions.
+ label: User-visible source name.
+ source_mtime: File modification time; not an observation timestamp.
+ expected_positions: User-confirmed count, detecting whole-row truncation.
+ max_age_days: User's freshness policy, measured from the file mtime.
+ now: Injected clock for deterministic validation.
+
+ Returns:
+ Public import metadata, without portfolio identifiers or positions.
+
+ Raises:
+ ValueError: If any row, count, timestamp or valuation input is invalid.
+ """
+ now = now or datetime.now(timezone.utc)
+ if not isinstance(csv_text, str) or len(csv_text.encode("utf-8")) > MAX_IMPORT_BYTES:
+ raise ValueError("extraETF export exceeds the 4 MiB import limit")
+ label = label.strip()
+ if not label or len(label) > 80 or any(ord(c) < 32 for c in label):
+ raise ValueError("import label must contain 1 to 80 printable characters")
+ if type(expected_positions) is not int or not 0 <= expected_positions <= 20000:
+ raise ValueError("expected_positions must be an integer from 0 to 20000")
+ if type(max_age_days) is not int or not 1 <= max_age_days <= 365:
+ raise ValueError("max_age_days must be an integer from 1 to 365")
+ modified = aware_time(source_mtime)
+ if modified > now:
+ raise ValueError("file modification time is in the future")
+ expires = modified + timedelta(days=max_age_days)
+ if expires <= now:
+ raise ValueError("extraETF export is stale under the selected freshness policy; export again")
+ parsed = parse_export(csv_text)
+ positions = list(parsed.require_positions())
+ if len(positions) != expected_positions:
+ raise ValueError(f"expected {expected_positions} holdings, but the export contains {len(positions)}")
+ for row in positions:
+ if not is_iso_currency(row["currency"]):
+ raise ValueError(f"unsupported currency identity: {row['currency']}")
+ price, qty = row.get("market_price"), row["quantity"]
+ if price is None or Decimal(str(price)) <= 0 or Decimal(str(qty)) < 0:
+ raise ValueError("every imported holding needs a positive exported price and non-negative quantity")
+ # An unexplained FX conversion would mix the export's account value
+ # with its instrument price. Only the price/quantity book is valued.
+ row.update(source_mtime=modified.isoformat(), as_of_source="file_mtime",
+ expires_at=expires.isoformat(), identity_status="unresolved_venue")
+ payload = {
+ "id": "extraetf-" + uuid.uuid4().hex,
+ "source_kind": "extraetf", "label": label,
+ "source_mtime": modified.isoformat(), "as_of_source": "file_mtime",
+ "imported_at": now.isoformat(), "expires_at": expires.isoformat(),
+ "max_age_days": max_age_days, "expected_positions": expected_positions,
+ "sha256": hashlib.sha256(csv_text.encode("utf-8")).hexdigest(),
+ "valuation_basis": "exported_quantity_times_price", "cash_included": False,
+ "positions": positions,
+ }
+ with self._connect() as db:
+ db.execute("INSERT INTO imports VALUES (?, ?)", (payload["id"], json.dumps(payload, ensure_ascii=False)))
+ return self.metadata(payload)
+
+ @staticmethod
+ def metadata(payload: dict[str, Any]) -> dict[str, Any]:
+ """Return source metadata without underlying account identifiers."""
+ return {k: v for k, v in payload.items() if k != "positions"}
+
+ def get(self, source_id: str, *, require_fresh: bool = False) -> dict[str, Any]:
+ """Read one import, optionally failing once its freshness policy expires."""
+ with self._connect() as db:
+ row = db.execute("SELECT payload FROM imports WHERE id = ?", (source_id,)).fetchone()
+ if row is None:
+ raise ValueError(f"unknown portfolio import: {source_id}")
+ payload = json.loads(row[0])
+ if require_fresh and aware_time(payload["expires_at"]) <= datetime.now(timezone.utc):
+ raise ValueError("extraETF export is stale; import a new Investments export")
+ return payload
+
+ def list(self) -> list[dict[str, Any]]:
+ """List import metadata; expired imports remain visible for replacement."""
+ if not self.path.exists():
+ return []
+ with self._connect() as db:
+ return [self.metadata(json.loads(row[0])) for row in db.execute("SELECT payload FROM imports ORDER BY rowid")]
+
+ def collect(self, source: Any) -> dict[str, Any]:
+ """Produce a holdings-only source; never read a broker or request a quote."""
+ payload = self.get(source.id, require_fresh=True)
+ positions = payload.pop("positions")
+ for row in positions:
+ row.update(source_id=source.id, source_kind="extraetf", source_label=source.label,
+ profile_id=None)
+ return {"status": "ok", "positions": positions, "account": {}, "import_metadata": payload}
diff --git a/agent/src/portfolio/rebalance.py b/agent/src/portfolio/rebalance.py
new file mode 100644
index 000000000..848b8e6c4
--- /dev/null
+++ b/agent/src/portfolio/rebalance.py
@@ -0,0 +1,79 @@
+"""Deterministic allocation proposals; this module has no execution transport."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from decimal import Decimal, InvalidOperation
+from typing import Any
+
+from src.portfolio.fx import from_usd
+from src.portfolio.imports import aware_time
+
+
+def propose_rebalance(snapshot: dict[str, Any], target_weights: dict[str, Any]) -> dict[str, Any]:
+ """Compare a complete, dated snapshot with user-supplied allocation fractions.
+
+ Args:
+ snapshot: Immutable portfolio snapshot including FX and source metadata.
+ target_weights: Canonical holding IDs (or CASH) to fractions summing to one.
+
+ Returns:
+ Value-only proposals in the snapshot's display currency, never orders.
+
+ Raises:
+ ValueError: If evidence is incomplete/stale or the target is malformed.
+ """
+ if not snapshot.get("complete") or snapshot.get("fx", {}).get("stale"):
+ raise ValueError("rebalancing requires a complete snapshot and a successful FX refresh")
+ for account in snapshot["accounts"]:
+ metadata = account.get("import_metadata")
+ if metadata and aware_time(metadata["expires_at"]) <= datetime.now(timezone.utc):
+ raise ValueError("imported evidence is stale; import a new export before rebalancing")
+ valuation = snapshot["valuation"]
+ if Decimal(str(valuation.get("unpriced_or_other_usd", 0))) != 0 or any(
+ not row.get("priced") for row in snapshot["positions"]
+ ):
+ raise ValueError("rebalancing requires every included asset to be identified and priced")
+ current = {row["canonical_id"]: Decimal(str(row["market_value_usd"])) for row in snapshot["combined_holdings"]}
+ current["CASH"] = Decimal(str(valuation["cash_usd"]))
+ if any(value < 0 for value in current.values()):
+ raise ValueError("allocation proposals currently support long-only holdings")
+ if not isinstance(target_weights, dict) or not target_weights or set(target_weights) - current.keys():
+ raise ValueError("targets must name held canonical_id values or CASH")
+ target: dict[str, Decimal] = {}
+ for key, raw in target_weights.items():
+ try:
+ if isinstance(raw, bool):
+ raise ValueError("boolean allocation")
+ weight = Decimal(str(raw))
+ if not weight.is_finite() or not 0 <= weight <= 1:
+ raise ValueError("invalid weight")
+ except (InvalidOperation, ValueError) as exc:
+ raise ValueError("target weights must be finite fractions between 0 and 1") from exc
+ target[key] = weight
+ if abs(sum(target.values()) - Decimal(1)) > Decimal("0.00000001"):
+ raise ValueError("target weights must sum to 1")
+ total = sum(current.values())
+ if total <= 0:
+ raise ValueError("portfolio value must be positive")
+ currency = snapshot["display_currency"]
+ rates = {k: Decimal(str(v)) for k, v in snapshot["fx"]["rates"].items()}
+ rows = []
+ for key in sorted(current):
+ weight = target.get(key, Decimal(0))
+ desired = total * weight
+ rows.append({
+ "canonical_id": key, "current_weight": float(current[key] / total),
+ "target_weight": float(weight), "drift": float(weight - current[key] / total),
+ "current_value": float(from_usd(current[key], currency, rates)),
+ "target_value": float(from_usd(desired, currency, rates)),
+ "change_value": float(from_usd(desired - current[key], currency, rates)),
+ })
+ return {
+ "mode": "proposal_only", "snapshot_id": snapshot["snapshot_id"],
+ "created_at": snapshot["created_at"], "currency": currency,
+ "fx_as_of": snapshot["fx"].get("as_of"), "rows": rows,
+ "limitations": ["No orders, quantities, taxes, fees or execution prices are generated.",
+ "Cash and assets absent from an imported export are outside this allocation."]
+ + snapshot.get("warnings", []),
+ }
diff --git a/agent/src/portfolio/service.py b/agent/src/portfolio/service.py
index 668bdc822..b52a99d0f 100644
--- a/agent/src/portfolio/service.py
+++ b/agent/src/portfolio/service.py
@@ -10,7 +10,7 @@ import subprocess
import sys
import urllib.request
import uuid
-from datetime import datetime, timezone
+from datetime import date, datetime, timezone
from decimal import Decimal, InvalidOperation
from typing import Any, Callable
@@ -24,7 +24,7 @@ from src.portfolio.compatibility import (
ensure_supported_currencies,
profile_compatibility,
)
-from src.portfolio.fx import Rates, build_rates, from_usd
+from src.portfolio.fx import FxQuote, Rates, build_rates, from_usd
from src.portfolio.normalization import (
STABLECOINS,
account_cash_usd,
@@ -139,7 +139,7 @@ class PortfolioService:
get_positions: Callable[..., dict[str, Any]] | None = None,
get_quote: Callable[..., dict[str, Any]] | None = None,
get_longbridge_quotes: Callable[..., dict[str, Any]] | None = None,
- fx_fetcher: Callable[[], tuple[Decimal, Decimal, str]] | None = None,
+ fx_fetcher: Callable[[], FxQuote | tuple[Decimal, Decimal, str]] | None = None,
progress_callback: Callable[[str, str, str | None], None] | None = None,
) -> None:
"""Wire the service to its stores and connector read functions.
@@ -156,8 +156,8 @@ class PortfolioService:
``src.trading.service.get_quote``.
get_longbridge_quotes: Optional batch quote reader used only for
Longbridge positions the connector reports without a price.
- fx_fetcher: Returns ``(usd_cny, usd_hkd, fetched_at)``. Defaults to
- the built-in HTTPS fetch.
+ fx_fetcher: Returns a dated FxQuote (or the legacy CNY/HKD tuple
+ for injected readers). Defaults to the reference-rate HTTPS fetch.
progress_callback: Called as ``(source_id, status, error)`` while a
refresh walks its sources.
"""
@@ -211,6 +211,7 @@ class PortfolioService:
return source_catalog(
self.settings_store.load(),
self.settings_store.connection_store,
+ self.settings_store.import_store,
)
def _connection_profile(self, source: PortfolioSource):
@@ -222,6 +223,8 @@ class PortfolioService:
Returns:
A ``(connection, profile)`` pair.
"""
+ if source.source_kind != "connection":
+ raise ValueError("file imports have no broker connection")
connection = self.settings_store.connection_store.get(source.connection_id)
return connection, profile_by_id(connection.profile_id)
@@ -245,9 +248,12 @@ class PortfolioService:
sources = [source for source in settings.sources if source.enabled]
if not sources:
raise RuntimeError("Add and enable at least one read-only account on the Portfolio page before refreshing")
- usd_cny, usd_hkd, fx_at, fx_stale = self._rates()
- rates = build_rates(usd_cny, usd_hkd)
+ quote, fx_stale = self._rates()
+ rates = quote.rates
+ usd_cny, usd_hkd, fx_at = rates["CNY"], rates["HKD"], quote.fetched_at
display_currency = settings.display_currency
+ if display_currency not in rates:
+ raise RuntimeError(f"FX rate for {display_currency} is unavailable; refresh when the reference feed recovers")
refreshed_at = _now()
results: dict[str, dict[str, Any]] = {}
# The Longbridge Python SDK wraps a native runtime whose contexts are
@@ -283,10 +289,16 @@ class PortfolioService:
accounts: list[dict[str, Any]] = []
for source in sources:
result = results[source.id]
- connection, profile = self._connection_profile(source)
- broker = profile.connector
+ if source.source_kind == "extraetf":
+ profile = None
+ profile_id = None
+ broker = "extraetf"
+ else:
+ connection, profile = self._connection_profile(source)
+ profile_id = connection.profile_id
+ broker = profile.connector
if result["status"] != "ok":
- accounts.append(self._failed_account(source, connection.profile_id, profile, result))
+ accounts.append(self._failed_account(source, profile_id, profile, result))
continue
try:
broker_positions = [
@@ -327,7 +339,7 @@ class PortfolioService:
}
accounts.append(
self._failed_account(
- source, connection.profile_id, profile, failure
+ source, profile_id, profile, failure
)
)
if self._progress_callback is not None:
@@ -337,9 +349,11 @@ class PortfolioService:
accounts.append(
{
"source_id": source.id,
- "profile_id": connection.profile_id,
+ "profile_id": profile_id,
"label": source.label,
"broker": broker,
+ "source_kind": source.source_kind,
+ "import_metadata": result.get("import_metadata"),
"status": "ok",
"last_success_at": refreshed_at,
"total_usd": _number(account_total),
@@ -353,8 +367,8 @@ class PortfolioService:
"position_count": len(broker_positions),
"priced_position_count": priced_count,
"unpriced_position_count": len(broker_positions) - priced_count,
- "auth": auth_metadata(profile),
- "portfolio_compatibility": profile_compatibility(profile),
+ "auth": auth_metadata(profile) if profile is not None else None,
+ "portfolio_compatibility": profile_compatibility(profile) if profile is not None else None,
}
)
positions.extend(broker_positions)
@@ -402,6 +416,8 @@ class PortfolioService:
code: _number(rate) for code, rate in sorted(rates.items())
},
"fetched_at": fx_at,
+ "as_of": quote.as_of,
+ "source": quote.source,
"stale": fx_stale,
},
"accounts": accounts,
@@ -419,8 +435,8 @@ class PortfolioService:
def _failed_account(
self,
source: PortfolioSource,
- profile_id: str,
- profile: TradingProfile,
+ profile_id: str | None,
+ profile: TradingProfile | None,
result: dict[str, Any],
) -> dict[str, Any]:
"""Build the account row for a source that could not be read.
@@ -444,7 +460,8 @@ class PortfolioService:
"source_id": source.id,
"profile_id": profile_id,
"label": source.label,
- "broker": profile.connector,
+ "broker": profile.connector if profile is not None else "extraetf",
+ "source_kind": source.source_kind,
"status": "error",
"error": result.get("error"),
"error_code": result.get("error_code"),
@@ -455,8 +472,8 @@ class PortfolioService:
"total_cny": None,
"total_display": None,
"position_count": 0,
- "auth": auth_metadata(profile),
- "portfolio_compatibility": profile_compatibility(profile),
+ "auth": auth_metadata(profile) if profile is not None else None,
+ "portfolio_compatibility": profile_compatibility(profile) if profile is not None else None,
}
def latest(self) -> dict[str, Any] | None:
@@ -478,6 +495,12 @@ class PortfolioService:
if not enabled or observed != enabled:
return None
+ for source in enabled_sources:
+ if source.source_kind == "extraetf" and any(row.get("source_id") == source.id and row.get("status") == "ok" for row in snapshot["accounts"]):
+ try:
+ self.settings_store.import_store.get(source.id, require_fresh=True)
+ except ValueError:
+ return None
compatibility_by_source = {}
for source in enabled_sources:
try:
@@ -629,6 +652,7 @@ class PortfolioService:
"unrealized_pnl_usd",
"priced",
"updated_at",
+ "portfolio_id", "portfolio_name", "instrument_id_kind", "source_mtime", "as_of_source",
]
output = io.StringIO()
writer = csv.DictWriter(output, fieldnames=fields, extrasaction="ignore")
@@ -660,6 +684,7 @@ class PortfolioService:
market_value = _decimal(row.get("market_value_usd"))
holdings.append(
{
+ "canonical_id": row["canonical_id"],
"symbol": row["symbol"],
"asset_type": row["asset_type"],
"markets": row["markets"],
@@ -686,6 +711,11 @@ class PortfolioService:
"asset_provider_type": row["broker"],
"status": row["status"],
"total_usd": row.get("total_usd"),
+ "source_kind": row.get("source_kind", "connection"),
+ "file_evidence": {
+ key: row["import_metadata"].get(key)
+ for key in ("source_mtime", "as_of_source", "expires_at", "valuation_basis", "cash_included")
+ } if row.get("import_metadata") else None,
}
for index, row in enumerate(snapshot["accounts"])
],
@@ -695,6 +725,15 @@ class PortfolioService:
"privacy": "No account numbers, credentials, order IDs, names, or local paths included.",
}
+ def rebalance(self, snapshot_id: str, target_weights: dict[str, Any]) -> dict[str, Any]:
+ """Return value-only allocation changes against one explicitly pinned snapshot."""
+ from src.portfolio.rebalance import propose_rebalance
+
+ snapshot = self.snapshot_by_id(snapshot_id)
+ if snapshot is None:
+ raise ValueError("portfolio snapshot unavailable")
+ return propose_rebalance(snapshot, target_weights)
+
@staticmethod
def _risk_xray_symbol(position: dict[str, Any]) -> str | None:
"""Map one held position onto a symbol the market-data loaders accept.
@@ -712,6 +751,8 @@ class PortfolioService:
Returns:
A loader-routable symbol, or ``None`` when the market is unknown.
"""
+ if position.get("instrument_id_kind") or position.get("source_kind") == "extraetf":
+ return None # An ISIN or exported pair is not an observed listing/venue.
symbol = str(position.get("symbol") or "").strip().upper()
if not symbol:
return None
@@ -793,7 +834,8 @@ class PortfolioService:
if currency == "HKD" or market == "HK" or symbol.endswith(".HK")
else ("CRYPTO" if row.get("asset_type") in {"crypto", "stablecoin"} else "US")
)
- key = f"{region}:{canonical}"
+ key = (f"{row['instrument_id_kind'].upper()}:{row['instrument_id']}"
+ if row.get("instrument_id_kind") else f"{region}:{canonical}")
item = grouped.setdefault(
key,
{
@@ -846,6 +888,8 @@ class PortfolioService:
RuntimeError: If the profile is not read-only, or either connector
read returns a non-success status.
"""
+ if source.source_kind == "extraetf":
+ return self.settings_store.import_store.collect(source)
connection, profile = self._connection_profile(source)
if not profile.readonly:
raise RuntimeError("portfolio sources must use a read-only connector profile")
@@ -1013,44 +1057,42 @@ class PortfolioService:
raise RuntimeError("Longbridge isolated reader returned an incomplete payload")
return payload
- def _rates(self) -> tuple[Decimal, Decimal, str, bool]:
- """Return the USD/CNY and USD/HKD rates used to value this snapshot.
-
- Returns:
- ``(usd_cny, usd_hkd, fetched_at, stale)`` where ``stale`` marks a
- fall back to the cached rates.
-
- Raises:
- RuntimeError: If the fetch fails and no cached pair exists.
- """
+ def _rates(self) -> tuple[FxQuote, bool]:
+ """Fetch a validated quote or fall back to one coherent cached quote."""
try:
- usd_cny, usd_hkd, fetched_at = self._fx_fetcher()
- self.store.save_fx("USD", "CNY", str(usd_cny), fetched_at)
- self.store.save_fx("USD", "HKD", str(usd_hkd), fetched_at)
- return usd_cny, usd_hkd, fetched_at, False
+ result = self._fx_fetcher()
+ if isinstance(result, FxQuote):
+ quote = result.validated()
+ else:
+ cny, hkd, fetched = result # Backwards-compatible injected readers.
+ quote = FxQuote(build_rates(cny, hkd), fetched).validated()
+ self.store.save_fx_quote(quote.to_dict())
+ return quote, False
except Exception:
- cny = self.store.load_fx("USD", "CNY")
- hkd = self.store.load_fx("USD", "HKD")
+ cached = self.store.load_fx_quote()
+ if cached is not None:
+ return FxQuote(**cached).validated(), True
+ cny, hkd = self.store.load_fx("USD", "CNY"), self.store.load_fx("USD", "HKD")
if cny is None or hkd is None:
raise RuntimeError("FX service unavailable and no prior USD/CNY + USD/HKD cache exists")
- return _decimal(cny[0]), _decimal(hkd[0]), min(cny[1], hkd[1]), True
+ return FxQuote(build_rates(Decimal(cny[0]), Decimal(hkd[0])), min(cny[1], hkd[1]),
+ source="legacy_cache").validated(), True
@staticmethod
- def _fetch_fx() -> tuple[Decimal, Decimal, str]:
- """Fetch USD/CNY and USD/HKD from the public reference-rate endpoint.
-
- Returns:
- ``(usd_cny, usd_hkd, fetched_at)``.
- """
- url = "https://api.frankfurter.app/latest?from=USD&to=CNY,HKD"
+ def _fetch_fx() -> FxQuote:
+ """Read Frankfurter v1's dated reference rates; no intraday FX claim."""
+ url = "https://api.frankfurter.app/latest?from=USD&to=CNY,HKD,EUR"
request = urllib.request.Request(url, headers={"User-Agent": "Vibe-Trading/portfolio"})
with urllib.request.urlopen(request, timeout=8) as response: # noqa: S310 - fixed HTTPS host
payload = json.load(response)
- return (
- _decimal(payload["rates"]["CNY"]),
- _decimal(payload["rates"]["HKD"]),
- _now(),
- )
+ if payload.get("base") != "USD" or payload.get("amount") != 1:
+ raise RuntimeError("FX response does not declare a one-USD base")
+ observed = date.fromisoformat(payload["date"])
+ if observed > datetime.now(timezone.utc).date():
+ raise RuntimeError("FX response date is in the future")
+ rates = {code: Decimal(str(payload["rates"][code])) for code in ("CNY", "HKD", "EUR")}
+ return FxQuote({"USD": Decimal(1), **rates}, _now(), observed.isoformat(),
+ "Frankfurter v1 reference rates").validated()
@staticmethod
def _warnings(accounts: list[dict[str, Any]], positions: list[dict[str, Any]], fx_stale: bool) -> list[str]:
@@ -1065,10 +1107,21 @@ class PortfolioService:
English warning strings, safe to render verbatim in any UI.
"""
warnings = []
+ for account in accounts:
+ metadata = account.get("import_metadata")
+ if metadata:
+ warnings.append(
+ f"extraETF file modified {metadata['source_mtime']}; file mtime is not a price observation. "
+ f"Expires {metadata['expires_at']} under your freshness policy. "
+ "Totals cover exported holdings only; cash and unexported assets are not included. "
+ "ISIN/venue identity is unresolved, so these holdings are excluded from risk-series tools."
+ )
+ if any(row.get("source_kind") == "extraetf" for row in accounts) and len(accounts) > 1:
+ warnings.append("Imported views may overlap other selected sources; duplicate accounts cannot be detected. Select disjoint sources only.")
if fx_stale:
warnings.append(
"Exchange-rate service unavailable; valued with the last "
- "successfully fetched USD/CNY and USD/HKD rates."
+ "successfully fetched reference rates; see the recorded FX date."
)
failed = [str(row.get("label") or row["broker"]) for row in accounts if row["status"] != "ok"]
if failed:
@@ -1097,7 +1150,7 @@ class PortfolioService:
experimental = [
str(row.get("label") or row.get("broker"))
for row in accounts
- if row.get("portfolio_compatibility", {}).get("level") == "experimental"
+ if (row.get("portfolio_compatibility") or {}).get("level") == "experimental"
]
if experimental:
warnings.append(
diff --git a/agent/src/portfolio/store.py b/agent/src/portfolio/store.py
index 80023c1c6..67e3fe4cf 100644
--- a/agent/src/portfolio/store.py
+++ b/agent/src/portfolio/store.py
@@ -64,6 +64,9 @@ class PortfolioStore:
);
CREATE INDEX IF NOT EXISTS idx_portfolio_snapshots_created
ON portfolio_snapshots(created_at DESC);
+ CREATE TABLE IF NOT EXISTS portfolio_fx_quotes (
+ id INTEGER PRIMARY KEY CHECK (id = 1), payload TEXT NOT NULL
+ );
CREATE TABLE IF NOT EXISTS portfolio_fx_cache (
base TEXT NOT NULL,
quote TEXT NOT NULL,
@@ -195,6 +198,8 @@ class PortfolioStore:
"total_usd": row["total_usd"],
"total_cny": row["total_cny"],
"total_hkd": total_hkd,
+ "total_eur": (str(Decimal(row["total_usd"]) * Decimal(str(payload["fx"]["rates"]["EUR"])))
+ if payload.get("fx", {}).get("rates", {}).get("EUR") else None),
}
)
if len(history) >= row_limit:
@@ -283,3 +288,15 @@ class PortfolioStore:
(base, quote),
).fetchone()
return (str(row["rate"]), str(row["fetched_at"])) if row else None
+
+
+ def save_fx_quote(self, payload: dict[str, Any]) -> None:
+ """Atomically cache a whole observation, preserving its rate date."""
+ with self._connect() as db:
+ db.execute("INSERT OR REPLACE INTO portfolio_fx_quotes VALUES (1, ?)", (json.dumps(payload),))
+
+ def load_fx_quote(self) -> dict[str, Any] | None:
+ """Read one complete cached observation, never a mixture of rate dates."""
+ with self._connect() as db:
+ row = db.execute("SELECT payload FROM portfolio_fx_quotes WHERE id = 1").fetchone()
+ return json.loads(row[0]) if row else None
diff --git a/agent/src/tools/portfolio_tool.py b/agent/src/tools/portfolio_tool.py
index 4a0772792..cb534051c 100644
--- a/agent/src/tools/portfolio_tool.py
+++ b/agent/src/tools/portfolio_tool.py
@@ -15,7 +15,7 @@ class PortfolioSummaryTool(BaseTool):
name = "portfolio_summary"
description = (
"Read the latest sanitized snapshot of the user's locally configured "
- "read-only brokerage accounts. Returns deterministic totals, account "
+ "read-only brokerage accounts and explicitly imported holdings. Returns deterministic totals, account "
"allocation, combined holdings, weights, unrealized P/L, data-quality "
"warnings, and risk_xray_args (symbols + weights) that can be passed "
"straight to the portfolio_risk_xray tool. A source that failed to "
@@ -37,6 +37,10 @@ class PortfolioSummaryTool(BaseTool):
"immutable observation instead of the latest one."
),
},
+ "target_weights": {
+ "type": "object", "additionalProperties": {"type": "number"},
+ "description": "Optional user-defined allocation fractions summing to 1, keyed by holdings canonical_id or CASH. Requires snapshot_id. Returns value-only proposals; never sends orders. Do not invent user targets.",
+ },
},
"required": [],
}
@@ -72,4 +76,12 @@ class PortfolioSummaryTool(BaseTool):
},
ensure_ascii=False,
)
- return json.dumps({"status": "ok", "context": context}, ensure_ascii=False)
+ result = {"status": "ok", "context": context}
+ if kwargs.get("target_weights") is not None:
+ if not snapshot_id:
+ return json.dumps({"status": "error", "message": "target_weights requires snapshot_id"})
+ try:
+ result["proposal"] = PortfolioService().rebalance(snapshot_id, kwargs["target_weights"])
+ except ValueError as exc:
+ return json.dumps({"status": "error", "message": str(exc)})
+ return json.dumps(result, ensure_ascii=False)
diff --git a/agent/tests/test_extraetf_integration.py b/agent/tests/test_extraetf_integration.py
new file mode 100644
index 000000000..b751ae3db
--- /dev/null
+++ b/agent/tests/test_extraetf_integration.py
@@ -0,0 +1,191 @@
+"""File evidence remains dated, complete, distinct from broker account identity."""
+
+from __future__ import annotations
+
+import json
+from datetime import datetime, timedelta, timezone
+from decimal import Decimal
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from src.portfolio.config import PortfolioSettingsStore
+from src.portfolio.fx import FxQuote
+from src.portfolio.imports import PortfolioImportStore
+from src.portfolio.rebalance import propose_rebalance
+from src.portfolio.service import PortfolioService
+from src.portfolio.store import PortfolioStore
+
+HEADER = "ISIN;Name;Typ;Anzahl;Kaufpreis;Aktueller Kurs;Aktueller Wert;Währung;Wechselkurs;Region;Land;Sektor;Portfolioname;Portfolio ID"
+CSV = HEADER + "\n" + "IE00B4L5Y983;Example ETF;ETF;10;8;10;100;EUR;1;Welt;;;Private account;one\n" + "IE00B4L5Y983;Example ETF;ETF;20;8;10;200;EUR;1;Welt;;;Other private account;two\n"
+NOW = datetime.now(timezone.utc)
+
+
+def create(store, **overrides):
+ values = dict(csv_text=CSV, label="Private import", source_mtime=(NOW - timedelta(hours=1)).isoformat(),
+ expected_positions=2, max_age_days=7)
+ values.update(overrides)
+ return store.create(**values)
+
+
+def service(tmp_path, *, rates=None):
+ settings = PortfolioSettingsStore(tmp_path / "portfolio.json")
+ imported = create(settings.import_store)
+ settings.save({"display_currency": "EUR", "sources": [{"connection_id": imported["id"], "source_kind": "extraetf", "label": "Private import"}]})
+ def no_broker(*args, **kwargs):
+ pytest.fail("file import must never call a broker")
+ instance = PortfolioService(
+ PortfolioStore(tmp_path / "snapshots.sqlite3"), settings_store=settings,
+ get_account=no_broker, get_positions=no_broker, get_quote=no_broker,
+ fx_fetcher=lambda: FxQuote(rates or {"USD": Decimal(1), "CNY": Decimal(7), "HKD": Decimal(8), "EUR": Decimal("0.9")},
+ NOW.isoformat(), NOW.date().isoformat()),
+ )
+ return instance, imported
+
+
+def test_import_refresh_context_and_proposal_share_real_store(tmp_path):
+ instance, imported = service(tmp_path)
+ snapshot = instance.refresh()
+ assert snapshot["complete"]
+ assert snapshot["totals"]["display"] == pytest.approx(300)
+ assert snapshot["totals"]["usd"] == pytest.approx(333.33333333)
+ assert len(snapshot["positions"]) == 2
+ assert {row["portfolio_id"] for row in snapshot["positions"]} == {"one", "two"}
+ assert all(row["updated_at"] is None for row in snapshot["positions"])
+ assert snapshot["accounts"][0]["auth"] is None
+ assert instance.latest()["snapshot_id"] == snapshot["snapshot_id"]
+ assert float(instance.history()[0]["total_eur"]) == pytest.approx(300)
+ context = instance.analysis_context(snapshot["snapshot_id"])
+ assert context["risk_xray_args"] == {"symbols": [], "weights": {}}
+ assert len(context["holdings"]) == 1
+ key = context["holdings"][0]["canonical_id"]
+ assert key == "ISIN:IE00B4L5Y983"
+ serialized = json.dumps(context)
+ for private in ("Private import", "Private account", "Other private account", "portfolio_id", str(tmp_path)):
+ assert private not in serialized
+ assert context["account_allocation"][0]["file_evidence"]["source_mtime"] == imported["source_mtime"]
+ result = instance.rebalance(snapshot["snapshot_id"], {key: 0.6, "CASH": 0.4})
+ assert result["mode"] == "proposal_only"
+ assert result["currency"] == "EUR"
+ assert {row["canonical_id"]: row["change_value"] for row in result["rows"]} == pytest.approx({key: -120, "CASH": 120})
+ assert "portfolio_id" in instance.export_csv()
+ assert instance.sources()[0]["source_kind"] == "extraetf"
+
+
[email protected]("override,match", [
+ ({"expected_positions": 3}, "expected 3"),
+ ({"source_mtime": "2000-01-01T00:00:00Z"}, "stale"),
+ ({"source_mtime": (NOW + timedelta(days=1)).isoformat()}, "future"),
+ ({"source_mtime": "2026-10-01T00:00:00"}, "timezone"),
+ ({"csv_text": CSV.replace(";10;100;", ";;100;")}, "positive exported price"),
+ ({"csv_text": CSV.replace(";two", ";one")}, "twice"),
+ ({"expected_positions": True}, "integer"),
+ ({"max_age_days": False}, "integer"),
+ ({"csv_text": CSV.replace("EUR", "XYZ")}, "currency"),
+])
+def test_bad_import_never_persists_a_partial_source(tmp_path, override, match):
+ store = PortfolioImportStore(tmp_path / "imports.sqlite3")
+ with pytest.raises(ValueError, match=match):
+ create(store, **override)
+ assert store.list() == []
+
+
+def test_expired_import_is_an_error_and_never_uses_old_positions(tmp_path):
+ instance, imported = service(tmp_path)
+ healthy = instance.refresh()
+ with instance.settings_store.import_store._connect() as db:
+ payload = instance.settings_store.import_store.get(imported["id"])
+ payload["expires_at"] = "2000-01-01T00:00:00Z"
+ db.execute("UPDATE imports SET payload = ? WHERE id = ?", (json.dumps(payload), imported["id"]))
+ assert instance.latest() is None
+ failed = instance.refresh()
+ assert failed["complete"] is False
+ assert failed["positions"] == []
+ assert failed["totals"]["usd"] == 0
+ assert failed["accounts"][0]["status"] == "error"
+ assert failed["accounts"][0]["last_success_at"] == healthy["created_at"]
+
+
+def test_missing_eur_rate_fails_the_import_source_without_usd_fallback(tmp_path):
+ instance, _ = service(tmp_path, rates={"USD": Decimal(1), "CNY": Decimal(7), "HKD": Decimal(8)})
+ instance.save_settings({**instance.settings(), "display_currency": "USD"})
+ result = instance.refresh()
+ assert result["complete"] is False
+ assert "EUR" in result["accounts"][0]["error"]
+ assert result["positions"] == []
+
+
[email protected]("targets", [{"UNKNOWN": 1}, {"CASH": 0.9}, {"CASH": True}, {"CASH": float("nan")}, {"CASH": 1.1}])
+def test_rebalance_rejects_guessed_or_invalid_targets(tmp_path, targets):
+ instance, _ = service(tmp_path)
+ snapshot = instance.refresh()
+ with pytest.raises(ValueError):
+ instance.rebalance(snapshot["snapshot_id"], targets)
+
+
+def test_rebalance_requires_complete_unexpired_evidence(tmp_path):
+ instance, _ = service(tmp_path)
+ snapshot = instance.refresh()
+ snapshot["accounts"][0]["import_metadata"]["expires_at"] = "2000-01-01T00:00:00Z"
+ with pytest.raises(ValueError, match="stale"):
+ propose_rebalance(snapshot, {"CASH": 1})
+ snapshot["complete"] = False
+ with pytest.raises(ValueError, match="complete"):
+ propose_rebalance(snapshot, {"CASH": 1})
+
+
+def test_fx_http_shape_date_and_eur_then_coherent_cache(tmp_path, monkeypatch):
+ import io
+ import src.portfolio.service as module
+ payload = {"amount": 1, "base": "USD", "date": NOW.date().isoformat(), "rates": {"CNY": 7, "HKD": 8, "EUR": 0.9}}
+ seen = []
+ def fetch(request, **kwargs):
+ seen.append(request.full_url)
+ return io.BytesIO(json.dumps(payload).encode())
+ monkeypatch.setattr(module.urllib.request, "urlopen", fetch)
+ instance, _ = service(tmp_path)
+ instance._fx_fetcher = instance._fetch_fx
+ snapshot = instance.refresh()
+ assert seen == ["https://api.frankfurter.app/latest?from=USD&to=CNY,HKD,EUR"]
+ assert snapshot["fx"]["as_of"] == NOW.date().isoformat()
+ payload["rates"]["EUR"] = -1
+ cached = instance.refresh()
+ assert cached["fx"]["stale"]
+ assert cached["fx"]["rates"] == snapshot["fx"]["rates"]
+ assert cached["fx"]["fetched_at"] == snapshot["fx"]["fetched_at"]
+
+
+def test_http_import_settings_refresh_and_rebalance_use_same_store(tmp_path, monkeypatch):
+ from src.api import portfolio_routes
+ from src.api.security import require_auth, require_settings_write_auth
+ instance, _ = service(tmp_path)
+ monkeypatch.setattr(portfolio_routes, "PortfolioService", lambda **kwargs: instance)
+ app = FastAPI()
+ app.dependency_overrides[require_auth] = lambda: None
+ app.dependency_overrides[require_settings_write_auth] = lambda: None
+ portfolio_routes.register_portfolio_routes(app)
+ client = TestClient(app)
+ result = client.post("/api/portfolio/imports/extraetf", json={
+ "csv_text": CSV, "label": "Web import", "source_mtime": (NOW - timedelta(hours=1)).isoformat(),
+ "expected_positions": 2, "max_age_days": 7,
+ })
+ assert result.status_code == 200, result.text
+ imported = result.json()["import"]
+ assert "positions" not in imported
+ settings = {"display_currency": "EUR", "sources": [{"connection_id": imported["id"], "source_kind": "extraetf", "label": "Web import"}]}
+ assert client.put("/api/portfolio/settings", json=settings).status_code == 200
+ snapshot = client.post("/api/portfolio/refresh").json()["snapshot"]
+ proposal = client.post("/api/portfolio/rebalance", json={"snapshot_id": snapshot["snapshot_id"], "target_weights": {"CASH": 1}})
+ assert proposal.status_code == 200, proposal.text
+ assert proposal.json()["proposal"]["rows"][0]["change_value"] == pytest.approx(300)
+
+
+def test_two_imports_cannot_double_count_the_same_underlying_portfolios(tmp_path):
+ settings = PortfolioSettingsStore(tmp_path / "portfolio.json")
+ first, second = create(settings.import_store), create(settings.import_store)
+ sources = [{"connection_id": item["id"], "source_kind": "extraetf", "label": item["label"]} for item in (first, second)]
+ with pytest.raises(ValueError, match="overlapping Portfolio IDs"):
+ settings.save({"sources": sources})
+ sources[0]["enabled"] = False
+ assert len(settings.save({"sources": sources}).sources) == 2
diff --git a/agent/tests/test_portfolio_fx.py b/agent/tests/test_portfolio_fx.py
index ecaf1b019..14f975668 100644
--- a/agent/tests/test_portfolio_fx.py
+++ b/agent/tests/test_portfolio_fx.py
@@ -73,8 +73,8 @@ def test_account_total_converts_a_valid_iso_currency_when_rated() -> None:
def test_parse_settings_rejects_valid_iso_display_currency_without_production_rate() -> (
None
):
- with pytest.raises(ValueError, match="EUR.*no production FX rate"):
- parse_settings({"display_currency": "EUR", "sources": []})
+ with pytest.raises(ValueError, match="KRW.*no production FX rate"):
+ parse_settings({"display_currency": "KRW", "sources": []})
def test_parse_settings_accepts_rateable_display_currency() -> None:
diff --git a/agent/tests/test_portfolio_service.py b/agent/tests/test_portfolio_service.py
index dda9e9403..013de315e 100644
--- a/agent/tests/test_portfolio_service.py
+++ b/agent/tests/test_portfolio_service.py
@@ -340,8 +340,8 @@ def test_unrated_balance_currency_fails_only_that_source(tmp_path):
def test_display_currency_without_production_rate_is_rejected_on_save(tmp_path):
store = PortfolioSettingsStore(tmp_path / "portfolio.json")
- with pytest.raises(ValueError, match="EUR.*no production FX rate"):
- store.save({"display_currency": "EUR", "sources": []})
+ with pytest.raises(ValueError, match="KRW.*no production FX rate"):
+ store.save({"display_currency": "KRW", "sources": []})
def test_failed_source_is_excluded_from_totals_and_reports_its_last_success(tmp_path):
diff --git a/frontend/src/components/portfolio/ExtraEtfImport.tsx b/frontend/src/components/portfolio/ExtraEtfImport.tsx
new file mode 100644
index 000000000..f2b8a640b
--- /dev/null
+++ b/frontend/src/components/portfolio/ExtraEtfImport.tsx
@@ -0,0 +1,38 @@
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { api } from "@/lib/api";
+
+const fieldClass = "w-full rounded-md border bg-background px-3 py-2 text-sm";
+
+/** Explicit local export import; the user still selects it in portfolio sources. */
+export function ExtraEtfImport({ onImported }: { onImported: () => Promise<void> }) {
+ const { t } = useTranslation();
+ const [file, setFile] = useState<File | null>(null);
+ const [label, setLabel] = useState("");
+ const [count, setCount] = useState("");
+ const [age, setAge] = useState("7");
+ const [busy, setBusy] = useState(false);
+ const [message, setMessage] = useState("");
+ return <form className="space-y-3 rounded-lg border p-4" onSubmit={async (event) => {
+ event.preventDefault();
+ if (!file || busy) return;
+ setBusy(true); setMessage("");
+ try {
+ if (file.size > 4 * 1024 * 1024) throw new Error(t("portfolio.imports.tooLarge"));
+ await api.importExtraEtf({ csv_text: await file.text(), label, source_mtime: new Date(file.lastModified).toISOString(), expected_positions: Number(count), max_age_days: Number(age) });
+ await onImported();
+ setMessage(t("portfolio.imports.success"));
+ } catch (error) { setMessage(error instanceof Error ? error.message : String(error)); }
+ finally { setBusy(false); }
+ }}>
+ <h3 className="font-medium">{t("portfolio.imports.title")}</h3>
+ <p className="text-xs text-muted-foreground">{t("portfolio.imports.hint")}</p>
+ <label className="block text-sm">{t("portfolio.imports.file")}<input required disabled={busy} type="file" accept=".csv,text/csv" className={fieldClass} onChange={(event) => { setFile(event.target.files?.[0] ?? null); setMessage(""); }} /></label>
+ <label className="block text-sm">{t("portfolio.editor.accountLabel")}<input required maxLength={80} disabled={busy} value={label} onChange={(event) => setLabel(event.target.value)} className={fieldClass} /></label>
+ <label className="block text-sm">{t("portfolio.imports.count")}<input required type="number" min="0" max="20000" step="1" disabled={busy} value={count} onChange={(event) => setCount(event.target.value)} className={fieldClass} /></label>
+ <label className="block text-sm">{t("portfolio.imports.age")}<input required type="number" min="1" max="365" step="1" disabled={busy} value={age} onChange={(event) => setAge(event.target.value)} className={fieldClass} /></label>
+ <p className="text-xs text-muted-foreground">{t("portfolio.imports.overlap")}</p>
+ <button type="submit" disabled={busy || !file} className="rounded-md border px-3 py-2 text-sm disabled:opacity-50">{busy ? t("portfolio.imports.importing") : t("portfolio.imports.import")}</button>
+ {message && <p role="status" className="text-sm">{message}</p>}
+ </form>;
+}
diff --git a/frontend/src/components/portfolio/PortfolioSourceEditor.tsx b/frontend/src/components/portfolio/PortfolioSourceEditor.tsx
index 205885ca2..e77000704 100644
--- a/frontend/src/components/portfolio/PortfolioSourceEditor.tsx
+++ b/frontend/src/components/portfolio/PortfolioSourceEditor.tsx
@@ -1,6 +1,7 @@
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { ArrowDown, ArrowUp, Plus, Save, Trash2, X } from "lucide-react";
+import { ExtraEtfImport } from "@/components/portfolio/ExtraEtfImport";
import { ConnectionCenter } from "@/components/portfolio/ConnectionCenter";
import type {
PortfolioSettings,
@@ -81,10 +82,11 @@ export function PortfolioSourceEditor({ open, settings, catalog, saving, onClose
...draft,
sources: [...draft.sources, {
connection_id: connection.connection_id,
+ source_kind: connection.source_kind ?? "connection",
label: connection.label,
enabled: true,
order: draft.sources.length,
- include_cash: true,
+ include_cash: connection.source_kind !== "extraetf",
}],
});
setConnectionToAdd("");
@@ -98,7 +100,7 @@ export function PortfolioSourceEditor({ open, settings, catalog, saving, onClose
</header>
<div className="flex-1 space-y-6 overflow-y-auto p-5">
- <fieldset><legend className="text-sm font-medium">{t("portfolio.editor.currency")}</legend><div className="mt-2 grid grid-cols-3 gap-2">{(["USD", "CNY", "HKD"] as const).map((currency) => <button key={currency} type="button" onClick={() => setDraft({ ...draft, display_currency: currency })} className={`rounded-md border px-3 py-2 text-sm ${draft.display_currency === currency ? "border-primary bg-primary/5 text-primary" : "bg-card"}`}>{currency}</button>)}</div></fieldset>
+ <fieldset><legend className="text-sm font-medium">{t("portfolio.editor.currency")}</legend><div className="mt-2 grid grid-cols-4 gap-2">{(["USD", "CNY", "HKD", "EUR"] as const).map((currency) => <button key={currency} type="button" onClick={() => setDraft({ ...draft, display_currency: currency })} className={`rounded-md border px-3 py-2 text-sm ${draft.display_currency === currency ? "border-primary bg-primary/5 text-primary" : "bg-card"}`}>{currency}</button>)}</div></fieldset>
<section>
<div className="flex items-end justify-between gap-3"><div><h3 className="text-sm font-medium">{t("portfolio.editor.selected")}</h3><p className="mt-1 text-xs text-muted-foreground">{t("portfolio.editor.selectedHint")}</p></div><span className="text-xs text-muted-foreground">{draft.sources.length}</span></div>
@@ -108,10 +110,10 @@ export function PortfolioSourceEditor({ open, settings, catalog, saving, onClose
return <article key={source.connection_id} className="rounded-lg border bg-card p-4">
<div className="flex items-start gap-3">
<input type="checkbox" checked={source.enabled} onChange={(event) => updateSource(index, { enabled: event.target.checked })} className="mt-2 h-4 w-4 accent-primary" aria-label={t("portfolio.editor.enableAccount")} />
- <div className="min-w-0 flex-1"><input value={source.label} onChange={(event) => updateSource(index, { label: event.target.value })} className={fieldClass} aria-label={t("portfolio.editor.accountLabel")} /><div className="mt-2 flex flex-wrap gap-2 text-xs text-muted-foreground"><span>{connection?.connector.toUpperCase()}</span><span>·</span><span>{connection?.environment === "live" ? t("portfolio.env.live") : t("portfolio.env.paper")}</span><span>·</span><span>{connection?.transport}</span></div></div>
+ <div className="min-w-0 flex-1"><input value={source.label} onChange={(event) => updateSource(index, { label: event.target.value })} className={fieldClass} aria-label={t("portfolio.editor.accountLabel")} /><div className="mt-2 flex flex-wrap gap-2 text-xs text-muted-foreground"><span>{connection?.connector.toUpperCase()}</span><span>·</span><span>{source.source_kind === "extraetf" ? t("portfolio.imports.source") : connection?.environment === "live" ? t("portfolio.env.live") : t("portfolio.env.paper")}</span><span>·</span><span>{connection?.transport}</span></div></div>
<div className="flex gap-1"><button type="button" onClick={() => move(index, -1)} disabled={index === 0} className="rounded p-1.5 hover:bg-muted disabled:opacity-30" aria-label={t("portfolio.editor.moveUp")}><ArrowUp className="h-4 w-4" /></button><button type="button" onClick={() => move(index, 1)} disabled={index === draft.sources.length - 1} className="rounded p-1.5 hover:bg-muted disabled:opacity-30" aria-label={t("portfolio.editor.moveDown")}><ArrowDown className="h-4 w-4" /></button><button type="button" onClick={() => remove(index)} className="rounded p-1.5 text-danger hover:bg-danger/10" aria-label={t("portfolio.editor.removeAccount")}><Trash2 className="h-4 w-4" /></button></div>
</div>
- <label className="mt-3 flex items-center gap-2 text-xs text-muted-foreground"><input type="checkbox" checked={source.include_cash} onChange={(event) => updateSource(index, { include_cash: event.target.checked })} className="h-4 w-4 accent-primary" />{t("portfolio.editor.includeCash")}</label>
+ {source.source_kind !== "extraetf" && <label className="mt-3 flex items-center gap-2 text-xs text-muted-foreground"><input type="checkbox" checked={source.include_cash} onChange={(event) => updateSource(index, { include_cash: event.target.checked })} className="h-4 w-4 accent-primary" />{t("portfolio.editor.includeCash")}</label>}
</article>;
})}
{!draft.sources.length ? <div className="rounded-lg border border-dashed p-8 text-center text-sm text-muted-foreground">{t("portfolio.editor.noAccounts")}</div> : null}
@@ -122,6 +124,7 @@ export function PortfolioSourceEditor({ open, settings, catalog, saving, onClose
<div className="flex items-end justify-between gap-3"><div><h3 className="text-sm font-medium">{t("portfolio.editor.addTitle")}</h3><p className="mt-1 text-xs text-muted-foreground">{t("portfolio.editor.addHint")}</p></div><button type="button" onClick={() => setConnectionCenterOpen(true)} className="shrink-0 text-xs text-primary">{t("portfolio.editor.openConnections")}</button></div>
<div className="mt-3 flex gap-2"><select value={connectionToAdd} onChange={(event) => setConnectionToAdd(event.target.value)} className={fieldClass} aria-label={t("portfolio.editor.addTitle")} disabled={!available.length}><option value="">{available.length ? t("portfolio.editor.chooseConnection") : t("portfolio.editor.noConnections")}</option>{available.map((connection) => <option key={connection.connection_id} value={connection.connection_id}>{connection.label}</option>)}</select><button type="button" onClick={add} disabled={!available.length} className="inline-flex shrink-0 items-center gap-2 rounded-md border px-3 py-2 text-sm disabled:opacity-40"><Plus className="h-4 w-4" />{t("portfolio.editor.add")}</button></div>
</section>
+ <ExtraEtfImport onImported={onConnectionsChanged} />
</div>
<footer className="flex items-center justify-between gap-3 border-t p-5"><p className="text-xs text-muted-foreground">{t("portfolio.editor.footerHint")}</p><div className="flex gap-2"><button type="button" onClick={onClose} className="rounded-md border px-4 py-2 text-sm">{t("portfolio.editor.cancel")}</button><button type="button" disabled={saving} onClick={() => void onSave({ ...draft, sources: draft.sources.map((source, order) => ({ ...source, order })) })} className="inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground disabled:opacity-50"><Save className="h-4 w-4" />{saving ? t("portfolio.editor.saving") : t("portfolio.editor.save")}</button></div></footer>
diff --git a/frontend/src/components/portfolio/RebalanceProposal.tsx b/frontend/src/components/portfolio/RebalanceProposal.tsx
new file mode 100644
index 000000000..f65918a94
--- /dev/null
+++ b/frontend/src/components/portfolio/RebalanceProposal.tsx
@@ -0,0 +1,32 @@
+import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { api, type PortfolioSnapshot, type RebalanceProposal as Proposal } from "@/lib/api";
+
+/** Value-only drift analysis against the exact snapshot shown to the user. */
+export function RebalanceProposal({ snapshot }: { snapshot: PortfolioSnapshot }) {
+ const { t, i18n } = useTranslation();
+ const [targets, setTargets] = useState<Record<string, string>>({});
+ const [proposal, setProposal] = useState<Proposal | null>(null);
+ const [error, setError] = useState("");
+ const [busy, setBusy] = useState(false);
+ useEffect(() => { setTargets({}); setProposal(null); setError(""); }, [snapshot.snapshot_id]);
+ const ids = [...(snapshot.combined_holdings ?? []).flatMap((row) => row.canonical_id ? [row.canonical_id] : []), "CASH"];
+ const money = (value: number) => new Intl.NumberFormat(i18n.language, { style: "currency", currency: proposal?.currency ?? (snapshot.display_currency ?? "USD"), maximumFractionDigits: 2 }).format(value);
+ return <details className="rounded-xl border bg-card p-5">
+ <summary className="cursor-pointer font-semibold">{t("portfolio.rebalance.title")}</summary>
+ <p className="my-3 text-sm text-muted-foreground">{t("portfolio.rebalance.hint")}</p>
+ <form onSubmit={async (event) => {
+ event.preventDefault(); setBusy(true); setError(""); setProposal(null);
+ try {
+ const response = await api.proposePortfolioRebalance(snapshot.snapshot_id, Object.fromEntries(ids.map((id) => [id, Number(targets[id] || 0) / 100])));
+ setProposal(response.proposal);
+ } catch (cause) { setError(cause instanceof Error ? cause.message : String(cause)); }
+ finally { setBusy(false); }
+ }}>
+ <div className="grid max-h-80 gap-2 overflow-y-auto sm:grid-cols-2 lg:grid-cols-3">{ids.map((id) => <label key={id} className="flex items-center justify-between gap-2 rounded-md border p-2 text-sm"><span className="break-all" dir="ltr">{id}</span><input aria-label={t("portfolio.rebalance.target", { id })} type="number" min="0" max="100" step="any" value={targets[id] ?? ""} disabled={busy} onChange={(event) => { setTargets({ ...targets, [id]: event.target.value }); setProposal(null); }} className="w-24 rounded border bg-background p-2" placeholder="0 %" /></label>)}</div>
+ <button disabled={busy || !snapshot.complete || !snapshot.combined_holdings} className="my-3 rounded-md border px-4 py-2 text-sm disabled:opacity-50">{t("portfolio.rebalance.generate")}</button>
+ </form>
+ {error && <p role="alert" className="text-sm text-danger">{error}</p>}
+ {proposal && <div className="overflow-x-auto"><table className="w-full text-sm"><thead><tr><th className="text-start">{t("portfolio.holdings.colSymbol")}</th><th>{t("portfolio.rebalance.current")}</th><th>{t("portfolio.rebalance.targetValue")}</th><th>{t("portfolio.rebalance.change")}</th></tr></thead><tbody>{proposal.rows.map((row) => <tr key={row.canonical_id}><td className="py-2" dir="ltr">{row.canonical_id}</td><td className="text-center">{money(row.current_value)}</td><td className="text-center">{money(row.target_value)}</td><td className="text-center">{money(row.change_value)}</td></tr>)}</tbody></table><p className="mt-2 text-xs text-muted-foreground">{t("portfolio.rebalance.hint")}</p></div>}
+ </details>;
+}
diff --git a/frontend/src/components/portfolio/__tests__/ImportRebalance.test.tsx b/frontend/src/components/portfolio/__tests__/ImportRebalance.test.tsx
new file mode 100644
index 000000000..04d93a68c
--- /dev/null
+++ b/frontend/src/components/portfolio/__tests__/ImportRebalance.test.tsx
@@ -0,0 +1,42 @@
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { beforeEach, expect, it, vi } from "vitest";
+import { ExtraEtfImport } from "../ExtraEtfImport";
+import { RebalanceProposal } from "../RebalanceProposal";
+import { api, type PortfolioSnapshot } from "@/lib/api";
+import i18n from "@/i18n";
+
+vi.mock("@/lib/api", async () => {
+ const actual = await vi.importActual<typeof import("@/lib/api")>("@/lib/api");
+ return { ...actual, api: { ...actual.api, importExtraEtf: vi.fn(), proposePortfolioRebalance: vi.fn() } };
+});
+beforeEach(async () => { vi.clearAllMocks(); await i18n.changeLanguage("en"); });
+
+it("imports with the file's mtime and user-confirmed count and freshness", async () => {
+ vi.mocked(api.importExtraEtf).mockResolvedValue({ status: "ok", import: { id: "extraetf-a" } });
+ const reload = vi.fn().mockResolvedValue(undefined);
+ render(<ExtraEtfImport onImported={reload} />);
+ const file = new File(["original CSV"], "holdings.csv", { type: "text/csv", lastModified: 1791800000000 });
+ Object.defineProperty(file, "text", { value: async () => "original CSV" });
+ fireEvent.change(screen.getByLabelText("Investments CSV"), { target: { files: [file] } });
+ fireEvent.change(screen.getByLabelText("Account label"), { target: { value: "My export" } });
+ fireEvent.change(screen.getByLabelText(/Expected holdings count/), { target: { value: "27" } });
+ fireEvent.change(screen.getByLabelText(/Maximum file age/), { target: { value: "3" } });
+ fireEvent.submit(screen.getByRole("button", { name: "Import file" }).closest("form")!);
+ await waitFor(() => expect(reload).toHaveBeenCalledOnce());
+ expect(api.importExtraEtf).toHaveBeenCalledWith({ csv_text: "original CSV", label: "My export", source_mtime: new Date(file.lastModified).toISOString(), expected_positions: 27, max_age_days: 3 });
+ expect(screen.getByRole("status")).toHaveTextContent("then save and refresh");
+});
+
+it("pins a proposal to the shown snapshot and invalidates it when targets change", async () => {
+ const snapshot = { snapshot_id: "shown", display_currency: "EUR", complete: true, combined_holdings: [{ canonical_id: "ISIN:IE00B4L5Y983", symbol: "IE00B4L5Y983", market_value_usd: 100 }] } as PortfolioSnapshot;
+ vi.mocked(api.proposePortfolioRebalance).mockResolvedValue({ status: "ok", proposal: { mode: "proposal_only", snapshot_id: "shown", currency: "EUR", rows: [{ canonical_id: "ISIN:IE00B4L5Y983", current_value: 100, target_value: 60, change_value: -40 }] } });
+ render(<RebalanceProposal snapshot={snapshot} />);
+ fireEvent.click(screen.getByText("Allocation proposal"));
+ fireEvent.change(screen.getByLabelText("ISIN:IE00B4L5Y983 target (%)"), { target: { value: "60" } });
+ fireEvent.change(screen.getByLabelText("CASH target (%)"), { target: { value: "40" } });
+ fireEvent.click(screen.getByRole("button", { name: "Calculate proposal" }));
+ await screen.findByText("-€40.00");
+ expect(api.proposePortfolioRebalance).toHaveBeenCalledWith("shown", { "ISIN:IE00B4L5Y983": 0.6, CASH: 0.4 });
+ fireEvent.change(screen.getByLabelText("CASH target (%)"), { target: { value: "20" } });
+ expect(screen.queryByText("-€40.00")).not.toBeInTheDocument();
+});
diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.json
index c2671acb0..70be6065b 100644
--- a/frontend/src/i18n/locales/ar.json
+++ b/frontend/src/i18n/locales/ar.json
@@ -2134,7 +2134,7 @@
"badge": "محلي للقراءة فقط · حسابات متعددة",
"title": "المحفظة",
"subtitle": "تقييم واحد يجمع كل الاتصالات المفعّلة للقراءة فقط. الحساب الذي يتعذّر قراءته يظهر كخطأ ولا يُحتسب ضمن الإجماليات.",
- "fxFresh": "USD/CNY {{rate}} · سعر حي",
+ "fxFresh": "USD/CNY {{rate}} · سعر صرف مرجعي",
"fxCached": "USD/CNY {{rate}} · سعر مخزّن",
"manageAccounts": "إدارة الحسابات",
"exportCsv": "تصدير CSV",
@@ -2299,6 +2299,30 @@
"accountDeactivated": " · معطّل",
"accountSave": "استخدام هذا الحساب",
"accountSaved": "تم حفظ الحساب."
+ },
+ "imports": {
+ "title": "استيراد extraETF Investments",
+ "hint": "الحيازات فقط، دون نقد أو أسعار مباشرة. وقت تعديل الملف ليس وقت رصد السعر؛ ولا تحدد رموز ISIN سوق التداول.",
+ "file": "ملف Investments CSV",
+ "count": "عدد الحيازات المتوقع (تحقق منه في extraETF)",
+ "age": "أقصى عمر للملف (بالأيام)",
+ "overlap": "اختر مصادر غير متداخلة. قد يتضمن عرض extraETF حسابات متصلة هنا بالفعل.",
+ "import": "استيراد الملف",
+ "importing": "جارٍ الاستيراد…",
+ "success": "تم الاستيراد. أضف هذا الملف من المصادر المتاحة أعلاه، ثم احفظ وحدّث.",
+ "source": "استيراد ملف",
+ "mtime": "تعديل الملف: {{time}}",
+ "expires": "تنتهي الصلاحية: {{time}}",
+ "tooLarge": "الحد الأقصى للاستيراد هو 4 MiB."
+ },
+ "rebalance": {
+ "title": "مقترح توزيع الأصول",
+ "hint": "أدخل نسباً مستهدفة مجموعها 100%. التغييرات مبالغ للمراجعة فقط؛ لا تُحسب أوامر أو كميات أو ضرائب أو رسوم.",
+ "target": "النسبة المستهدفة لـ {{id}} (%)",
+ "generate": "حساب المقترح",
+ "current": "القيمة الحالية",
+ "targetValue": "القيمة المستهدفة",
+ "change": "تغير القيمة"
}
},
"analysis": {
diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.json
index 63aff2d0c..0a285943e 100644
--- a/frontend/src/i18n/locales/de.json
+++ b/frontend/src/i18n/locales/de.json
@@ -2134,7 +2134,7 @@
"badge": "Lokal & schreibgeschützt · Mehrere Konten",
"title": "Portfolio",
"subtitle": "Eine Bewertung über alle aktivierten schreibgeschützten Verbindungen. Ein Konto, das nicht gelesen werden kann, wird als Fehler gemeldet und bleibt aus den Summen heraus.",
- "fxFresh": "USD/CNY {{rate}} · aktueller Kurs",
+ "fxFresh": "USD/CNY {{rate}} · Referenzkurs",
"fxCached": "USD/CNY {{rate}} · zwischengespeicherter Kurs",
"manageAccounts": "Konten verwalten",
"exportCsv": "CSV exportieren",
@@ -2299,6 +2299,30 @@
"accountDeactivated": " · deaktiviert",
"accountSave": "Dieses Konto verwenden",
"accountSaved": "Konto gespeichert."
+ },
+ "imports": {
+ "title": "extraETF Investments importieren",
+ "hint": "Nur Bestände, ohne Bargeld oder Livekurse. Das Änderungsdatum der Datei ist kein Kurszeitpunkt; den ISINs ist kein Handelsplatz zugeordnet.",
+ "file": "Investments-CSV",
+ "count": "Erwartete Anzahl der Positionen (in extraETF prüfen)",
+ "age": "Maximales Dateialter (Tage)",
+ "overlap": "Wählen Sie überschneidungsfreie Quellen. Eine extraETF-Ansicht kann hier bereits verbundene Konten enthalten.",
+ "import": "Datei importieren",
+ "importing": "Import läuft…",
+ "success": "Importiert. Fügen Sie den Export aus den verfügbaren Quellen oben hinzu, speichern und aktualisieren Sie.",
+ "source": "Dateiimport",
+ "mtime": "Datei geändert: {{time}}",
+ "expires": "Gültig bis: {{time}}",
+ "tooLarge": "Die Importgrenze beträgt 4 MiB."
+ },
+ "rebalance": {
+ "title": "Allokationsvorschlag",
+ "hint": "Geben Sie Zielanteile mit insgesamt 100% ein. Änderungen sind nur zu prüfende Beträge; Orders, Stückzahlen, Steuern und Gebühren werden nicht berechnet.",
+ "target": "Ziel für {{id}} (%)",
+ "generate": "Vorschlag berechnen",
+ "current": "Aktueller Wert",
+ "targetValue": "Zielwert",
+ "change": "Wertänderung"
}
},
"analysis": {
diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json
index 9a8230a93..1a539a16c 100644
--- a/frontend/src/i18n/locales/en.json
+++ b/frontend/src/i18n/locales/en.json
@@ -2134,7 +2134,7 @@
"badge": "Local read-only · Multi-account",
"title": "Portfolio",
"subtitle": "One valuation across the enabled read-only connections. An account that cannot be read is reported as an error and left out of the totals.",
- "fxFresh": "USD/CNY {{rate}} · live rate",
+ "fxFresh": "USD/CNY {{rate}} · reference rate",
"fxCached": "USD/CNY {{rate}} · cached rate",
"manageAccounts": "Manage accounts",
"exportCsv": "Export CSV",
@@ -2299,6 +2299,30 @@
"accountDeactivated": " · deactivated",
"accountSave": "Use this account",
"accountSaved": "Account saved."
+ },
+ "imports": {
+ "title": "Import extraETF Investments",
+ "hint": "Holdings only, without cash or live prices. File modification time is not a price observation; ISINs have no resolved trading venue.",
+ "file": "Investments CSV",
+ "count": "Expected holdings count (confirm in extraETF)",
+ "age": "Maximum file age (days)",
+ "overlap": "Select disjoint sources. An extraETF view may already include accounts connected elsewhere here.",
+ "import": "Import file",
+ "importing": "Importing…",
+ "success": "Imported. Add this export from the available sources above, then save and refresh.",
+ "source": "File import",
+ "mtime": "File modified: {{time}}",
+ "expires": "Expires: {{time}}",
+ "tooLarge": "The import limit is 4 MiB."
+ },
+ "rebalance": {
+ "title": "Allocation proposal",
+ "hint": "Enter target percentages totalling 100%. Changes are amounts for review only; no orders, quantities, taxes or fees are calculated.",
+ "target": "{{id}} target (%)",
+ "generate": "Calculate proposal",
+ "current": "Current value",
+ "targetValue": "Target value",
+ "change": "Value change"
}
},
"analysis": {
diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.json
index af447cad6..e9770503a 100644
--- a/frontend/src/i18n/locales/es.json
+++ b/frontend/src/i18n/locales/es.json
@@ -2134,7 +2134,7 @@
"badge": "Local y solo lectura · Varias cuentas",
"title": "Cartera",
"subtitle": "Una sola valoración de todas las conexiones de solo lectura activas. La cuenta que no se puede leer se marca como error y queda fuera de los totales.",
- "fxFresh": "USD/CNY {{rate}} · tipo en vivo",
+ "fxFresh": "USD/CNY {{rate}} · tipo de referencia",
"fxCached": "USD/CNY {{rate}} · tipo en caché",
"manageAccounts": "Gestionar cuentas",
"exportCsv": "Exportar CSV",
@@ -2299,6 +2299,30 @@
"accountDeactivated": " · desactivada",
"accountSave": "Usar esta cuenta",
"accountSaved": "Cuenta guardada."
+ },
+ "imports": {
+ "title": "Importar extraETF Investments",
+ "hint": "Solo posiciones, sin efectivo ni precios en tiempo real. La fecha del archivo no es la fecha de observación del precio; los ISIN no tienen un mercado resuelto.",
+ "file": "CSV de Investments",
+ "count": "Número de posiciones esperado (confírmelo en extraETF)",
+ "age": "Antigüedad máxima del archivo (días)",
+ "overlap": "Seleccione fuentes sin solapamientos. La vista de extraETF puede incluir cuentas conectadas aquí.",
+ "import": "Importar archivo",
+ "importing": "Importando…",
+ "success": "Importado. Añada esta exportación desde las fuentes disponibles arriba, guarde y actualice.",
+ "source": "Archivo importado",
+ "mtime": "Archivo modificado: {{time}}",
+ "expires": "Caduca: {{time}}",
+ "tooLarge": "El límite de importación es de 4 MiB."
+ },
+ "rebalance": {
+ "title": "Propuesta de asignación",
+ "hint": "Introduzca porcentajes objetivo que sumen 100%. Los cambios son importes para revisar; no se calculan órdenes, cantidades, impuestos ni comisiones.",
+ "target": "Objetivo de {{id}} (%)",
+ "generate": "Calcular propuesta",
+ "current": "Valor actual",
+ "targetValue": "Valor objetivo",
+ "change": "Cambio de valor"
}
},
"analysis": {
diff --git a/frontend/src/i18n/locales/fa.json b/frontend/src/i18n/locales/fa.json
index 99aab62f1..67ba04a16 100644
--- a/frontend/src/i18n/locales/fa.json
+++ b/frontend/src/i18n/locales/fa.json
@@ -2134,7 +2134,7 @@
"badge": "محلی فقط‌خواندنی · چندحسابی",
"title": "پورتفولیو",
"subtitle": "یک ارزش‌گذاری بر اساس اتصالات فقط‌خواندنی فعال. حسابی که خوانده نشود به‌صورت خطا گزارش و از جمع‌ها کنار گذاشته می‌شود.",
- "fxFresh": "USD/CNY {{rate}} · نرخ زنده",
+ "fxFresh": "USD/CNY {{rate}} · نرخ مرجع",
"fxCached": "USD/CNY {{rate}} · نرخ ذخیره‌شده",
"manageAccounts": "مدیریت حساب‌ها",
"exportCsv": "خروجی CSV",
@@ -2299,6 +2299,30 @@
"accountDeactivated": " · غیرفعال‌شده",
"accountSave": "استفاده از این حساب",
"accountSaved": "حساب ذخیره شد."
+ },
+ "imports": {
+ "title": "وارد کردن extraETF Investments",
+ "hint": "فقط دارایی‌های صادرشده، بدون وجه نقد یا قیمت زنده. زمان تغییر فایل زمان مشاهده قیمت نیست؛ محل معامله ISINها مشخص نشده است.",
+ "file": "فایل CSV از Investments",
+ "count": "تعداد مورد انتظار دارایی‌ها (در extraETF تأیید کنید)",
+ "age": "بیشینه عمر فایل (روز)",
+ "overlap": "منابع بدون همپوشانی انتخاب کنید. نمای extraETF ممکن است حساب‌های متصل دیگر را نیز شامل شود.",
+ "import": "وارد کردن فایل",
+ "importing": "در حال وارد کردن…",
+ "success": "وارد شد. این فایل را از منابع موجود بالا اضافه کنید، سپس ذخیره و تازه‌سازی کنید.",
+ "source": "وارد کردن فایل",
+ "mtime": "زمان تغییر فایل: {{time}}",
+ "expires": "انقضا: {{time}}",
+ "tooLarge": "سقف اندازه فایل 4 MiB است."
+ },
+ "rebalance": {
+ "title": "پیشنهاد تخصیص",
+ "hint": "درصدهای هدف را با جمع 100% وارد کنید. تغییرات فقط مبالغ پیشنهادی برای بررسی‌اند؛ سفارش، تعداد، مالیات یا کارمزد محاسبه نمی‌شود.",
+ "target": "هدف {{id}} (%)",
+ "generate": "محاسبه پیشنهاد",
+ "current": "ارزش فعلی",
+ "targetValue": "ارزش هدف",
+ "change": "تغییر ارزش"
}
},
"analysis": {
diff --git a/frontend/src/i18n/locales/id.json b/frontend/src/i18n/locales/id.json
index a8d434e20..04567d333 100644
--- a/frontend/src/i18n/locales/id.json
+++ b/frontend/src/i18n/locales/id.json
@@ -2134,7 +2134,7 @@
"badge": "Read-only lokal · Multi-akun",
"title": "Portofolio",
"subtitle": "Satu valuasi untuk semua koneksi read-only yang aktif. Akun yang tidak dapat dibaca akan dilaporkan sebagai error dan tidak disertakan dalam total.",
- "fxFresh": "USD/CNY {{rate}} · kurs live",
+ "fxFresh": "USD/CNY {{rate}} · kurs referensi",
"fxCached": "USD/CNY {{rate}} · kurs cache",
"manageAccounts": "Kelola akun",
"exportCsv": "Ekspor CSV",
@@ -2299,6 +2299,30 @@
"accountDeactivated": " · dinonaktifkan",
"accountSave": "Gunakan akun ini",
"accountSaved": "Akun tersimpan."
+ },
+ "imports": {
+ "title": "Impor extraETF Investments",
+ "hint": "Hanya kepemilikan, tanpa kas atau harga langsung. Waktu perubahan berkas bukan waktu pengamatan harga; tempat perdagangan ISIN belum teridentifikasi.",
+ "file": "CSV Investments",
+ "count": "Jumlah kepemilikan yang diharapkan (konfirmasi di extraETF)",
+ "age": "Usia maksimum berkas (hari)",
+ "overlap": "Pilih sumber yang tidak tumpang tindih. Tampilan extraETF mungkin sudah mencakup akun lain yang terhubung di sini.",
+ "import": "Impor berkas",
+ "importing": "Mengimpor…",
+ "success": "Berhasil diimpor. Tambahkan ekspor ini dari sumber yang tersedia di atas, lalu simpan dan segarkan.",
+ "source": "Impor berkas",
+ "mtime": "Berkas diubah: {{time}}",
+ "expires": "Berlaku hingga: {{time}}",
+ "tooLarge": "Batas impor adalah 4 MiB."
+ },
+ "rebalance": {
+ "title": "Usulan alokasi",
+ "hint": "Masukkan persentase target dengan total 100%. Perubahan hanya berupa nilai untuk ditinjau; order, jumlah unit, pajak, atau biaya tidak dihitung.",
+ "target": "Target {{id}} (%)",
+ "generate": "Hitung usulan",
+ "current": "Nilai saat ini",
+ "targetValue": "Nilai target",
+ "change": "Perubahan nilai"
}
},
"analysis": {
diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.json
index e1a560bc6..44064a773 100644
--- a/frontend/src/i18n/locales/ja.json
+++ b/frontend/src/i18n/locales/ja.json
@@ -2134,7 +2134,7 @@
"badge": "ローカル読み取り専用 · 複数口座",
"title": "ポートフォリオ",
"subtitle": "有効な読み取り専用接続をまとめて 1 つの評価にします。読み取れなかった口座はエラーとして表示され、合計には含まれません。",
- "fxFresh": "USD/CNY {{rate}} · 最新レート",
+ "fxFresh": "USD/CNY {{rate}} · 参考為替レート",
"fxCached": "USD/CNY {{rate}} · キャッシュされたレート",
"manageAccounts": "口座を管理",
"exportCsv": "CSV を書き出す",
@@ -2299,6 +2299,30 @@
"accountDeactivated": "・無効化済み",
"accountSave": "この口座を使う",
"accountSaved": "口座を保存しました。"
+ },
+ "imports": {
+ "title": "extraETF Investments をインポート",
+ "hint": "現金やリアルタイム価格を含まない保有明細です。ファイル更新時刻は価格の観測時刻ではなく、ISIN の取引市場も未解決です。",
+ "file": "Investments CSV",
+ "count": "保有行数(extraETF で確認)",
+ "age": "ファイルの最大経過日数",
+ "overlap": "重複しないソースを選択してください。extraETF に、ここで接続済みの口座が含まれる場合があります。",
+ "import": "ファイルをインポート",
+ "importing": "インポート中…",
+ "success": "インポートしました。上の利用可能なソースから追加し、保存して更新してください。",
+ "source": "ファイルインポート",
+ "mtime": "ファイル更新日時:{{time}}",
+ "expires": "有効期限:{{time}}",
+ "tooLarge": "インポートの上限は 4 MiB です。"
+ },
+ "rebalance": {
+ "title": "配分変更案",
+ "hint": "合計 100% の目標比率を入力してください。変更額は確認用です。注文、数量、税金、手数料は計算しません。",
+ "target": "{{id}} の目標(%)",
+ "generate": "変更案を計算",
+ "current": "現在の評価額",
+ "targetValue": "目標額",
+ "change": "変更額"
}
},
"analysis": {
diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.json
index 46b584631..399acac15 100644
--- a/frontend/src/i18n/locales/ko.json
+++ b/frontend/src/i18n/locales/ko.json
@@ -2134,7 +2134,7 @@
"badge": "로컬 읽기 전용 · 다중 계좌",
"title": "포트폴리오",
"subtitle": "활성화된 읽기 전용 연결을 하나의 평가로 합칩니다. 읽지 못한 계좌는 오류로 표시되며 합계에서 제외됩니다.",
- "fxFresh": "USD/CNY {{rate}} · 실시간 환율",
+ "fxFresh": "USD/CNY {{rate}} · 참고 환율",
"fxCached": "USD/CNY {{rate}} · 캐시된 환율",
"manageAccounts": "계좌 관리",
"exportCsv": "CSV 내보내기",
@@ -2299,6 +2299,30 @@
"accountDeactivated": " · 비활성화됨",
"accountSave": "이 계좌 사용",
"accountSaved": "계좌를 저장했습니다."
+ },
+ "imports": {
+ "title": "extraETF Investments 가져오기",
+ "hint": "현금이나 실시간 가격이 없는 보유 내역입니다. 파일 수정 시간은 가격 관측 시간이 아니며, ISIN의 거래 시장은 확인되지 않았습니다.",
+ "file": "Investments CSV",
+ "count": "예상 보유 행 수 (extraETF에서 확인)",
+ "age": "허용할 파일의 최대 경과 일수",
+ "overlap": "서로 겹치지 않는 소스를 선택하세요. extraETF에 여기서 연결한 다른 계좌가 이미 포함되어 있을 수 있습니다.",
+ "import": "파일 가져오기",
+ "importing": "가져오는 중…",
+ "success": "가져왔습니다. 위의 사용 가능한 소스에서 추가한 뒤 저장하고 새로고침하세요.",
+ "source": "파일 가져오기",
+ "mtime": "파일 수정: {{time}}",
+ "expires": "만료: {{time}}",
+ "tooLarge": "가져오기 제한은 4 MiB입니다."
+ },
+ "rebalance": {
+ "title": "배분 조정 제안",
+ "hint": "합계가 100%인 목표 비중을 입력하세요. 변경 금액은 검토용이며 주문, 수량, 세금 또는 수수료를 계산하지 않습니다.",
+ "target": "{{id}} 목표 (%)",
+ "generate": "제안 계산",
+ "current": "현재 금액",
+ "targetValue": "목표 금액",
+ "change": "변경 금액"
}
},
"analysis": {
diff --git a/frontend/src/i18n/locales/pt-BR.json b/frontend/src/i18n/locales/pt-BR.json
index b84670511..36f537926 100644
--- a/frontend/src/i18n/locales/pt-BR.json
+++ b/frontend/src/i18n/locales/pt-BR.json
@@ -2134,7 +2134,7 @@
"badge": "Somente leitura local · Várias contas",
"title": "Portfólio",
"subtitle": "Uma avaliação nas conexões somente leitura habilitadas. Uma conta que não pode ser lida é relatada como um erro e deixada de fora dos totais.",
- "fxFresh": "USD/CNY {{rate}} · taxa ao vivo",
+ "fxFresh": "USD/CNY {{rate}} · taxa de referência",
"fxCached": "USD/CNY {{rate}} · taxa em cache",
"manageAccounts": "Gerenciar contas",
"exportCsv": "Exportar CSV",
@@ -2299,6 +2299,30 @@
"accountDeactivated": " · desativada",
"accountSave": "Usar esta conta",
"accountSaved": "Conta salva."
+ },
+ "imports": {
+ "title": "Importar extraETF Investments",
+ "hint": "Apenas posições, sem caixa ou preços em tempo real. A data do arquivo não é a data de observação do preço; os ISINs não têm mercado de negociação definido.",
+ "file": "CSV de Investments",
+ "count": "Número esperado de posições (confirme no extraETF)",
+ "age": "Idade máxima do arquivo (dias)",
+ "overlap": "Selecione fontes sem sobreposição. A visão do extraETF pode incluir contas já conectadas aqui.",
+ "import": "Importar arquivo",
+ "importing": "Importando…",
+ "success": "Importado. Adicione esta exportação pelas fontes disponíveis acima, salve e atualize.",
+ "source": "Importação de arquivo",
+ "mtime": "Arquivo modificado: {{time}}",
+ "expires": "Validade: {{time}}",
+ "tooLarge": "O limite de importação é de 4 MiB."
+ },
+ "rebalance": {
+ "title": "Proposta de alocação",
+ "hint": "Informe percentuais-alvo que somem 100%. As alterações são valores para revisão; não são calculadas ordens, quantidades, impostos ou taxas.",
+ "target": "Meta de {{id}} (%)",
+ "generate": "Calcular proposta",
+ "current": "Valor atual",
+ "targetValue": "Valor-alvo",
+ "change": "Alteração de valor"
}
},
"analysis": {
diff --git a/frontend/src/i18n/locales/tr.json b/frontend/src/i18n/locales/tr.json
index f47d594cd..797c6796f 100644
--- a/frontend/src/i18n/locales/tr.json
+++ b/frontend/src/i18n/locales/tr.json
@@ -2100,7 +2100,7 @@
"badge": "Local read-only · Multi-account",
"title": "Portföy",
"subtitle": "One valuation across the enabled read-only connections. An account that cannot be read is reported as an error and left out of the totals.",
- "fxFresh": "USD/CNY {{rate}} · live rate",
+ "fxFresh": "USD/CNY {{rate}} · referans kuru",
"fxCached": "USD/CNY {{rate}} · cached rate",
"manageAccounts": "Manage accounts",
"exportCsv": "Export CSV",
@@ -2265,6 +2265,30 @@
"accountDeactivated": " · deactivated",
"accountSave": "Use this account",
"accountSaved": "Account saved."
+ },
+ "imports": {
+ "title": "extraETF Investments içe aktar",
+ "hint": "Yalnızca varlıklar; nakit veya canlı fiyat içermez. Dosya değişiklik zamanı fiyat gözlem zamanı değildir; ISIN’lerin işlem yeri belirlenmemiştir.",
+ "file": "Investments CSV",
+ "count": "Beklenen varlık satırı sayısı (extraETF’te doğrulayın)",
+ "age": "Dosyanın azami yaşı (gün)",
+ "overlap": "Örtüşmeyen kaynaklar seçin. extraETF görünümü burada bağlı başka hesapları zaten içerebilir.",
+ "import": "Dosyayı içe aktar",
+ "importing": "İçe aktarılıyor…",
+ "success": "İçe aktarıldı. Bu dışa aktarımı yukarıdaki kullanılabilir kaynaklardan ekleyin, kaydedin ve yenileyin.",
+ "source": "Dosya içe aktarımı",
+ "mtime": "Dosya değişikliği: {{time}}",
+ "expires": "Geçerlilik sonu: {{time}}",
+ "tooLarge": "İçe aktarma sınırı 4 MiB’dir."
+ },
+ "rebalance": {
+ "title": "Dağılım önerisi",
+ "hint": "Toplamı %100 olan hedef yüzdeleri girin. Değişiklikler yalnızca incelenecek tutarlardır; emir, miktar, vergi veya ücret hesaplanmaz.",
+ "target": "{{id}} hedefi (%)",
+ "generate": "Öneriyi hesapla",
+ "current": "Mevcut değer",
+ "targetValue": "Hedef değer",
+ "change": "Değer değişimi"
}
},
"navigation": {
diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.json
index a6ca4cb4c..2c7d4f03a 100644
--- a/frontend/src/i18n/locales/zh-CN.json
+++ b/frontend/src/i18n/locales/zh-CN.json
@@ -2134,7 +2134,7 @@
"badge": "本机只读 · 多账户",
"title": "持仓总览",
"subtitle": "把已启用的只读连接汇总成一份估值。读取失败的账户会标记为错误,并且不计入合计。",
- "fxFresh": "USD/CNY {{rate}} · 实时汇率",
+ "fxFresh": "USD/CNY {{rate}} · 参考汇率",
"fxCached": "USD/CNY {{rate}} · 缓存汇率",
"manageAccounts": "管理账户",
"exportCsv": "导出 CSV",
@@ -2299,6 +2299,30 @@
"accountDeactivated": " · 已停用",
"accountSave": "使用这个账户",
"accountSaved": "账户已保存。"
+ },
+ "imports": {
+ "title": "导入 extraETF Investments",
+ "hint": "仅包含导出的持仓,不含现金或实时价格。文件修改时间不是行情观测时间;ISIN 尚未匹配交易场所。",
+ "file": "Investments CSV 文件",
+ "count": "预期持仓行数(请在 extraETF 中核对)",
+ "age": "文件最长有效期(天)",
+ "overlap": "请选择互不重叠的数据源。extraETF 视图可能已包含此处连接的其他账户。",
+ "import": "导入文件",
+ "importing": "正在导入…",
+ "success": "导入成功。请从上方可用来源中添加该导出,保存后刷新。",
+ "source": "文件导入",
+ "mtime": "文件修改时间:{{time}}",
+ "expires": "有效期至:{{time}}",
+ "tooLarge": "导入文件不能超过 4 MiB。"
+ },
+ "rebalance": {
+ "title": "目标配置建议",
+ "hint": "输入合计 100% 的目标比例。差额仅为供审阅的金额建议,不生成订单,也不计算数量、税费。",
+ "target": "{{id}} 目标比例(%)",
+ "generate": "计算建议",
+ "current": "当前金额",
+ "targetValue": "目标金额",
+ "change": "调整金额"
}
},
"analysis": {
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index ad74c6dc8..a2322290a 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -123,6 +123,10 @@ export interface CorrelationRegimeResponse {
}
export interface PortfolioPosition {
+ portfolio_id?: string;
+ portfolio_name?: string;
+ source_mtime?: string;
+ instrument_id_kind?: string;
source_id?: string;
profile_id?: string;
source_label?: string;
@@ -160,6 +164,8 @@ export interface PortfolioConnectorCompatibility {
* as history — never as a current valuation.
*/
export interface PortfolioAccount {
+ source_kind?: "connection" | "extraetf";
+ import_metadata?: { source_mtime: string; expires_at: string; as_of_source: string } | null;
source_id?: string;
profile_id?: string;
label?: string;
@@ -201,10 +207,11 @@ export interface PortfolioSnapshot {
unpriced_or_other_usd: number;
identified_coverage: number;
};
- fx: { usd_cny: number; usd_hkd: number; rates?: Record<string, number>; fetched_at: string; stale: boolean };
+ fx: { as_of?: string | null; source?: string; usd_cny: number; usd_hkd: number; rates?: Record<string, number>; fetched_at: string; stale: boolean };
accounts: PortfolioAccount[];
positions: PortfolioPosition[];
combined_holdings?: Array<{
+ canonical_id?: string;
symbol: string;
market_value_usd: number;
asset_type?: string;
@@ -216,6 +223,7 @@ export interface PortfolioSnapshot {
}
export interface PortfolioHistoryPoint {
+ total_eur?: string | null;
id: string;
created_at: string;
complete: number;
@@ -225,6 +233,13 @@ export interface PortfolioHistoryPoint {
total_hkd?: string | null;
}
+export interface RebalanceProposal {
+ mode: "proposal_only";
+ snapshot_id: string;
+ currency: string;
+ rows: Array<{ canonical_id: string; current_value: number; target_value: number; change_value: number }>;
+}
+
export interface PortfolioRefreshState {
running: boolean;
current: string | null;
@@ -242,6 +257,7 @@ export interface PortfolioReconnectState {
}
export interface PortfolioSourceSettings {
+ source_kind?: "connection" | "extraetf";
connection_id: string;
label: string;
enabled: boolean;
@@ -255,13 +271,14 @@ export interface PortfolioSettings {
}
export interface PortfolioSourceCatalogItem {
+ source_kind?: "connection" | "extraetf";
id: string;
connection_id: string;
profile_id: string;
connector: string;
label: string;
- environment: "paper" | "live";
- transport: "local_tws" | "remote_mcp" | "broker_sdk" | "local_plugin";
+ environment: "paper" | "live" | "import";
+ transport: "local_tws" | "remote_mcp" | "broker_sdk" | "local_plugin" | "file_import";
capabilities: string[];
readonly: boolean;
notes: string;
@@ -271,7 +288,7 @@ export interface PortfolioSourceCatalogItem {
credential_fields: CredentialField[];
credential_status: Record<string, boolean>;
credentials_configured: boolean;
- portfolio_compatibility: PortfolioConnectorCompatibility;
+ portfolio_compatibility: PortfolioConnectorCompatibility | null;
}
export interface CredentialField {
@@ -490,6 +507,10 @@ export const api = {
`/api/connections/${encodeURIComponent(connectionId)}`,
{ method: "DELETE" },
),
+ importExtraEtf: (payload: { csv_text: string; label: string; source_mtime: string; expected_positions: number; max_age_days: number }) =>
+ request<{ status: string; import: { id: string } }>("/api/portfolio/imports/extraetf", { method: "POST", body: JSON.stringify(payload) }),
+ proposePortfolioRebalance: (snapshotId: string, targetWeights: Record<string, number>) =>
+ request<{ status: string; proposal: RebalanceProposal }>("/api/portfolio/rebalance", { method: "POST", body: JSON.stringify({ snapshot_id: snapshotId, target_weights: targetWeights }) }),
getPortfolioHistory: (limit = 180) =>
request<{ status: string; history: PortfolioHistoryPoint[] }>(`/api/portfolio/history?limit=${encodeURIComponent(String(limit))}`),
downloadPortfolioCsv: async () => {
diff --git a/frontend/src/pages/Portfolio.tsx b/frontend/src/pages/Portfolio.tsx
index d34a0eea8..0c4b4254d 100644
--- a/frontend/src/pages/Portfolio.tsx
+++ b/frontend/src/pages/Portfolio.tsx
@@ -1,4 +1,5 @@
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import { RebalanceProposal } from "@/components/portfolio/RebalanceProposal";
import { useTranslation } from "react-i18next";
import {
AlertTriangle,
@@ -355,7 +356,7 @@ export function Portfolio() {
<p className="mt-2 text-sm text-muted-foreground">{t("portfolio.page.subtitle")}</p>
{snapshot?.fx && Number.isFinite(snapshot.fx.usd_cny) ? (
<p className="mt-2 text-xs text-muted-foreground">
- {t(snapshot.fx.stale ? "portfolio.page.fxCached" : "portfolio.page.fxFresh", { rate: snapshot.fx.usd_cny.toFixed(4) })}
+ {t(snapshot.fx.stale ? "portfolio.page.fxCached" : "portfolio.page.fxFresh", { rate: snapshot.fx.usd_cny.toFixed(4) })}{snapshot.fx.as_of ? ` · ${snapshot.fx.as_of}` : ""}
</p>
) : null}
</div>
@@ -459,13 +460,14 @@ export function Portfolio() {
const valueMain = row.priced ? money(displayValue(row.market_value_usd, row.market_value_cny, displayCurrency, snapshot.fx), displayCurrency) : "—";
const valueAlt = row.priced ? (displayCurrency === "USD" ? money(row.market_value_cny, "CNY") : money(row.market_value_usd)) : t("portfolio.holdings.unpriced");
const pnlDisplay = displayValue(row.unrealized_pnl_usd, undefined, displayCurrency, snapshot.fx);
- return <tr key={`${row.source_id ?? row.broker}-${row.symbol}`} className="hover:bg-muted/20"><Td><div className="font-medium">{row.source_label ?? row.broker.toUpperCase()}</div><div className="mt-1 text-xs"><BrokerBadge broker={row.broker} /></div></Td><Td><div className="font-medium">{row.symbol}</div><div className="max-w-52 truncate text-xs text-muted-foreground">{row.name}</div></Td><Td><span className="capitalize text-muted-foreground">{row.asset_type}</span></Td><Td>{quantity(row.quantity)}</Td><Td><div>{price(row.cost_price)}</div><div className="text-xs text-muted-foreground">{price(row.market_price)}</div></Td><Td><div className="font-medium">{valueMain}</div><div className="text-xs text-muted-foreground">{valueAlt}</div></Td><Td>{row.priced ? percentage(weight) : "—"}</Td><Td><span className={pnlDisplay == null ? "text-muted-foreground" : pnlDisplay >= 0 ? "text-positive" : "text-danger"}>{pnlDisplay == null ? "—" : money(pnlDisplay, displayCurrency)}</span></Td><Td><DataBadge priced={row.priced} /></Td></tr>;
+ return <tr key={`${row.source_id ?? row.broker}-${row.portfolio_id ?? ""}-${row.symbol}`} className="hover:bg-muted/20"><Td><div className="font-medium">{row.source_label ?? row.broker.toUpperCase()}</div><div className="mt-1 text-xs"><BrokerBadge broker={row.broker} /></div></Td><Td><div className="font-medium">{row.symbol}</div><div className="max-w-52 truncate text-xs text-muted-foreground">{row.name}</div>{row.portfolio_id && <div className="text-xs text-muted-foreground">{row.portfolio_name} · {row.portfolio_id}</div>}{row.source_mtime && <div className="text-xs text-muted-foreground">{t("portfolio.imports.mtime", { time: dateTime(row.source_mtime) })}</div>}</Td><Td><span className="capitalize text-muted-foreground">{row.asset_type}</span></Td><Td>{quantity(row.quantity)}</Td><Td><div>{price(row.cost_price)}</div><div className="text-xs text-muted-foreground">{price(row.market_price)}</div></Td><Td><div className="font-medium">{valueMain}</div><div className="text-xs text-muted-foreground">{valueAlt}</div></Td><Td>{row.priced ? percentage(weight) : "—"}</Td><Td><span className={pnlDisplay == null ? "text-muted-foreground" : pnlDisplay >= 0 ? "text-positive" : "text-danger"}>{pnlDisplay == null ? "—" : money(pnlDisplay, displayCurrency)}</span></Td><Td><DataBadge priced={row.priced} /></Td></tr>;
})}
</tbody>
</table>
</div>
</section>
+ <RebalanceProposal key={snapshot.snapshot_id} snapshot={snapshot} />
<HistoryChart history={history} currency={displayCurrency} />
<section className="rounded-xl border bg-card p-5">
@@ -560,7 +562,7 @@ function AccountCard({ account, active, displayCurrency, fx, onClick, onReconnec
<>
<div className="mt-4 text-2xl font-semibold">{money(accountDisplay, displayCurrency)}</div>
<div className="mt-1 text-xs text-muted-foreground">{displayCurrency === "USD" ? money(account.total_cny, "CNY") : money(account.total_usd)} · {t("portfolio.accounts.positions", { count: account.position_count ?? 0 })}</div>
- <div className="mt-4 flex items-center justify-between border-t pt-3 text-xs"><span className="text-positive">{t("portfolio.accounts.fresh")}</span><span className="text-muted-foreground">{dateTime(account.last_success_at)}</span></div>
+ <div className="mt-4 flex items-center justify-between border-t pt-3 text-xs"><span className="text-positive">{account.source_kind === "extraetf" ? t("portfolio.imports.source") : t("portfolio.accounts.fresh")}</span><span className="text-muted-foreground">{dateTime(account.import_metadata?.source_mtime ?? account.last_success_at)}</span></div>
</>
)}
{failed && account.error ? <p className="mt-3 line-clamp-2 text-xs text-muted-foreground" title={account.error}>{account.error}</p> : null}
@@ -583,6 +585,7 @@ function DataBadge({ priced }: { priced: boolean }) {
function CredentialCard({ account }: { account: PortfolioAccount }) {
const { t } = useTranslation();
const auth = account.auth;
+ if (account.source_kind === "extraetf") return <div className="rounded-lg border p-4"><div className="font-medium">{account.label}</div><p className="mt-2 text-sm">{t("portfolio.imports.hint")}</p>{account.import_metadata && <><p className="mt-2 text-xs">{t("portfolio.imports.mtime", { time: dateTime(account.import_metadata.source_mtime) })}</p><p className="text-xs">{t("portfolio.imports.expires", { time: dateTime(account.import_metadata.expires_at) })}</p></>}</div>;
const renewal = auth?.renewal === "automatic"
? t("portfolio.credentials.renewalAutomatic")
: auth?.renewal === "session"
@@ -654,7 +657,7 @@ function HistoryChart({ history, currency = "USD" }: { history: PortfolioHistory
},
xAxis: { type: "category", boundaryGap: false, data: rows.map((row) => new Date(row.created_at).toLocaleString(uiLocale(), { month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit" })), axisLabel: { color: theme.textColor, hideOverlap: true }, axisLine: { lineStyle: { color: theme.gridColor } } },
yAxis: { type: "value", scale: true, axisLabel: { color: theme.textColor, formatter: (v: number) => compactMoney(v, currency) }, splitLine: { lineStyle: { color: theme.gridColor, opacity: 0.45 } } },
- series: [{ type: "line", data: rows.map((row) => { const value = currency === "USD" ? row.total_usd : currency === "CNY" ? row.total_cny : currency === "HKD" ? row.total_hkd : null; return value == null ? null : Number(value); }), smooth: true, symbol: rows.length < 30 ? "circle" : "none", lineStyle: { width: 2, color: "#4f6edb" }, itemStyle: { color: "#4f6edb" }, areaStyle: { color: "rgba(79,110,219,0.10)" } }],
+ series: [{ type: "line", data: rows.map((row) => { const value = currency === "USD" ? row.total_usd : currency === "CNY" ? row.total_cny : currency === "HKD" ? row.total_hkd : currency === "EUR" ? row.total_eur : null; return value == null ? null : Number(value); }), smooth: true, symbol: rows.length < 30 ? "circle" : "none", lineStyle: { width: 2, color: "#4f6edb" }, itemStyle: { color: "#4f6edb" }, areaStyle: { color: "rgba(79,110,219,0.10)" } }],
});
const resize = () => chart.resize();
window.addEventListener("resize", resize);