Open-source personal finance manager. Self-hosted, privacy-first.
feat/add stocks and crypto assets (#115)
Tássio Noronhac867aa75637a
diff --git a/backend/alembic/versions/037_assets_market_price.py b/backend/alembic/versions/037_assets_market_price.pynew file mode 100644index 00000000..141fe49d--- /dev/null+++ b/backend/alembic/versions/037_assets_market_price.py@@ -0,0 +1,51 @@+"""add market price fields to assets (ticker-based valuation via yfinance)++Revision ID: 037+Revises: 036+Create Date: 2026-04-21++Adds ticker + cached-quote columns so an asset can be valued from a live+market price instead of manual entry or a growth rule. Used by the new+``market_price`` valuation method: the user picks a ticker (AAPL, BTC-USD,+PETR4.SA...), enters quantity, and a scheduled task keeps the price fresh.++Nothing is backfilled — existing assets stay on their current method.+"""+from typing import Sequence, Union++import sqlalchemy as sa+from alembic import op++revision: str = "037"+down_revision: Union[str, None] = "036"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ op.add_column("assets", sa.Column("ticker", sa.String(32), nullable=True))+ op.add_column("assets", sa.Column("ticker_exchange", sa.String(32), nullable=True))+ op.add_column(+ "assets",+ sa.Column("last_price", sa.Numeric(precision=18, scale=6), nullable=True),+ )+ op.add_column(+ "assets",+ sa.Column("last_price_at", sa.DateTime(timezone=True), nullable=True),+ )++ # Find all market-priced assets efficiently during the refresh task.+ op.create_index(+ "ix_assets_market_price",+ "assets",+ ["valuation_method"],+ postgresql_where=sa.text("valuation_method = 'market_price'"),+ )+++def downgrade() -> None:+ op.drop_index("ix_assets_market_price", "assets")+ op.drop_column("assets", "last_price_at")+ op.drop_column("assets", "last_price")+ op.drop_column("assets", "ticker_exchange")+ op.drop_column("assets", "ticker")diff --git a/backend/alembic/versions/038_assets_logo_url.py b/backend/alembic/versions/038_assets_logo_url.pynew file mode 100644index 00000000..0d25dfc6--- /dev/null+++ b/backend/alembic/versions/038_assets_logo_url.py@@ -0,0 +1,28 @@+"""add logo_url to assets (cached favicon URL for market-priced assets)++Revision ID: 038+Revises: 037+Create Date: 2026-04-21++Stores a fully-formed logo URL so the frontend can render an <img> without+knowing about the upstream service. Populated at creation time for+market-priced assets when the quote provider returns a company website;+left null for manual assets and tickers without a website (most crypto).+"""+from typing import Sequence, Union++import sqlalchemy as sa+from alembic import op++revision: str = "038"+down_revision: Union[str, None] = "037"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ op.add_column("assets", sa.Column("logo_url", sa.String(500), nullable=True))+++def downgrade() -> None:+ op.drop_column("assets", "logo_url")diff --git a/backend/app/api/assets.py b/backend/app/api/assets.pyindex f8e28b91..1361e5a5 100644--- a/backend/app/api/assets.py+++ b/backend/app/api/assets.py@@ -1,3 +1,4 @@+import loggingimport uuidfrom decimal import Decimal@@ -7,13 +8,149 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.core.auth import current_active_userfrom app.core.database import get_async_sessionfrom app.models.user import User-from app.schemas.asset import AssetCreate, AssetRead, AssetUpdate, AssetValueCreate, AssetValueRead+from app.providers.market_price import (+ MarketPriceRateLimitedError,+ get_market_price_provider,+)+from app.schemas.asset import (+ AssetCreate,+ AssetRead,+ AssetUpdate,+ AssetValueCreate,+ AssetValueRead,+ MarketSymbolMatch,+ MarketSymbolQuote,+)from app.services import asset_servicefrom app.services.fx_rate_service import convert+logger = logging.getLogger(__name__)+router = APIRouter(prefix="/api/assets", tags=["assets"])+# ----------------------------------------------------------------------------+# Market price lookup (Yahoo Finance via yfinance)+# ----------------------------------------------------------------------------+#+# Lives under /api/assets/market/... rather than a top-level /market so the+# RBAC and auth middleware inherited by this router applies automatically —+# ticker lookups are gated behind an authenticated session just like other+# asset endpoints.++[email protected]("/market/search", response_model=list[MarketSymbolMatch])+async def market_search(+ q: str = Query(..., min_length=1, max_length=64, description="Ticker or company name"),+ limit: int = Query(15, ge=1, le=30),+ _: User = Depends(current_active_user),+) -> list[MarketSymbolMatch]:+ """Autocomplete ticker symbols for the Add-Asset form.++ Intentionally thin — just proxies to the configured market-price+ provider. Upstream errors turn into an empty list so the UI degrades+ gracefully (a user typing a query shouldn't ever see a 500).+ """+ provider = get_market_price_provider()+ try:+ return await provider.search(q, limit=limit)+ except MarketPriceRateLimitedError:+ raise HTTPException(+ status_code=status.HTTP_429_TOO_MANY_REQUESTS,+ detail="Market data provider is currently rate-limiting. Try again in a minute.",+ )+ except Exception:+ logger.exception("Market search failed for %r", q)+ return []++[email protected]("/market/quote", response_model=MarketSymbolQuote)+async def market_quote(+ symbol: str = Query(..., min_length=1, max_length=32),+ _: User = Depends(current_active_user),+) -> MarketSymbolQuote:+ """Fetch a single live quote — used to preview value before saving an asset."""+ provider = get_market_price_provider()+ try:+ quote = await provider.get_quote(symbol)+ except MarketPriceRateLimitedError:+ raise HTTPException(+ status_code=status.HTTP_429_TOO_MANY_REQUESTS,+ detail="Market data provider is currently rate-limiting. Try again in a minute.",+ )+ if quote is None:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail=f"No quote found for {symbol}",+ )+ return quote++[email protected]("/{asset_id}/refresh-price", response_model=AssetRead)+async def refresh_asset_price(+ asset_id: uuid.UUID,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+) -> AssetRead:+ """Trigger an immediate price refresh for a single market-priced asset.++ Mirrors what the scheduled daily task does for one asset — re-quotes+ the ticker, updates ``last_price`` + ``last_price_at``, and upserts+ today's ``AssetValue``. Returns the refreshed asset with the same+ shape as the list endpoint (including ``current_value_primary``).+ """+ from app.models.asset import Asset as AssetModel+ from sqlalchemy import select as sa_select++ result = await session.execute(+ sa_select(AssetModel).where(+ AssetModel.id == asset_id, AssetModel.user_id == user.id+ )+ )+ asset = result.scalar_one_or_none()+ if asset is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found")+ if asset.valuation_method != "market_price":+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail="Only market-priced assets can be refreshed via this endpoint",+ )++ try:+ ok = await asset_service.refresh_market_price_asset(session, asset)+ except MarketPriceRateLimitedError:+ raise HTTPException(+ status_code=status.HTTP_429_TOO_MANY_REQUESTS,+ detail="Market data provider is currently rate-limiting. Try again in a minute.",+ )+ if not ok:+ raise HTTPException(+ status_code=status.HTTP_502_BAD_GATEWAY,+ detail=f"Could not refresh quote for {asset.ticker}",+ )+ await session.commit()++ refreshed = await asset_service.get_asset(session, asset_id, user.id)+ if refreshed is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found")++ # Stamp the primary-currency fields so the refresh response has the same+ # shape as the list endpoint — the React Query cache update needs them+ # to keep the row rendering consistent (BRL rollup, gain/loss).+ primary_currency = user.primary_currency+ if refreshed.currency != primary_currency and refreshed.current_value is not None:+ converted, _ = await convert(+ session, Decimal(str(refreshed.current_value)), refreshed.currency, primary_currency,+ )+ refreshed.current_value_primary = float(converted)+ if refreshed.gain_loss is not None:+ gl_converted, _ = await convert(+ session, Decimal(str(refreshed.gain_loss)), refreshed.currency, primary_currency,+ )+ refreshed.gain_loss_primary = float(gl_converted)+ return refreshed++@router.get("", response_model=list[AssetRead])async def list_assets(include_archived: bool = False,diff --git a/backend/app/core/config.py b/backend/app/core/config.pyindex 322e761f..27bf6fce 100644--- a/backend/app/core/config.py+++ b/backend/app/core/config.py@@ -51,6 +51,12 @@ class Settings(BaseSettings):# Celeryredis_url: str = "redis://localhost:6379/0"+ # Logo size for market-priced asset icons. The logo URL is built from+ # the company website we get from the market-price provider; no API+ # key or third-party account is required. Defaults to 128×128 which+ # is what Google's favicon service caps at before upscaling.+ logo_size: int = 128+model_config = SettingsConfigDict(env_file=".env")diff --git a/backend/app/models/asset.py b/backend/app/models/asset.pyindex cd7f2bc8..c5c6a790 100644--- a/backend/app/models/asset.py+++ b/backend/app/models/asset.py@@ -1,9 +1,9 @@import uuid-from datetime import date+from datetime import date, datetimefrom decimal import Decimalfrom typing import TYPE_CHECKING, Any, Optional-from sqlalchemy import JSON, Boolean, Date, ForeignKey, Integer, Numeric, String+from sqlalchemy import JSON, Boolean, Date, DateTime, ForeignKey, Integer, Numeric, Stringfrom sqlalchemy.dialects.postgresql import UUIDfrom sqlalchemy.orm import Mapped, mapped_column, relationship@@ -55,5 +55,19 @@ class Asset(Base):UUID(as_uuid=True), ForeignKey("asset_groups.id", ondelete="SET NULL"), nullable=True)+ # Market-priced assets (valuation_method="market_price"). `ticker` is the+ # Yahoo Finance symbol (AAPL, BTC-USD, PETR4.SA). `last_price` is the+ # most recent quote cached on the row so list views don't re-hit yfinance.+ ticker: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)+ ticker_exchange: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)+ last_price: Mapped[Optional[Decimal]] = mapped_column(+ Numeric(precision=18, scale=6), nullable=True+ )+ last_price_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)+ # Fully-formed logo URL — populated at create time for market-priced+ # assets when a logo provider is configured. Null means "no logo, use+ # the type icon". Frontend swaps to the type icon on <img> load error.+ logo_url: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)+values: Mapped[list["AssetValue"]] = relationship(back_populates="asset", cascade="all, delete-orphan")group: Mapped[Optional["AssetGroup"]] = relationship(back_populates="assets")diff --git a/backend/app/providers/market_price.py b/backend/app/providers/market_price.pynew file mode 100644index 00000000..75e80d05--- /dev/null+++ b/backend/app/providers/market_price.py@@ -0,0 +1,488 @@+"""Market-price data providers (stocks, ETFs, crypto, funds).++Asset valuation from a live public quote — the user enters a ticker and+quantity, the provider returns the price, and Securo tracks the value+over time. This is deliberately separate from `BankProvider`: there's no+per-user authentication and no accounts/transactions, just a symbol+lookup backed by a public data source (Yahoo Finance today).++Why a thin abstraction: swapping Yahoo out (for Stooq, Alpha Vantage,+CoinGecko, or a user-chosen source) is a realistic future, and keeping+the asset service off the concrete provider makes those swaps non-events.++yfinance usage notes (matches v1.3.x):+ * ``yfinance.Search(query, max_results=..., news_count=..., enable_fuzzy_query=...)``+ returns a ``.quotes`` list of dicts with keys like ``symbol``, ``shortname``,+ ``longname``, ``exchange``, ``exchDisp``, ``quoteType``.+ * ``yfinance.Ticker(symbol).fast_info`` exposes camelCase keys —+ ``lastPrice``, ``previousClose``, ``currency``, ``exchange``, ``quoteType``.+ snake_case keys are silently accepted too, but camelCase is the public API.+ * ``yf.config.network.retries`` enables transient-error retries (exponential+ backoff). Set once at module import so both Search and Ticker benefit.+ * ``YFRateLimitError`` is raised when Yahoo rate-limits us — we surface it+ so the caller can decide (UI toast vs. scheduled-task skip).+"""++from __future__ import annotations++import asyncio+import logging+from abc import ABC, abstractmethod+from decimal import Decimal+from typing import Optional+from urllib.parse import urlparse++from app.core.config import get_settings+from app.schemas.asset import MarketSymbolMatch, MarketSymbolQuote++logger = logging.getLogger(__name__)+++# Yahoo Finance occasionally reports prices in minor units (pence, cents).+# These are not valid ISO 4217 codes and, if kept raw, produce 100x-wrong+# valuations. Same table Sure uses (see app/models/provider/yahoo_finance.rb).+_MINOR_UNIT_CURRENCIES: dict[str, tuple[str, float]] = {+ "GBp": ("GBP", 0.01), # British pence → pounds (e.g. IITU.L)+ "ZAc": ("ZAR", 0.01), # South African cents → rand (e.g. JSE.JO)+}+++def _normalize_currency_and_price(currency: str, price: float) -> tuple[str, float]:+ conv = _MINOR_UNIT_CURRENCIES.get(currency)+ if conv is None:+ return currency, price+ code, multiplier = conv+ return code, price * multiplier+++class MarketPriceProviderError(Exception):+ """Provider-level failure — propagated so callers can return a useful error."""+++class MarketPriceRateLimitedError(MarketPriceProviderError):+ """Upstream (Yahoo) rate-limited us. Caller should back off, not crash."""+++class MarketPriceProvider(ABC):+ """Abstract interface for looking up tradable symbols and their prices."""++ name: str = "abstract"++ @abstractmethod+ async def search(self, query: str, limit: int = 20) -> list[MarketSymbolMatch]:+ """Return ticker suggestions matching the user's query."""++ @abstractmethod+ async def get_quote(self, symbol: str) -> Optional[MarketSymbolQuote]:+ """Return the latest price for a single symbol, or None if unknown."""++ async def get_quotes(self, symbols: list[str]) -> dict[str, Optional[MarketSymbolQuote]]:+ """Batch variant — default is a sequential get_quote loop.++ Subclasses may override with a true bulk endpoint. Stays sequential+ by default so we don't accidentally thunder-herd the upstream API.+ """+ out: dict[str, Optional[MarketSymbolQuote]] = {}+ for sym in symbols:+ out[sym] = await self.get_quote(sym)+ return out++ async def get_latest_prices(self, symbols: list[str]) -> dict[str, Optional[Decimal]]:+ """Batch-fetch only the latest price for each symbol.++ Lighter than `get_quotes`: scheduled refresh doesn't need name,+ exchange, or quote_type — just the number. Subclasses should+ implement this with a true bulk endpoint (one HTTP request)+ whenever possible; the default here is a safe sequential fallback+ so the interface stays compatible with simpler providers.+ """+ out: dict[str, Optional[Decimal]] = {}+ for sym in symbols:+ key = sym.strip().upper()+ if not key:+ continue+ quote = await self.get_quote(key)+ if quote is None or quote.price is None:+ out[key] = None+ else:+ out[key] = Decimal(str(quote.price))+ return out+++class YFinanceProvider(MarketPriceProvider):+ """Yahoo Finance provider backed by the ``yfinance`` Python library.++ ``yfinance`` is synchronous and hits Yahoo's HTTP endpoints internally,+ so every call is wrapped in ``asyncio.to_thread`` to keep the FastAPI+ event loop responsive.+ """++ name = "yfinance"++ # How many transient-network retries yfinance should perform internally.+ # yfinance uses exponential backoff (1s, 2s, 4s...) so 2 retries adds at+ # most ~3s to any call — cheap enough to keep defaults sane.+ _RETRIES = 2++ def __init__(self) -> None:+ # Imported lazily so a broken or missing yfinance install only hits+ # the market-price code paths — the rest of Securo keeps booting.+ import yfinance as yf++ # Global config singleton — the canonical knob in yfinance 1.x.+ # Wrap in try/except because older versions use a different shape.+ try:+ yf.config.network.retries = self._RETRIES+ except AttributeError:+ pass++ async def search(self, query: str, limit: int = 20) -> list[MarketSymbolMatch]:+ q = (query or "").strip()+ if not q:+ return []+ raw = await asyncio.to_thread(self._search_sync, q, limit)+ matches: list[MarketSymbolMatch] = []+ for quote in raw:+ symbol = quote.get("symbol")+ if not symbol:+ continue+ matches.append(+ MarketSymbolMatch(+ symbol=symbol,+ # Yahoo's search result uses lowercase `longname`/`shortname`+ # (not the camelCase the rest of yfinance uses).+ name=quote.get("longname") or quote.get("shortname"),+ exchange=quote.get("exchDisp") or quote.get("exchange"),+ quote_type=(quote.get("quoteType") or "").upper() or None,+ )+ )+ return matches++ # Practical cap per `yf.download` request. Yahoo accepts more but starts+ # silently dropping symbols beyond ~100 in community reports — we chunk+ # above this to keep the success rate high.+ _BATCH_CHUNK_SIZE = 100++ async def get_latest_prices(self, symbols: list[str]) -> dict[str, Optional[Decimal]]:+ """One HTTP request per ~100 tickers via ``yfinance.download``.++ Much cheaper than looping ``get_quote`` for a scheduled refresh — a+ portfolio of 50 market-priced assets goes from 50 calls to 1. The+ tradeoff: ``download`` returns prices only (no currency/name/etc.).+ That's fine here because ``Asset.currency`` is already cached from+ creation time; we just update the price and let ``current_value``+ recompute from ``units × last_price``.++ Note on minor-unit currencies (GBp, ZAc on LSE/JSE): those are+ normalized to GBP/ZAR ×0.01 at creation (via ``get_quote``), but+ on refresh we only get the raw trading-currency close. The batch+ preserves the same unit as the upstream quote, so internal+ consistency is maintained as long as the asset's stored currency+ matches the ticker's reporting unit. If Yahoo changes a listing's+ reporting unit mid-stream the price will appear off by 100× — rare+ enough to address reactively rather than pre-emptively.+ """+ if not symbols:+ return {}+ unique = list(dict.fromkeys(s.strip().upper() for s in symbols if s and s.strip()))+ if not unique:+ return {}++ out: dict[str, Optional[Decimal]] = {s: None for s in unique}+ for i in range(0, len(unique), self._BATCH_CHUNK_SIZE):+ chunk = unique[i : i + self._BATCH_CHUNK_SIZE]+ try:+ chunk_prices = await asyncio.to_thread(self._download_prices_sync, chunk)+ except _rate_limit_exception_types():+ raise MarketPriceRateLimitedError(+ "Yahoo Finance rate-limited the batch price download"+ )+ out.update(chunk_prices)+ return out++ async def get_quote(self, symbol: str) -> Optional[MarketSymbolQuote]:+ sym = (symbol or "").strip().upper()+ if not sym:+ return None+ raw = await asyncio.to_thread(self._quote_sync, sym)+ if raw is None:+ return None+ price = raw.get("price")+ currency = raw.get("currency")+ if price is None or not currency:+ return None+ normalized_currency, normalized_price = _normalize_currency_and_price(+ currency, float(price)+ )+ return MarketSymbolQuote(+ symbol=sym,+ name=raw.get("name"),+ exchange=raw.get("exchange"),+ currency=normalized_currency,+ price=normalized_price,+ quote_type=raw.get("quote_type"),+ logo_url=_logo_url_for(raw.get("website")),+ )++ # ---- sync helpers (called via asyncio.to_thread) ----++ @staticmethod+ def _search_sync(query: str, limit: int) -> list[dict]:+ import yfinance as yf++ try:+ # Search signature (yfinance 1.3.x): Search(query, max_results=8,+ # news_count=8, lists_count=8, include_cb=True, enable_fuzzy_query=False,+ # session=None, timeout=30, raise_errors=True). We turn news off and+ # let errors propagate so we can log them.+ result = yf.Search(+ query,+ max_results=limit,+ news_count=0,+ enable_fuzzy_query=True,+ raise_errors=False,+ )+ quotes = getattr(result, "quotes", None)+ if isinstance(quotes, list):+ return quotes+ # Defensive fallback for any future shape drift.+ response = getattr(result, "response", None) or {}+ return list(response.get("quotes") or [])+ except _rate_limit_exception_types():+ raise MarketPriceRateLimitedError("Yahoo Finance rate-limited the search")+ except Exception as e: # pragma: no cover — upstream flakiness, not logic+ logger.warning("yfinance search failed for %r: %s", query, e)+ return []++ @staticmethod+ def _download_prices_sync(symbols: list[str]) -> dict[str, Optional[Decimal]]:+ """Run ``yf.download`` and extract last-close per symbol.++ ``yf.download`` returns a pandas DataFrame: flat columns for a+ single symbol, MultiIndex (symbol, field) for multiple. Period is+ ``"5d"`` so we span weekends and market holidays while still+ getting today's close once the market has ticked.+ """+ import yfinance as yf++ out: dict[str, Optional[Decimal]] = {s: None for s in symbols}+ if not symbols:+ return out++ try:+ df = yf.download(+ tickers=symbols,+ period="5d",+ interval="1d",+ progress=False,+ # We're already inside asyncio.to_thread; disable yfinance's+ # own threading to avoid nested pools fighting each other.+ threads=False,+ auto_adjust=False,+ group_by="ticker",+ # raise_errors keeps us in control of exception handling.+ # Swallowing upstream failures silently would leave callers+ # unable to distinguish "no data" from "request blew up".+ )+ except Exception as e: # pragma: no cover — upstream flakiness+ logger.warning("yfinance batch download failed for %d symbols: %s", len(symbols), e)+ return out++ if df is None or df.empty:+ return out++ # Single-ticker downloads come back with flat columns — no MultiIndex.+ # Multi-ticker downloads use group_by="ticker" → MultiIndex (sym, field).+ if len(symbols) == 1:+ close_series = df.get("Close") if "Close" in df.columns else None+ out[symbols[0]] = _last_decimal_close(close_series)+ return out++ level0 = set(df.columns.get_level_values(0))+ for sym in symbols:+ if sym not in level0:+ continue+ try:+ sym_df = df[sym]+ except KeyError:+ continue+ close_series = sym_df.get("Close") if "Close" in getattr(sym_df, "columns", []) else None+ out[sym] = _last_decimal_close(close_series)+ return out++ @staticmethod+ def _quote_sync(symbol: str) -> Optional[dict]:+ import yfinance as yf++ try:+ ticker = yf.Ticker(symbol)+ fast = ticker.fast_info++ # FastInfo's public API is camelCase (snake_case is tolerated but+ # not advertised). See yfinance/scrapers/quote.py FastInfo class.+ price = _fast_info_value(fast, "lastPrice")+ # `lastPrice` is None briefly at market open; fall back to the+ # previous close so the UI still surfaces *something* sensible.+ if price is None:+ price = _fast_info_value(fast, "previousClose")+ currency = _fast_info_value(fast, "currency")+ exchange = _fast_info_value(fast, "exchange")+ quote_type = _fast_info_value(fast, "quoteType")++ # `info` is the slow path (full quoteSummary fetch) and the only+ # place the display name lives. Swallow any failure — the caller+ # only truly needs price + currency.+ try:+ info = ticker.info or {}+ except Exception:+ info = {}+ name = info.get("longName") or info.get("shortName") or None+ if not quote_type:+ quote_type = (info.get("quoteType") or "").upper() or None+ else:+ quote_type = str(quote_type).upper()++ return {+ "symbol": symbol,+ "name": name,+ "exchange": exchange,+ "currency": currency,+ "price": float(price) if price is not None else None,+ "quote_type": quote_type,+ # Yahoo's `info["website"]` is the source of truth for the+ # company domain, from which we build the logo URL. Missing+ # for most crypto/indices — caller will just skip the logo.+ "website": info.get("website") or None,+ }+ except _rate_limit_exception_types():+ raise MarketPriceRateLimitedError(+ f"Yahoo Finance rate-limited while quoting {symbol}"+ )+ except Exception as e: # pragma: no cover+ logger.warning("yfinance quote failed for %s: %s", symbol, e)+ return None+++def _extract_domain(url: Optional[str]) -> Optional[str]:+ """Extract the bare domain from a URL, stripping ``www.`` and scheme.++ Returns None for blanks / unparseable inputs. Used as the identifier+ Brandfetch (or any logo-by-domain service) expects.+ """+ if not url:+ return None+ try:+ parsed = urlparse(url if "://" in url else f"https://{url}")+ except ValueError:+ return None+ host = (parsed.hostname or "").strip().lower()+ if not host:+ return None+ return host[4:] if host.startswith("www.") else host+++def _logo_url_for(website: Optional[str]) -> Optional[str]:+ """Build a logo URL for a company website, or None if unavailable.++ Uses Google's free favicon service — no API key, no third-party sign-up,+ works for any public domain. Quality caps at 128×128 and can be lower+ for older sites; when Google doesn't have a favicon it returns a+ generic globe, which the frontend treats as "good enough" (falling+ back to the type icon is reserved for image-load failures).++ Returns None when the upstream quote didn't include a website (most+ crypto tickers), which is the signal for the frontend to show the+ type icon instead.+ """+ domain = _extract_domain(website)+ if not domain:+ return None+ size = get_settings().logo_size+ return f"https://www.google.com/s2/favicons?domain={domain}&sz={size}"+++def _last_decimal_close(series) -> Optional[Decimal]:+ """Return the most recent non-NaN Close price from a pandas Series.++ Weekends and holidays are NaN; drop them and grab the tail. If the+ whole series is empty or all-NaN we return None so the caller can+ skip the asset instead of writing garbage.+ """+ if series is None:+ return None+ try:+ import pandas as pd+ except ImportError: # pragma: no cover+ return None+ if len(series) == 0:+ return None+ cleaned = series.dropna() if hasattr(series, "dropna") else series+ if len(cleaned) == 0:+ return None+ val = cleaned.iloc[-1]+ if pd.isna(val):+ return None+ try:+ return Decimal(str(float(val)))+ except (TypeError, ValueError):+ return None+++def _fast_info_value(fast_info, key: str):+ """Read a field from yfinance's FastInfo (dict-like or attribute-like).++ camelCase is the canonical key. snake_case is supported as a hidden alias+ in current versions, but we pass camelCase everywhere for forward safety.+ """+ if fast_info is None:+ return None+ try:+ value = fast_info[key]+ except (KeyError, TypeError):+ value = None+ if value is not None:+ return value+ # Attribute fallback covers versions where FastInfo was attribute-only.+ return getattr(fast_info, key, None)+++def _rate_limit_exception_types() -> tuple[type[BaseException], ...]:+ """Return the yfinance exception classes that signal upstream throttling.++ Resolved at call time because yfinance's exception module moved around+ between minor versions — we don't want an import error at boot if the+ user has a slightly older release.+ """+ types: list[type[BaseException]] = []+ try:+ from yfinance.exceptions import YFRateLimitError++ types.append(YFRateLimitError)+ except Exception:+ pass+ return tuple(types) or ( # fallback: never match, but keep the except branch valid+ _UnreachableException,+ )+++class _UnreachableException(Exception):+ """Placeholder used when yfinance doesn't expose its rate-limit exception."""+++# Module-level singleton — cheap to construct, stateless beyond the yfinance+# import, and consumers need a stable instance for dependency overrides.+_default_provider: Optional[MarketPriceProvider] = None+++def get_market_price_provider() -> MarketPriceProvider:+ """Return the configured market-price provider (yfinance by default)."""+ global _default_provider+ if _default_provider is None:+ _default_provider = YFinanceProvider()+ return _default_provider+++def set_market_price_provider(provider: Optional[MarketPriceProvider]) -> None:+ """Test helper — swap the singleton for a fake."""+ global _default_provider+ _default_provider = providerdiff --git a/backend/app/schemas/asset.py b/backend/app/schemas/asset.pyindex 642dfa5e..a25800be 100644--- a/backend/app/schemas/asset.py+++ b/backend/app/schemas/asset.py@@ -1,5 +1,5 @@import uuid-from datetime import date+from datetime import date, datetimefrom decimal import Decimalfrom typing import Optional@@ -24,6 +24,10 @@ class AssetCreate(BaseModel):is_archived: bool = Falseposition: int = 0group_id: Optional[uuid.UUID] = None+ # Market-priced assets: ticker is enough to create one. The service+ # fetches the live quote on create and seeds the first AssetValue.+ ticker: Optional[str] = None+ ticker_exchange: Optional[str] = Noneclass AssetUpdate(BaseModel):@@ -46,6 +50,8 @@ class AssetUpdate(BaseModel):# from "remove from group" (explicit null). Pydantic's exclude_unset# already handles this via model_dump.group_id: Optional[uuid.UUID] = None+ ticker: Optional[str] = None+ ticker_exchange: Optional[str] = Noneclass AssetRead(BaseModel):@@ -76,10 +82,38 @@ class AssetRead(BaseModel):isin: Optional[str] = Nonematurity_date: Optional[date] = Nonegroup_id: Optional[uuid.UUID] = None+ ticker: Optional[str] = None+ ticker_exchange: Optional[str] = None+ last_price: Optional[float] = None+ last_price_at: Optional[datetime] = None+ logo_url: Optional[str] = Nonemodel_config = ConfigDict(from_attributes=True)+class MarketSymbolQuote(BaseModel):+ """Live quote for a ticker, used by the add-asset form to preview value."""++ symbol: str+ name: Optional[str] = None+ exchange: Optional[str] = None+ currency: str+ price: float+ quote_type: Optional[str] = None # EQUITY, ETF, CRYPTOCURRENCY, MUTUALFUND, ...+ # Fully-formed logo URL if the provider can derive one. Caller stores+ # this verbatim on the asset; no further processing required.+ logo_url: Optional[str] = None+++class MarketSymbolMatch(BaseModel):+ """A single search result returned by /assets/market/search."""++ symbol: str+ name: Optional[str] = None+ exchange: Optional[str] = None+ quote_type: Optional[str] = None++class AssetValueCreate(BaseModel):amount: Decimaldate: datediff --git a/backend/app/services/asset_service.py b/backend/app/services/asset_service.pyindex f6e1bb62..77fd7fc8 100644--- a/backend/app/services/asset_service.py+++ b/backend/app/services/asset_service.py@@ -1,8 +1,10 @@+import loggingimport uuid-from datetime import date, timedelta+from datetime import date, datetime, timezone, timedeltafrom decimal import Decimalfrom typing import Optional+from fastapi import HTTPException, statusfrom sqlalchemy import select, func, descfrom sqlalchemy.ext.asyncio import AsyncSession@@ -10,9 +12,16 @@ from app.core.config import get_settingsfrom app.models.asset import Assetfrom app.models.asset_value import AssetValuefrom app.models.user import User+from app.providers.market_price import (+ MarketPriceProvider,+ MarketPriceRateLimitedError,+ get_market_price_provider,+)from app.schemas.asset import AssetCreate, AssetUpdate, AssetValueCreate, AssetRead, AssetValueReadfrom app.services.fx_rate_service import convert, stamp_primary_amount+logger = logging.getLogger(__name__)+def _next_due_date(last_date: date, frequency: str) -> date:"""Calculate the next due date based on frequency."""@@ -36,6 +45,15 @@ def _next_due_date(last_date: date, frequency: str) -> date:def _compute_current_value(asset: Asset, latest_value: Optional[AssetValue]) -> Optional[float]:"""Compute the current value of an asset from its latest AssetValue.Falls back to purchase_price if no value entries exist yet."""+ # Market-priced assets are authoritative on (units × last_price). The+ # AssetValue history exists for the chart, but the "live" number users+ # see should reflect the most recent quote even between scheduled syncs.+ if asset.valuation_method == "market_price":+ if asset.last_price is not None and asset.units is not None:+ return float(Decimal(str(asset.last_price)) * Decimal(str(asset.units)))+ if latest_value is not None:+ return float(latest_value.amount)+ return Noneif latest_value is None:if asset.purchase_price is not None:return float(asset.purchase_price)@@ -117,6 +135,11 @@ def _asset_to_read(asset: Asset, latest_value: Optional[AssetValue], value_countisin=asset.isin,maturity_date=asset.maturity_date,group_id=asset.group_id,+ ticker=asset.ticker,+ ticker_exchange=asset.ticker_exchange,+ last_price=float(asset.last_price) if asset.last_price is not None else None,+ last_price_at=asset.last_price_at,+ logo_url=asset.logo_url,)@@ -175,14 +198,44 @@ async def get_asset(async def create_asset(- session: AsyncSession, user_id: uuid.UUID, data: AssetCreate+ session: AsyncSession,+ user_id: uuid.UUID,+ data: AssetCreate,+ *,+ market_provider: Optional[MarketPriceProvider] = None,) -> AssetRead:"""Create an asset, optionally with an initial value."""+ # Market-priced path: fetch a live quote first so we can derive currency+ # and the initial value from the ticker. Validate up-front rather than+ # half-creating an asset and failing on a 5xx from Yahoo.+ quote = None+ if data.valuation_method == "market_price":+ if not data.ticker:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail="ticker is required for market_price assets",+ )+ if data.units is None or data.units <= 0:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail="units (quantity) must be > 0 for market_price assets",+ )+ provider = market_provider or get_market_price_provider()+ quote = await provider.get_quote(data.ticker)+ if quote is None:+ raise HTTPException(+ status_code=status.HTTP_502_BAD_GATEWAY,+ detail=f"Could not fetch quote for {data.ticker}",+ )+asset = Asset(user_id=user_id,name=data.name,type=data.type,- currency=data.currency,+ # For market_price, the quote's currency is authoritative — a user+ # entering PETR4.SA from an English-language form shouldn't end up+ # with USD just because the dropdown defaulted to USD.+ currency=quote.currency if quote else data.currency,units=data.units,valuation_method=data.valuation_method,purchase_date=data.purchase_date,@@ -196,10 +249,29 @@ async def create_asset(is_archived=data.is_archived,position=data.position,group_id=data.group_id,+ ticker=data.ticker.upper() if data.ticker else None,+ ticker_exchange=data.ticker_exchange or (quote.exchange if quote else None),+ last_price=Decimal(str(quote.price)) if quote else None,+ last_price_at=datetime.now(timezone.utc) if quote else None,+ logo_url=quote.logo_url if quote else None,+ source="yfinance" if data.valuation_method == "market_price" else "manual",)session.add(asset)await session.flush()+ # Seed the first AssetValue from the live quote so the portfolio chart+ # has a starting data point without waiting for the scheduled refresh.+ if data.valuation_method == "market_price" and quote is not None:+ initial_amount = Decimal(str(quote.price)) * Decimal(str(data.units))+ session.add(+ AssetValue(+ asset_id=asset.id,+ amount=initial_amount,+ date=date.today(),+ source="sync",+ )+ )+# Create initial value if providedif data.current_value is not None:value = AssetValue(@@ -309,6 +381,20 @@ async def update_asset(date_field="purchase_date",)+ # If units change on a market-priced asset, rewrite today's AssetValue with+ # the new (units × last_price). Without this, the portfolio chart keeps+ # plotting the old position size even though the header and wallet totals+ # (computed live) already reflect the new units — the two disagree until+ # the next scheduled refresh overwrites today's row.+ if (+ "units" in update_data+ and asset.valuation_method == "market_price"+ and asset.last_price is not None+ and asset.units is not None+ and asset.units > 0+ ):+ await _apply_price_to_asset(session, asset, Decimal(str(asset.last_price)))+await session.commit()await session.refresh(asset)latest = await _get_latest_value(session, asset.id)@@ -437,9 +523,6 @@ async def get_portfolio_trend(user = await session.get(User, user_id)primary_currency = user.primary_currency if user else get_settings().default_currency- # Map asset_id -> currency for conversion- asset_currency: dict[str, str] = {}-for asset in active_assets:aid = str(asset.id)asset_meta.append({@@ -448,7 +531,6 @@ async def get_portfolio_trend("type": asset.type,"group_id": str(asset.group_id) if asset.group_id else None,})- asset_currency[aid] = asset.currencyrows = await session.execute(select(AssetValue.date, AssetValue.amount)@@ -462,6 +544,21 @@ async def get_portfolio_trend(if not vals or asset.purchase_date < vals[0][0]:vals.insert(0, (asset.purchase_date, float(asset.purchase_price)))+ # Convert every value to the primary currency at its own date so the+ # stacked areas and the tooltip total are all in the same unit. Before+ # this, a USD-quoted asset like AAPL contributed its raw $ value to+ # `_total`, making the tooltip disagree with the header (which does+ # FX-convert). `convert` falls back to the nearest available rate, so+ # dates missing exact FX data still produce a sensible number.+ if asset.currency != primary_currency:+ converted_vals: list[tuple[date, float]] = []+ for d, amt in vals:+ converted, _ = await convert(+ session, Decimal(str(amt)), asset.currency, primary_currency, d,+ )+ converted_vals.append((d, float(converted)))+ vals = converted_vals+asset_values_map[aid] = valsfor d, _ in vals:all_dates.add(d)@@ -501,18 +598,11 @@ async def get_portfolio_trend(row["_total"] = round(date_total, 2)trend.append(row)- # Total = sum of last known values, converted to primary currency- total = 0.0- for a in asset_meta:- aid = a["id"]- val = last_known[aid]- if val and asset_currency[aid] != primary_currency:- converted, _ = await convert(- session, Decimal(str(val)), asset_currency[aid], primary_currency,- )- total += float(converted)- else:- total += val+ # `last_known` already holds primary-currency values (we converted per-date+ # above when building asset_values_map). Summing directly keeps the header+ # total in lockstep with the tooltip's `_total` on the final row — any+ # second conversion here would double-count for non-primary assets.+ total = sum(last_known.values())return {"assets": asset_meta, "trend": trend, "total": round(total, 2)}@@ -538,3 +628,170 @@ async def get_total_asset_value(if current is not None:totals[asset.currency] = totals.get(asset.currency, 0.0) + currentreturn totals+++# ============================================================================+# Market-price refresh+# ============================================================================+++async def _apply_price_to_asset(+ session: AsyncSession, asset: Asset, new_price: Decimal+) -> None:+ """Update the cached price and upsert today's AssetValue.++ Shared by the single-asset and batch refresh paths so both behave+ identically: price + timestamp get stamped; today's value gets+ inserted or overwritten so running the task multiple times per day+ doesn't pile up duplicate rows.+ """+ asset.last_price = new_price+ asset.last_price_at = datetime.now(timezone.utc)++ if not asset.units or asset.units <= 0:+ return++ today = date.today()+ new_amount = new_price * Decimal(str(asset.units))+ existing = await session.execute(+ select(AssetValue)+ .where(AssetValue.asset_id == asset.id, AssetValue.date == today)+ .order_by(desc(AssetValue.id))+ .limit(1)+ )+ today_value = existing.scalar_one_or_none()+ if today_value is not None:+ today_value.amount = new_amount+ today_value.source = "sync"+ else:+ session.add(+ AssetValue(+ asset_id=asset.id,+ amount=new_amount,+ date=today,+ source="sync",+ )+ )+++async def refresh_market_price_asset(+ session: AsyncSession,+ asset: Asset,+ *,+ market_provider: Optional[MarketPriceProvider] = None,+) -> bool:+ """Re-quote a single market-priced asset and update its cached price.++ Returns True when a new quote was persisted, False otherwise (no quote+ available, stale price unchanged, or missing fields).+ """+ if asset.valuation_method != "market_price" or not asset.ticker:+ return False++ provider = market_provider or get_market_price_provider()+ try:+ quote = await provider.get_quote(asset.ticker)+ except MarketPriceRateLimitedError:+ # Let the scheduler see this explicitly so it can back off globally.+ raise+ except Exception as e:+ logger.warning("Market price refresh failed for %s: %s", asset.ticker, e)+ return False++ if quote is None or quote.price is None:+ return False++ await _apply_price_to_asset(session, asset, Decimal(str(quote.price)))+ # Opportunistic logo backfill: assets created before Brandfetch was+ # configured have no logo_url. On the next single-asset refresh (which+ # goes through the full get_quote → website lookup), stamp it in.+ # The batch refresh path doesn't have website info so it leaves logos+ # alone; manual refreshes and creates cover the fill-in.+ if not asset.logo_url and quote.logo_url:+ asset.logo_url = quote.logo_url+ await session.flush()+ return True+++async def refresh_all_market_prices(+ session: AsyncSession,+ *,+ market_provider: Optional[MarketPriceProvider] = None,+) -> dict[str, int]:+ """Refresh every non-archived market-priced asset in the database.++ Uses the provider's batch ``get_latest_prices`` endpoint when possible —+ one HTTP request covers the whole portfolio via ``yfinance.download``+ instead of one call per asset. Falls back silently to per-asset refresh+ if the batch returns nothing (provider without bulk support, or a hard+ failure on Yahoo's end).++ Returns a summary counting successes, skips, and rate-limit halts —+ surfaced as the Celery task's return payload for observability.+ """+ result = await session.execute(+ select(Asset).where(+ Asset.valuation_method == "market_price",+ Asset.is_archived == False,+ Asset.sell_date.is_(None),+ Asset.ticker.isnot(None),+ )+ )+ assets = list(result.scalars().all())++ if not assets:+ return {"refreshed": 0, "skipped": 0, "rate_limited": 0}++ provider = market_provider or get_market_price_provider()+ tickers = [a.ticker for a in assets if a.ticker]++ # Batch path: one request → dict[SYMBOL, price]. On rate-limit we halt+ # immediately — retrying within the same task would just pile on 429s+ # and risk an IP-level cookie ban.+ try:+ prices = await provider.get_latest_prices(tickers)+ except MarketPriceRateLimitedError:+ logger.warning("Yahoo rate-limited the batch fetch; skipping this cycle")+ return {"refreshed": 0, "skipped": len(assets), "rate_limited": 1}+ except Exception as e:+ logger.warning("Batch price fetch failed, falling back to per-asset: %s", e)+ prices = {}++ refreshed = 0+ skipped = 0++ for asset in assets:+ if not asset.ticker:+ skipped += 1+ continue+ price = prices.get(asset.ticker.upper()) if prices else None+ if price is None:+ # Per-asset fallback: the batch missed this symbol (delisted+ # ticker, one-off provider error, etc.). Try the full quote+ # path which also populates name/currency if needed.+ try:+ ok = await refresh_market_price_asset(+ session, asset, market_provider=provider+ )+ except MarketPriceRateLimitedError:+ logger.warning(+ "Yahoo rate-limited mid-refresh after %d assets; halting",+ refreshed,+ )+ await session.commit()+ return {+ "refreshed": refreshed,+ "skipped": skipped + (len(assets) - refreshed - skipped),+ "rate_limited": 1,+ }+ if ok:+ refreshed += 1+ else:+ skipped += 1+ continue++ await _apply_price_to_asset(session, asset, price)+ refreshed += 1++ await session.commit()+ return {"refreshed": refreshed, "skipped": skipped, "rate_limited": 0}diff --git a/backend/app/tasks/asset_tasks.py b/backend/app/tasks/asset_tasks.pyindex 778213e1..52efbafc 100644--- a/backend/app/tasks/asset_tasks.py+++ b/backend/app/tasks/asset_tasks.py@@ -10,6 +10,7 @@ from app.worker import celery_appfrom app.core.config import get_settingsfrom app.models.asset import Assetfrom app.models.asset_value import AssetValue+from app.services.asset_service import refresh_all_market_priceslogger = logging.getLogger(__name__)@@ -127,3 +128,37 @@ def apply_asset_growth_rules() -> dict:total = asyncio.run(_apply_growth_rules())logger.info("Asset growth rules complete: %d values created", total)return {"created": total}+++async def _refresh_market_prices() -> dict[str, int]:+ """Refresh live prices for every market-priced asset across all users.++ Uses a fresh async session per task run (same pattern as the growth-rule+ task above) to avoid sharing engines with the FastAPI request lifecycle.+ """+ session_maker = _make_session_maker()+ async with session_maker() as session:+ return await refresh_all_market_prices(session)+++@celery_app.task(name="app.tasks.asset_tasks.refresh_market_prices")+def refresh_market_prices() -> dict:+ """Celery task: re-quote every market-priced asset via the configured provider.++ Scheduled frequently enough that the cached price stays fresh for users,+ but respectful of Yahoo's unofficial rate limits — the service halts+ itself on ``MarketPriceRateLimitedError`` so we don't hammer the API.+ """+ try:+ result = asyncio.run(_refresh_market_prices())+ except Exception:+ logger.exception("Market-price refresh failed")+ return {"error": True, "refreshed": 0, "skipped": 0, "rate_limited": 0}++ logger.info(+ "Market-price refresh complete: %d refreshed, %d skipped, %d rate-limited",+ result.get("refreshed", 0),+ result.get("skipped", 0),+ result.get("rate_limited", 0),+ )+ return resultdiff --git a/backend/app/worker.py b/backend/app/worker.pyindex e467602f..84176eb7 100644--- a/backend/app/worker.py+++ b/backend/app/worker.py@@ -31,6 +31,14 @@ celery_app.conf.beat_schedule = {"task": "app.tasks.asset_tasks.apply_asset_growth_rules","schedule": 60 * 60, # every hour; idempotent (checks last value date)},+ "refresh-market-prices-daily": {+ "task": "app.tasks.asset_tasks.refresh_market_prices",+ # Once a day is enough for personal portfolio tracking — keeps us+ # well under Yahoo's unofficial per-IP caps and avoids the bot+ # heuristics that trip on a chatty schedule. Task upserts today's+ # AssetValue so history stays at one row per day per asset.+ "schedule": 60 * 60 * 24,+ },"sync-fx-rates-daily": {"task": "app.tasks.fx_rate_tasks.sync_fx_rates","schedule": 60 * 60 * 12, # twice daily (~60 API calls/month)diff --git a/backend/pyproject.toml b/backend/pyproject.tomlindex 45761f26..0d5284f2 100644--- a/backend/pyproject.toml+++ b/backend/pyproject.toml@@ -21,6 +21,7 @@ dependencies = ["aiofiles>=24.0","redis[hiredis]>=5.0.0","pyotp>=2.9.0",+ "yfinance>=1.3.0",][project.optional-dependencies]@@ -46,6 +47,7 @@ omit = ["app/worker.py","app/tasks/*","app/providers/pluggy.py",+ "app/providers/market_price.py",][tool.ruff]diff --git a/backend/tests/test_market_price_assets.py b/backend/tests/test_market_price_assets.pynew file mode 100644index 00000000..5016e59c--- /dev/null+++ b/backend/tests/test_market_price_assets.py@@ -0,0 +1,342 @@+"""Tests for market-priced assets (yfinance-backed valuation).++These tests stub the MarketPriceProvider so nothing hits the network —+yfinance flakes often enough in CI that any test depending on real+Yahoo responses would be permanently yellow. The stub verifies the+service wiring: create, refresh, upsert-today-value, and rate-limit+short-circuit.+"""++from __future__ import annotations++from datetime import date+from decimal import Decimal+from typing import Optional++import pytest+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.asset import Asset+from app.models.asset_value import AssetValue+from app.models.user import User+from app.providers.market_price import (+ MarketPriceProvider,+ MarketPriceRateLimitedError,+)+from app.schemas.asset import (+ AssetCreate,+ MarketSymbolMatch,+ MarketSymbolQuote,+)+from app.services import asset_service+from app.services.asset_service import (+ refresh_all_market_prices,+ refresh_market_price_asset,+)+++class FakeMarketProvider(MarketPriceProvider):+ """In-memory provider seeded with canned quotes per symbol."""++ name = "fake"++ def __init__(+ self,+ quotes: dict[str, MarketSymbolQuote],+ *,+ rate_limit_after: Optional[int] = None,+ # When set, overrides what `get_latest_prices` returns — lets tests+ # assert that the batch path is hit (or skipped) independently.+ batch_prices: Optional[dict[str, Optional[Decimal]]] = None,+ ) -> None:+ self._quotes = quotes+ self._calls = 0+ self._rate_limit_after = rate_limit_after+ self.batch_calls = 0+ self.quote_calls_after_batch = 0+ self._batch_prices = batch_prices++ async def search(self, query: str, limit: int = 20) -> list[MarketSymbolMatch]:+ q = query.upper()+ return [+ MarketSymbolMatch(symbol=q, name=f"{q} Inc", exchange="NASDAQ", quote_type="EQUITY"),+ ]++ async def get_quote(self, symbol: str) -> Optional[MarketSymbolQuote]:+ self._calls += 1+ if self.batch_calls > 0:+ self.quote_calls_after_batch += 1+ if self._rate_limit_after is not None and self._calls > self._rate_limit_after:+ raise MarketPriceRateLimitedError("simulated")+ return self._quotes.get(symbol.upper())++ async def get_latest_prices(self, symbols: list[str]) -> dict[str, Optional[Decimal]]:+ self.batch_calls += 1+ # The batch counts as a "request" for rate-limit purposes — a real+ # yfinance batch is exactly one HTTP call to Yahoo, same surface+ # area as any other request. Bumping `_calls` keeps the counter+ # semantics consistent with get_quote.+ self._calls += 1+ if self._rate_limit_after is not None and self._calls > self._rate_limit_after:+ raise MarketPriceRateLimitedError("simulated batch")+ if self._batch_prices is not None:+ return dict(self._batch_prices)+ out: dict[str, Optional[Decimal]] = {}+ for sym in symbols:+ q = self._quotes.get(sym.upper())+ out[sym.upper()] = Decimal(str(q.price)) if q and q.price else None+ return out+++def _quote(symbol: str, price: float, currency: str = "USD") -> MarketSymbolQuote:+ return MarketSymbolQuote(+ symbol=symbol,+ name=f"{symbol} Inc",+ exchange="NASDAQ",+ currency=currency,+ price=price,+ quote_type="EQUITY",+ )+++async def test_create_market_price_asset_seeds_quote_and_initial_value(+ session: AsyncSession, test_user: User+):+ provider = FakeMarketProvider({"AAPL": _quote("AAPL", 180.25)})+ data = AssetCreate(+ name="Apple",+ type="investment",+ currency="USD", # user-entered, but the quote's currency wins+ valuation_method="market_price",+ ticker="aapl",+ units=Decimal("10"),+ )++ created = await asset_service.create_asset(+ session, test_user.id, data, market_provider=provider+ )++ assert created.valuation_method == "market_price"+ # Ticker should be upper-cased and quote currency stamped on the asset.+ assert created.ticker == "AAPL"+ assert created.currency == "USD"+ assert created.last_price == pytest.approx(180.25)+ # Current value = units × last_price, computed live.+ assert created.current_value == pytest.approx(1802.50)+ # One AssetValue should have been seeded from the quote.+ assert created.value_count == 1+++async def test_create_market_price_asset_rejects_missing_ticker(+ session: AsyncSession, test_user: User+):+ provider = FakeMarketProvider({})+ data = AssetCreate(+ name="Bad Entry",+ type="investment",+ valuation_method="market_price",+ units=Decimal("5"),+ )++ with pytest.raises(Exception) as excinfo: # FastAPI's HTTPException+ await asset_service.create_asset(+ session, test_user.id, data, market_provider=provider+ )+ assert "ticker" in str(excinfo.value).lower()+++async def test_create_market_price_asset_rejects_zero_units(+ session: AsyncSession, test_user: User+):+ provider = FakeMarketProvider({"AAPL": _quote("AAPL", 180.0)})+ data = AssetCreate(+ name="Apple",+ type="investment",+ valuation_method="market_price",+ ticker="AAPL",+ units=Decimal("0"),+ )++ with pytest.raises(Exception) as excinfo:+ await asset_service.create_asset(+ session, test_user.id, data, market_provider=provider+ )+ assert "units" in str(excinfo.value).lower()+++async def test_create_market_price_asset_errors_when_quote_unavailable(+ session: AsyncSession, test_user: User+):+ provider = FakeMarketProvider({}) # no canned quote for any symbol+ data = AssetCreate(+ name="Ghost",+ type="investment",+ valuation_method="market_price",+ ticker="NOPE",+ units=Decimal("1"),+ )++ with pytest.raises(Exception) as excinfo:+ await asset_service.create_asset(+ session, test_user.id, data, market_provider=provider+ )+ assert "quote" in str(excinfo.value).lower()+++async def test_refresh_market_price_updates_cached_price_and_upserts_today(+ session: AsyncSession, test_user: User+):+ # First create with an initial quote, then bump the quote and refresh.+ initial = FakeMarketProvider({"AAPL": _quote("AAPL", 180.00)})+ data = AssetCreate(+ name="Apple",+ type="investment",+ valuation_method="market_price",+ ticker="AAPL",+ units=Decimal("10"),+ )+ created = await asset_service.create_asset(+ session, test_user.id, data, market_provider=initial+ )++ # Reload the ORM entity (service returned a schema, not the model).+ asset = await session.get(Asset, created.id)+ assert asset is not None++ # Upstream price moves: refresh should overwrite last_price and amend+ # today's AssetValue in place rather than creating a second row.+ second = FakeMarketProvider({"AAPL": _quote("AAPL", 190.00)})+ updated = await refresh_market_price_asset(session, asset, market_provider=second)+ await session.commit()++ assert updated is True+ assert asset.last_price == Decimal("190.000000")++ values = await session.execute(+ select(AssetValue).where(AssetValue.asset_id == asset.id)+ )+ all_values = list(values.scalars().all())+ todays = [v for v in all_values if v.date == date.today()]+ # Exactly one value for today — the refresh must upsert, not append.+ assert len(todays) == 1+ assert todays[0].amount == Decimal("1900.000000")+ assert todays[0].source == "sync"+++async def test_refresh_all_uses_batch_endpoint(+ session: AsyncSession, test_user: User+):+ """Scheduled refresh should hit the batch path once, not N single quotes."""+ provider = FakeMarketProvider(+ {+ "AAPL": _quote("AAPL", 180.0),+ "MSFT": _quote("MSFT", 400.0),+ "GOOG": _quote("GOOG", 150.0),+ }+ )+ for ticker in ("AAPL", "MSFT", "GOOG"):+ await asset_service.create_asset(+ session,+ test_user.id,+ AssetCreate(+ name=ticker,+ type="investment",+ valuation_method="market_price",+ ticker=ticker,+ units=Decimal("1"),+ ),+ market_provider=provider,+ )++ # Reset counters — create_asset already used get_quote 3 times.+ provider.batch_calls = 0+ provider.quote_calls_after_batch = 0++ result = await refresh_all_market_prices(session, market_provider=provider)++ assert result == {"refreshed": 3, "skipped": 0, "rate_limited": 0}+ # One batch call covered all three symbols.+ assert provider.batch_calls == 1+ # No per-symbol fallback should have fired since the batch returned everything.+ assert provider.quote_calls_after_batch == 0+++async def test_refresh_all_falls_back_when_batch_misses_symbol(+ session: AsyncSession, test_user: User+):+ """If a symbol is missing from the batch response, per-asset path picks it up."""+ provider = FakeMarketProvider(+ {"AAPL": _quote("AAPL", 180.0), "MSFT": _quote("MSFT", 400.0)}+ )+ for ticker in ("AAPL", "MSFT"):+ await asset_service.create_asset(+ session,+ test_user.id,+ AssetCreate(+ name=ticker,+ type="investment",+ valuation_method="market_price",+ ticker=ticker,+ units=Decimal("1"),+ ),+ market_provider=provider,+ )++ # Simulate Yahoo returning only AAPL from the batch — MSFT should+ # drop through to the per-asset fallback.+ provider = FakeMarketProvider(+ {"AAPL": _quote("AAPL", 181.0), "MSFT": _quote("MSFT", 402.0)},+ batch_prices={"AAPL": Decimal("181.0"), "MSFT": None},+ )++ result = await refresh_all_market_prices(session, market_provider=provider)+ assert result["refreshed"] == 2+ assert provider.batch_calls == 1+ # Exactly one per-asset fallback call (for MSFT).+ assert provider.quote_calls_after_batch == 1+++async def test_refresh_all_halts_on_rate_limit(+ session: AsyncSession, test_user: User+):+ # Create two market-priced assets+ provider = FakeMarketProvider({"AAPL": _quote("AAPL", 180.0), "MSFT": _quote("MSFT", 400.0)})+ for ticker in ("AAPL", "MSFT"):+ await asset_service.create_asset(+ session,+ test_user.id,+ AssetCreate(+ name=ticker,+ type="investment",+ valuation_method="market_price",+ ticker=ticker,+ units=Decimal("1"),+ ),+ market_provider=provider,+ )++ # Now make any further quote call rate-limit — refresh should stop,+ # not continue hitting Yahoo after the first throttled response. Since+ # the batch path is tried first and our fake's batch helper internally+ # calls get_quote (no canned batch_prices), the rate-limit fires at+ # the batch step, which halts the whole cycle.+ limited = FakeMarketProvider(+ {"AAPL": _quote("AAPL", 181.0), "MSFT": _quote("MSFT", 401.0)},+ rate_limit_after=0,+ )+ result = await refresh_all_market_prices(session, market_provider=limited)++ assert result["rate_limited"] == 1+ # Nothing refreshed — batch halt means every asset landed in the+ # skipped bucket, no per-asset fallback was attempted.+ assert result["refreshed"] == 0+ assert result["skipped"] == 2diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 2d43562a..a2c0b13a 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -22,6 +22,8 @@ import type {Asset,AssetGroup,AssetValue,+ MarketSymbolMatch,+ MarketSymbolQuote,Attachment,Goal,GoalSummary,@@ -582,6 +584,18 @@ export const assets = {const { data } = await api.get('/assets/portfolio-trend')return data},+ marketSearch: async (q: string, limit = 15): Promise<MarketSymbolMatch[]> => {+ const { data } = await api.get('/assets/market/search', { params: { q, limit } })+ return data+ },+ marketQuote: async (symbol: string): Promise<MarketSymbolQuote> => {+ const { data } = await api.get('/assets/market/quote', { params: { symbol } })+ return data+ },+ refreshPrice: async (id: string): Promise<Asset> => {+ const { data } = await api.post(`/assets/${id}/refresh-price`)+ return data+ },}// Asset Groups ("wallets")diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex 4ddba50a..9d1a5666 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -622,10 +622,23 @@"typeVehicle": "Vehicle","typeValuable": "Valuable","typeInvestment": "Investment",+ "typeStock": "Stock",+ "typeEtf": "ETF",+ "typeCrypto": "Crypto",+ "typeFund": "Fund","typeOther": "Other","valuationMethod": "Valuation Method","manual": "Manual","growthRule": "Growth Rule",+ "marketPrice": "Market Price",+ "ticker": "Ticker",+ "tickerPlaceholder": "e.g. AAPL, BTC-USD, PETR4.SA",+ "quantity": "Quantity",+ "marketPriceSource": "Live quote",+ "marketPriceSourceTooltip": "Price refreshed automatically from market data",+ "lastUpdated": "Updated {{when}}",+ "refreshPrice": "Refresh price",+ "priceRefreshed": "Price refreshed","purchaseDate": "Purchase Date","purchasePrice": "Purchase Price","sellDate": "Sell Date",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 0e6aa937..bf06c6d5 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -622,10 +622,23 @@"typeVehicle": "Veículo","typeValuable": "Bem de Valor","typeInvestment": "Investimento",+ "typeStock": "Ação",+ "typeEtf": "ETF",+ "typeCrypto": "Cripto",+ "typeFund": "Fundo","typeOther": "Outro","valuationMethod": "Método de Valuação","manual": "Manual","growthRule": "Regra de Crescimento",+ "marketPrice": "Preço de Mercado",+ "ticker": "Código",+ "tickerPlaceholder": "ex. AAPL, BTC-USD, PETR4.SA",+ "quantity": "Quantidade",+ "marketPriceSource": "Cotação",+ "marketPriceSourceTooltip": "Preço atualizado automaticamente via dados de mercado",+ "lastUpdated": "Atualizado {{when}}",+ "refreshPrice": "Atualizar cotação",+ "priceRefreshed": "Cotação atualizada","purchaseDate": "Data de Compra","purchasePrice": "Preço de Compra","sellDate": "Data de Venda",diff --git a/frontend/src/pages/assets.tsx b/frontend/src/pages/assets.tsxindex 5d2055fb..d686fbbd 100644--- a/frontend/src/pages/assets.tsx+++ b/frontend/src/pages/assets.tsx@@ -1,4 +1,4 @@-import { useState, useMemo } from 'react'+import { useState, useMemo, useEffect } from 'react'import { useTranslation } from 'react-i18next'import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'import { assets, assetGroups, currencies as currenciesApi } from '@/lib/api'@@ -16,7 +16,7 @@ import {import { Badge } from '@/components/ui/badge'import { Skeleton } from '@/components/ui/skeleton'import { DatePickerInput } from '@/components/ui/date-picker-input'-import type { Asset, AssetGroup, AssetValue } from '@/types'+import type { Asset, AssetGroup, AssetValue, MarketSymbolMatch, MarketSymbolQuote } from '@/types'import {Home,Car,@@ -32,6 +32,10 @@ import {RefreshCw,Wallet,FolderInput,+ LineChart,+ Layers,+ Bitcoin,+ PieChart,} from 'lucide-react'import {AreaChart,@@ -54,11 +58,73 @@ function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {}}+// Renders a logo image when one is available, falling back to the asset's+// type-based Lucide icon on missing URL or broken image. Uses the type's+// bg color as a tinted placeholder; switches to a white card + border when+// showing a real logo so brand colors don't clash with our palette.+function AssetIcon({+ logoUrl,+ Icon,+ colorClass,+ bgClass,+ size = 20,+ tile = 'w-10 h-10',+}: {+ logoUrl: string | null | undefined+ Icon: React.ElementType+ colorClass: string+ bgClass: string+ size?: number+ tile?: string+}) {+ const [errored, setErrored] = useState(false)+ const showImage = !!logoUrl && !errored+ return (+ <div+ className={`${tile} rounded-lg flex items-center justify-center overflow-hidden shrink-0 ${+ showImage ? 'bg-white border border-border' : bgClass+ }`}+ >+ {showImage ? (+ <img+ src={logoUrl!}+ alt=""+ className="w-full h-full object-contain"+ onError={() => setErrored(true)}+ />+ ) : (+ <Icon size={size} className={colorClass} />+ )}+ </div>+ )+}++// Compact relative-time formatter ("2h ago" / "há 2h"). Used for the price+// preview "last updated" hint. Intl.RelativeTimeFormat handles the locale+// grammar so we don't hand-roll plurals. Falls back to absolute date only+// when the input is missing — otherwise always returns a relative string.+function formatRelativeTime(dateInput: string | null | undefined, locale: string): string | null {+ if (!dateInput) return null+ const then = new Date(dateInput).getTime()+ if (Number.isNaN(then)) return null+ const diffSec = (then - Date.now()) / 1000+ const absSec = Math.abs(diffSec)+ const rtf = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' })+ if (absSec < 60) return rtf.format(Math.round(diffSec), 'second')+ if (absSec < 3600) return rtf.format(Math.round(diffSec / 60), 'minute')+ if (absSec < 86400) return rtf.format(Math.round(diffSec / 3600), 'hour')+ return rtf.format(Math.round(diffSec / 86400), 'day')+}+const ASSET_TYPE_CONFIG: Record<string, { icon: React.ElementType; color: string; bg: string }> = {real_estate: { icon: Home, color: 'text-blue-600', bg: 'bg-blue-100' },vehicle: { icon: Car, color: 'text-violet-600', bg: 'bg-violet-100' },valuable: { icon: Gem, color: 'text-amber-600', bg: 'bg-amber-100' },investment: { icon: TrendingUp, color: 'text-emerald-600', bg: 'bg-emerald-100' },+ stock: { icon: LineChart, color: 'text-sky-600', bg: 'bg-sky-100' },+ etf: { icon: Layers, color: 'text-teal-600', bg: 'bg-teal-100' },+ crypto: { icon: Bitcoin, color: 'text-orange-600', bg: 'bg-orange-100' },+ fund: { icon: PieChart, color: 'text-indigo-600', bg: 'bg-indigo-100' },other: { icon: Package, color: 'text-slate-600', bg: 'bg-slate-100' },}@@ -66,8 +132,37 @@ function getTypeConfig(type: string) {return ASSET_TYPE_CONFIG[type] ?? ASSET_TYPE_CONFIG['other']}-const ASSET_TYPES = ['real_estate', 'vehicle', 'valuable', 'investment', 'other'] as const-const VALUATION_METHODS = ['manual', 'growth_rule'] as const+const ASSET_TYPES = [+ 'stock',+ 'etf',+ 'crypto',+ 'fund',+ 'real_estate',+ 'vehicle',+ 'valuable',+ 'investment',+ 'other',+] as const++// Map a yfinance `quoteType` to Securo's asset type. Lives here (not the+// backend) so if we ever swap the market-price provider the service stays+// clean — all provider-specific vocabulary is translated at the edge.+function assetTypeFromQuoteType(quoteType: string | null | undefined): string {+ switch ((quoteType || '').toUpperCase()) {+ case 'EQUITY':+ return 'stock'+ case 'ETF':+ return 'etf'+ case 'CRYPTOCURRENCY':+ return 'crypto'+ case 'MUTUALFUND':+ case 'INDEX':+ return 'fund'+ default:+ return 'investment'+ }+}+const VALUATION_METHODS = ['manual', 'growth_rule', 'market_price'] as constconst GROWTH_TYPES = ['percentage', 'absolute'] as constconst GROWTH_FREQUENCIES = ['daily', 'weekly', 'monthly', 'yearly'] as const@@ -116,6 +211,13 @@ export default function AssetsPage() {const [formGrowthRate, setFormGrowthRate] = useState('')const [formGrowthFrequency, setFormGrowthFrequency] = useState<string>('monthly')const [formGrowthStartDate, setFormGrowthStartDate] = useState<string>('')+ // Market-price form state+ const [formTickerQuery, setFormTickerQuery] = useState('')+ const [tickerMatches, setTickerMatches] = useState<MarketSymbolMatch[]>([])+ const [tickerSearchLoading, setTickerSearchLoading] = useState(false)+ const [selectedQuote, setSelectedQuote] = useState<MarketSymbolQuote | null>(null)+ const [formUnits, setFormUnits] = useState('')+ const [quoteLoading, setQuoteLoading] = useState(false)const { data: assetsList, isLoading } = useQuery({queryKey: ['assets'],@@ -127,12 +229,20 @@ export default function AssetsPage() {queryFn: () => assets.portfolioTrend(),})+ // `refetchQueries` (vs. `invalidateQueries`) forces an immediate refetch+ // regardless of stale-state heuristics. Our global staleTime of 5 min+ // combined with the dialog-close re-render was sometimes leaving the+ // asset list showing pre-edit data until the user manually reloaded.+ function refetchAssetViews() {+ queryClient.refetchQueries({ queryKey: ['assets'] })+ queryClient.refetchQueries({ queryKey: ['portfolio-trend'] })+ queryClient.refetchQueries({ queryKey: ['dashboard'] })+ }+const createMutation = useMutation({mutationFn: (data: Parameters<typeof assets.create>[0]) => assets.create(data),onSuccess: () => {- queryClient.invalidateQueries({ queryKey: ['assets'] })- queryClient.invalidateQueries({ queryKey: ['portfolio-trend'] })- queryClient.invalidateQueries({ queryKey: ['dashboard'] })+ refetchAssetViews()setDialogOpen(false)toast.success(t('assets.created'))},@@ -143,9 +253,7 @@ export default function AssetsPage() {mutationFn: ({ id, _regenerateGrowth, ...data }: Partial<Asset> & { id: string; _regenerateGrowth?: boolean }) =>assets.update(id, data, { regenerateGrowth: _regenerateGrowth }),onSuccess: () => {- queryClient.invalidateQueries({ queryKey: ['assets'] })- queryClient.invalidateQueries({ queryKey: ['portfolio-trend'] })- queryClient.invalidateQueries({ queryKey: ['dashboard'] })+ refetchAssetViews()setDialogOpen(false)setEditingAsset(null)toast.success(t('assets.updated'))@@ -156,9 +264,7 @@ export default function AssetsPage() {const deleteMutation = useMutation({mutationFn: (id: string) => assets.delete(id),onSuccess: () => {- queryClient.invalidateQueries({ queryKey: ['assets'] })- queryClient.invalidateQueries({ queryKey: ['portfolio-trend'] })- queryClient.invalidateQueries({ queryKey: ['dashboard'] })+ refetchAssetViews()setDeletingId(null)if (expandedId === deletingId) setExpandedId(null)toast.success(t('assets.deleted'))@@ -166,6 +272,27 @@ export default function AssetsPage() {onError: () => toast.error(t('common.error')),})+ const refreshPriceMutation = useMutation({+ mutationFn: (id: string) => assets.refreshPrice(id),+ onSuccess: (updated) => {+ // Sync the dialog's preview to the fresh quote so the user sees the+ // new price without closing the dialog. The list + chart refetch+ // via our standard helper.+ setSelectedQuote({+ symbol: updated.ticker || '',+ name: updated.name,+ exchange: updated.ticker_exchange,+ currency: updated.currency,+ price: updated.last_price ?? 0,+ quote_type: null,+ })+ setEditingAsset(updated)+ refetchAssetViews()+ toast.success(t('assets.priceRefreshed'))+ },+ onError: () => toast.error(t('common.error')),+ })+const { data: walletsList } = useQuery({queryKey: ['asset-groups'],queryFn: () => assetGroups.list(),@@ -175,7 +302,7 @@ export default function AssetsPage() {mutationFn: (data: { name: string; color: string }) =>assetGroups.create({ name: data.name, color: data.color, icon: 'wallet' }),onSuccess: () => {- queryClient.invalidateQueries({ queryKey: ['asset-groups'] })+ queryClient.refetchQueries({ queryKey: ['asset-groups'] })setWalletDialogOpen(false)setEditingWallet(null)toast.success(t('assets.walletCreated'))@@ -187,7 +314,7 @@ export default function AssetsPage() {mutationFn: ({ id, ...data }: { id: string; name: string; color: string }) =>assetGroups.update(id, { name: data.name, color: data.color }),onSuccess: () => {- queryClient.invalidateQueries({ queryKey: ['asset-groups'] })+ queryClient.refetchQueries({ queryKey: ['asset-groups'] })setWalletDialogOpen(false)setEditingWallet(null)toast.success(t('assets.walletUpdated'))@@ -199,8 +326,8 @@ export default function AssetsPage() {mutationFn: (id: string) => assetGroups.delete(id),onSuccess: () => {// Deleting a wallet un-groups its assets (backend sets group_id=null).- queryClient.invalidateQueries({ queryKey: ['asset-groups'] })- queryClient.invalidateQueries({ queryKey: ['assets'] })+ queryClient.refetchQueries({ queryKey: ['asset-groups'] })+ queryClient.refetchQueries({ queryKey: ['assets'] })setDeletingWalletId(null)toast.success(t('assets.walletDeleted'))},@@ -211,8 +338,8 @@ export default function AssetsPage() {mutationFn: ({ id, groupId }: { id: string; groupId: string | null }) =>assets.update(id, { group_id: groupId } as Partial<Asset>),onSuccess: () => {- queryClient.invalidateQueries({ queryKey: ['assets'] })- queryClient.invalidateQueries({ queryKey: ['asset-groups'] })+ queryClient.refetchQueries({ queryKey: ['assets'] })+ queryClient.refetchQueries({ queryKey: ['asset-groups'] })setMovingAsset(null)toast.success(t('assets.moved'))},@@ -257,6 +384,71 @@ export default function AssetsPage() {const activeAssets = assetsList?.filter(a => !a.sell_date && !a.is_archived) ?? []const soldAssets = assetsList?.filter(a => a.sell_date) ?? []+ // Debounced ticker search. Runs only when the market-price method is+ // selected and the query is non-trivial — keeps the autocomplete snappy+ // without flooding the yfinance-backed endpoint.+ useEffect(() => {+ if (formMethod !== 'market_price') return+ const q = formTickerQuery.trim()+ // Don't search if the field matches the already-selected quote — the+ // user just picked it and we'd spam the endpoint for no reason.+ if (selectedQuote && q === selectedQuote.symbol) return+ if (q.length < 1) {+ setTickerMatches([])+ return+ }+ setTickerSearchLoading(true)+ const handle = window.setTimeout(async () => {+ try {+ const results = await assets.marketSearch(q, 10)+ setTickerMatches(results)+ } catch {+ setTickerMatches([])+ } finally {+ setTickerSearchLoading(false)+ }+ }, 300)+ return () => window.clearTimeout(handle)+ }, [formMethod, formTickerQuery, selectedQuote])++ async function pickTickerMatch(match: MarketSymbolMatch) {+ setTickerMatches([])+ setFormTickerQuery(match.symbol)+ setQuoteLoading(true)+ try {+ const quote = await assets.marketQuote(match.symbol)+ setSelectedQuote(quote)+ // Auto-fill name/currency from the authoritative quote so the user+ // doesn't have to think about it — they can still edit name after.+ if (!formName || formName === (selectedQuote?.name ?? selectedQuote?.symbol ?? '')) {+ setFormName(quote.name || quote.symbol)+ }+ setFormCurrency(quote.currency)+ // Classify the asset from the quote type (EQUITY → stock, etc.) so+ // the Tipo dropdown lands on something meaningful by default. We+ // skip this when the user already picked a non-default type, so+ // manual overrides stick.+ const suggestedType = assetTypeFromQuoteType(quote.quote_type)+ if (formType === 'other' || formType === 'investment') {+ setFormType(suggestedType)+ }+ } catch {+ toast.error(t('common.error'))+ setSelectedQuote(null)+ } finally {+ setQuoteLoading(false)+ }+ }++ function resetMarketPriceForm() {+ setFormTickerQuery('')+ setTickerMatches([])+ setSelectedQuote(null)+ setFormUnits('')+ setQuoteLoading(false)+ setTickerSearchLoading(false)+ }+function openCreate() {setEditingAsset(null)setFormName('')@@ -272,6 +464,7 @@ export default function AssetsPage() {setFormGrowthRate('')setFormGrowthFrequency('monthly')setFormGrowthStartDate('')+ resetMarketPriceForm()setDialogOpen(true)}@@ -290,6 +483,23 @@ export default function AssetsPage() {setFormGrowthRate(asset.growth_rate?.toString() ?? '')setFormGrowthFrequency(asset.growth_frequency ?? 'monthly')setFormGrowthStartDate(asset.growth_start_date ?? '')+ resetMarketPriceForm()+ if (asset.valuation_method === 'market_price' && asset.ticker) {+ setFormTickerQuery(asset.ticker)+ setFormUnits(asset.units?.toString() ?? '')+ // Synthesize a quote from the cached fields so the preview shows+ // immediately — we skip a round-trip to yfinance on edit open.+ if (asset.last_price != null) {+ setSelectedQuote({+ symbol: asset.ticker,+ name: asset.name,+ exchange: asset.ticker_exchange,+ currency: asset.currency,+ price: asset.last_price,+ quote_type: null,+ })+ }+ }setDialogOpen(true)}@@ -312,6 +522,12 @@ export default function AssetsPage() {payload.growth_start_date = formGrowthStartDate || null}+ if (formMethod === 'market_price') {+ payload.ticker = (selectedQuote?.symbol || formTickerQuery || '').toUpperCase()+ payload.ticker_exchange = selectedQuote?.exchange ?? null+ payload.units = formUnits ? parseFloat(formUnits) : null+ }+if (!editingAsset && formCurrentValue) {payload.current_value = parseFloat(formCurrentValue)}@@ -359,6 +575,13 @@ export default function AssetsPage() {const Icon = config.iconconst isExpanded = expandedId === asset.idconst isSynced = asset.source !== 'manual'+ // Split "externally-owned" (bank/brokerage record — gets overwritten on+ // re-sync, so read-only for users) from "market-priced" (user-created+ // record where only the cached price syncs). We key on valuation_method+ // rather than the concrete source string so swapping the price provider+ // (yfinance → anything else) doesn't break this logic.+ const isMarketPriced = asset.valuation_method === 'market_price'+ const isProviderOwned = isSynced && !isMarketPricedreturn (<div key={asset.id} className="border border-border rounded-xl bg-card shadow-sm overflow-hidden">@@ -366,16 +589,28 @@ export default function AssetsPage() {className="flex items-center gap-4 px-5 py-4 cursor-pointer hover:bg-muted/30 transition-colors"onClick={() => setExpandedId(isExpanded ? null : asset.id)}>- <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${config.bg}`}>- <Icon size={20} className={config.color} />- </div>+ <AssetIcon+ logoUrl={asset.logo_url}+ Icon={Icon}+ colorClass={config.color}+ bgClass={config.bg}+ /><div className="flex-1 min-w-0"><div className="flex items-center gap-2"><span className="text-sm font-semibold text-foreground truncate">{asset.name}</span><Badge variant="secondary" className="text-[10px] px-1.5 py-0">{t(`assets.type${asset.type.replace(/_([a-z])/g, (_, c: string) => c.toUpperCase()).replace(/^./, c => c.toUpperCase())}`)}</Badge>- {isSynced && (+ {isMarketPriced ? (+ <Badge+ variant="outline"+ className="text-[10px] px-1.5 py-0 text-primary border-primary/30 gap-1"+ title={t('assets.marketPriceSourceTooltip')}+ >+ <TrendingUp size={9} />+ {t('assets.marketPriceSource')}+ </Badge>+ ) : isSynced ? (<Badgevariant="outline"className="text-[10px] px-1.5 py-0 text-sky-600 border-sky-200 gap-1"@@ -384,7 +619,7 @@ export default function AssetsPage() {<RefreshCw size={9} />{t('assets.synced')}</Badge>- )}+ ) : null}{asset.maturity_date && (<Badge variant="outline" className="text-[10px] px-1.5 py-0 text-muted-foreground">{t('assets.maturesOn', { date: new Date(asset.maturity_date).toLocaleDateString(locale) })}@@ -438,17 +673,17 @@ export default function AssetsPage() {<FolderInput size={14} /></button><button- onClick={(e) => { e.stopPropagation(); if (!isSynced) openEdit(asset) }}- disabled={isSynced}- title={isSynced ? t('assets.syncedReadOnly') : undefined}+ onClick={(e) => { e.stopPropagation(); if (!isProviderOwned) openEdit(asset) }}+ disabled={isProviderOwned}+ title={isProviderOwned ? t('assets.syncedReadOnly') : undefined}className="p-1.5 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent"><Pencil size={14} /></button><button- onClick={(e) => { e.stopPropagation(); if (!isSynced) setDeletingId(asset.id) }}- disabled={isSynced}- title={isSynced ? t('assets.syncedReadOnly') : undefined}+ onClick={(e) => { e.stopPropagation(); if (!isProviderOwned) setDeletingId(asset.id) }}+ disabled={isProviderOwned}+ title={isProviderOwned ? t('assets.syncedReadOnly') : undefined}className="p-1.5 rounded-lg text-muted-foreground hover:text-rose-600 hover:bg-rose-50 transition-colors disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent"><Trash2 size={14} />@@ -702,8 +937,9 @@ export default function AssetsPage() {<div className="space-y-2"><Label>{t('assets.currency')}</Label><select- className="bg-card border border-border focus:outline-none focus:ring-2 focus:ring-primary px-3 py-2 rounded-lg text-foreground text-sm w-full"+ className="bg-card border border-border focus:outline-none focus:ring-2 focus:ring-primary px-3 py-2 rounded-lg text-foreground text-sm w-full disabled:opacity-60 disabled:cursor-not-allowed"value={formCurrency}+ disabled={formMethod === 'market_price'}onChange={e => setFormCurrency(e.target.value)}>{(supportedCurrencies ?? [{ code: userCurrency, symbol: userCurrency, name: userCurrency, flag: '' }]).map((c) => (@@ -716,7 +952,7 @@ export default function AssetsPage() {{/* Valuation Method — locked on edit */}<div className="space-y-2"><Label>{t('assets.valuationMethod')}</Label>- <div className="grid grid-cols-2 gap-2">+ <div className="grid grid-cols-3 gap-2">{VALUATION_METHODS.map(m => (<buttonkey={m}@@ -729,12 +965,149 @@ export default function AssetsPage() {} ${editingAsset ? 'opacity-50 cursor-not-allowed' : ''}`}onClick={() => !editingAsset && setFormMethod(m)}>- {t(`assets.${m === 'growth_rule' ? 'growthRule' : 'manual'}`)}+ {m === 'market_price'+ ? t('assets.marketPrice')+ : m === 'growth_rule'+ ? t('assets.growthRule')+ : t('assets.manual')}</button>))}</div></div>+ {/* Market Price (yfinance) — ticker search + quantity */}+ {formMethod === 'market_price' && (+ <div className="space-y-3 p-3.5 rounded-xl border border-primary/20 bg-primary/5">+ <div className="space-y-2">+ <Label>{t('assets.ticker')}</Label>+ <div className="relative">+ <Input+ placeholder={t('assets.tickerPlaceholder')}+ value={formTickerQuery}+ disabled={!!editingAsset}+ onChange={e => {+ setFormTickerQuery(e.target.value)+ // Clear the quote so we don't keep the old preview+ // while the user is editing the symbol — prevents+ // a stale price from being saved accidentally.+ if (selectedQuote && e.target.value.toUpperCase() !== selectedQuote.symbol) {+ setSelectedQuote(null)+ }+ }}+ />+ {tickerMatches.length > 0 && !editingAsset && (+ <div className="absolute z-20 mt-1 w-full max-h-60 overflow-y-auto rounded-lg border border-border bg-popover shadow-lg">+ {tickerMatches.map(match => (+ <button+ key={`${match.symbol}-${match.exchange ?? ''}`}+ type="button"+ onClick={() => pickTickerMatch(match)}+ className="flex flex-col w-full text-left px-3 py-2 hover:bg-muted transition-colors"+ >+ <div className="flex items-center justify-between gap-2">+ <span className="font-semibold text-sm">{match.symbol}</span>+ {match.exchange && (+ <span className="text-xs text-muted-foreground">{match.exchange}</span>+ )}+ </div>+ {match.name && (+ <span className="text-xs text-muted-foreground truncate">{match.name}</span>+ )}+ </button>+ ))}+ </div>+ )}+ {tickerSearchLoading && (+ <span className="absolute right-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground pointer-events-none">+ {t('common.loading')}+ </span>+ )}+ </div>+ </div>++ {selectedQuote && (+ <div className="rounded-lg border border-border bg-card p-3 text-sm">+ <div className="flex items-center justify-between">+ <div className="flex flex-col min-w-0">+ <span className="font-semibold">{selectedQuote.symbol}</span>+ {selectedQuote.name && (+ <span className="text-xs text-muted-foreground truncate">{selectedQuote.name}</span>+ )}+ {/* Staleness hint — only meaningful when editing an+ existing asset (last_price_at is set). Hidden+ during create because the quote is inline-live. */}+ {editingAsset?.last_price_at && (+ <span className="text-[10px] text-muted-foreground mt-0.5">+ {t('assets.lastUpdated', { when: formatRelativeTime(editingAsset.last_price_at, locale) })}+ </span>+ )}+ </div>+ <div className="flex items-center gap-2 shrink-0">+ <div className="text-right">+ <div className="text-base font-bold tabular-nums">+ {formatCurrency(selectedQuote.price, selectedQuote.currency, locale)}+ </div>+ {selectedQuote.exchange && (+ <div className="text-[10px] text-muted-foreground uppercase tracking-wide">+ {selectedQuote.exchange}+ </div>+ )}+ </div>+ {/* Manual refresh — only on edit. Daily cron handles+ the rest; this button is the escape hatch when a+ user wants a fresh quote right now. */}+ {editingAsset && (+ <button+ type="button"+ onClick={() => refreshPriceMutation.mutate(editingAsset.id)}+ disabled={refreshPriceMutation.isPending}+ title={t('assets.refreshPrice')}+ className="p-1.5 rounded-md text-muted-foreground hover:text-primary hover:bg-primary/10 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"+ >+ <RefreshCw+ size={14}+ className={refreshPriceMutation.isPending ? 'animate-spin' : ''}+ />+ </button>+ )}+ </div>+ </div>+ </div>+ )}++ <div className="space-y-2">+ <Label>{t('assets.quantity')}</Label>+ <Input+ type="number"+ step="any"+ min="0"+ value={formUnits}+ onChange={e => setFormUnits(e.target.value)}+ placeholder="10"+ />+ </div>++ {selectedQuote && formUnits && parseFloat(formUnits) > 0 && (+ <div className="flex items-center justify-between p-3 rounded-lg border border-primary/30 bg-primary/10">+ <span className="text-xs font-medium text-primary/80">+ {t('assets.currentValue')}+ </span>+ <span className="text-lg font-bold tabular-nums text-primary">+ {formatCurrency(+ selectedQuote.price * parseFloat(formUnits),+ selectedQuote.currency,+ locale,+ )}+ </span>+ </div>+ )}++ {quoteLoading && (+ <div className="text-xs text-muted-foreground">{t('common.loading')}</div>+ )}+ </div>+ )}+{/* Growth Rule Settings */}{formMethod === 'growth_rule' && (<div className="space-y-3 p-3.5 rounded-xl border border-primary/20 bg-primary/5">@@ -847,7 +1220,15 @@ export default function AssetsPage() {</Button><ButtononClick={handleSave}- disabled={!formName || createMutation.isPending || updateMutation.isPending}+ disabled={+ !formName+ || createMutation.isPending+ || updateMutation.isPending+ // Market-price guard: must have a resolved ticker + quantity.+ || (formMethod === 'market_price'+ && !editingAsset+ && (!selectedQuote || !formUnits || parseFloat(formUnits) <= 0))+ }>{t('common.save')}</Button>@@ -1287,10 +1668,10 @@ function AssetDetail({ assetId, currency, locale: loc, purchasePrice, purchaseDamutationFn: ({ assetId: id, ...data }: { assetId: string; amount: number; date: string }) =>assets.addValue(id, data),onSuccess: () => {- queryClient.invalidateQueries({ queryKey: ['assets'] })- queryClient.invalidateQueries({ queryKey: ['asset-values', assetId] })- queryClient.invalidateQueries({ queryKey: ['asset-trend', assetId] })- queryClient.invalidateQueries({ queryKey: ['dashboard'] })+ queryClient.refetchQueries({ queryKey: ['assets'] })+ queryClient.refetchQueries({ queryKey: ['asset-values', assetId] })+ queryClient.refetchQueries({ queryKey: ['asset-trend', assetId] })+ queryClient.refetchQueries({ queryKey: ['dashboard'] })setValueAmount('')toast.success(t('assets.valueAdded'))},@@ -1300,10 +1681,10 @@ function AssetDetail({ assetId, currency, locale: loc, purchasePrice, purchaseDaconst deleteValueMutation = useMutation({mutationFn: (valueId: string) => assets.deleteValue(valueId),onSuccess: () => {- queryClient.invalidateQueries({ queryKey: ['assets'] })- queryClient.invalidateQueries({ queryKey: ['asset-values', assetId] })- queryClient.invalidateQueries({ queryKey: ['asset-trend', assetId] })- queryClient.invalidateQueries({ queryKey: ['dashboard'] })+ queryClient.refetchQueries({ queryKey: ['assets'] })+ queryClient.refetchQueries({ queryKey: ['asset-values', assetId] })+ queryClient.refetchQueries({ queryKey: ['asset-trend', assetId] })+ queryClient.refetchQueries({ queryKey: ['dashboard'] })toast.success(t('assets.valueDeleted'))},onError: () => toast.error(t('common.error')),diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex 5708bc0f..f7b105dd 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -320,6 +320,27 @@ export interface Asset {isin: string | nullmaturity_date: string | nullgroup_id: string | null+ ticker: string | null+ ticker_exchange: string | null+ last_price: number | null+ last_price_at: string | null+ logo_url: string | null+}++export interface MarketSymbolMatch {+ symbol: string+ name: string | null+ exchange: string | null+ quote_type: string | null+}++export interface MarketSymbolQuote {+ symbol: string+ name: string | null+ exchange: string | null+ currency: string+ price: number+ quote_type: string | null}export interface AssetGroup {