> ## Documentation Index
> Fetch the complete documentation index at: https://docs.wealthyhood.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Investments screen

> How to hydrate the Wealthyhood investments screen with portfolio prices and holdings data

The Wealthyhood investments screen shows a performance chart plus high-level metrics for the investor's
primary portfolio. Use the Portfolios API endpoints documented here to fetch the price series and portfolio
holdings that drive this UI.

<Info>
  All routes require a bearer token with the `read:users` scope plus the
  `x-user-id` header so the backend can resolve the retail account.
</Info>

## Overview

The investments screen displays portfolio performance, holdings breakdown, and interactive charts. It uses 4 endpoints to build the UI.

## Data sources

<CardGroup cols={2}>
  <Card title="Get User Portfolios" icon="list" href="/api-reference/portfolio/get-user-portfolios">
    Retrieve all portfolios for the user and identify the primary portfolio.
  </Card>

  <Card title="Prices by Tenor" icon="chart-line" href="/api-reference/portfolio/prices-by-tenor">
    Get historical price data for the portfolio chart organized by tenor.
  </Card>

  <Card title="Portfolio Returns by Tenor" icon="money-bill" href="/api-reference/portfolio/get-with-returns-by-tenor">
    Get portfolio holdings with pre-calculated performance metrics (returns and upBy values) across all time periods.
  </Card>

  <Card title="Investment Products" icon="database" href="/api-reference/investment-products/investment-products">
    Get current ticker/pricing data for all investment products.
  </Card>
</CardGroup>

<Info>
  Use the **Portfolio Returns by Tenor** endpoint to display pre-calculated returns and performance metrics without client-side calculations.
</Info>

## Prerequisites

* Bearer token with `read:users` scope
* `x-user-id` header to identify the user account

## Data Flow and Component Building

### Phase 1: Initial Load

1. **Fetch User Portfolios**
   * Call `GET /portfolios` to retrieve all portfolios for the user
   * Extract the primary portfolio ID (typically the first portfolio)

### Phase 2: Main Data Fetching

Fetch these in parallel:

1. **Prices by Tenor**
   * Response includes time series data for multiple tenors:
     * `1w`, `1m`, `3m`, `6m`, `1y`, `max`
   * Each tenor contains:
     * `data`: Array of `{timestamp, value, displayIntraday}` points
     * `value`: Portfolio value in the investor's base currency
     * `displayIntraday`: Boolean indicating whether to render intraday granularity

2. **Portfolio Returns by Tenor** (recommended for performance metrics)
   * Response includes:
     * `calculatedPrice`: Current portfolio value
     * `returnsValues`: Returns ratios by tenor (e.g., `{ "1w": 0.003, "1m": 0.012, ... }`)
     * `upByValues`: Absolute gains/losses by tenor (e.g., `{ "1w": 13.50, "1m": 54.20, ... }`)
     * `holdings`: Array with `sinceBuyReturns` for each holding
   * Use this for displaying returns percentages and upBy values without client-side calculations

3. **Investment Products**
   * Response: Array of investment products with current ticker data
   * Used to enrich holdings with current prices and asset metadata
   * Ticker data is automatically included (no query parameters needed)

### Phase 3: Building UI Components

#### Component 1: Portfolio Value Display

**Data Sources**: Prices by Tenor + Portfolio Returns by Tenor

1. Extract `calculatedPrice` as the current portfolio value
2. For the selected timeframe, use:
   * Returns percentage: `returnsValues[timeframe] * 100` (e.g., `0.012 * 100 = 1.2%`)
   * UpBy value: `upByValues[timeframe]` (absolute gain/loss in currency)

**User Interaction**: When user selects a different timeframe (1W, 1M, 3M, 6M, 1Y, MAX):

* Update displayed value and returns from Returns by Tenor for that timeframe
* Update chart data from Prices by Tenor for that timeframe

#### Component 2: Performance Chart

**Data Source**: Prices by Tenor

1. Parse the selected timeframe's time series data
2. Transform data points:
   * Convert `timestamp` (milliseconds) to date objects
   * Extract `value` as the price point
   * Format dates for x-axis labels
3. Render line chart with:
   * X-axis: Dates
   * Y-axis: Portfolio value
   * Handle `displayIntraday` flag for intraday vs daily data granularity

**User Interaction**: When timeframe filter changes:

* Switch to the corresponding time series from the Prices by Tenor response
* Re-render chart with new data

#### Component 3: Holdings Breakdown

**Data Sources**: Portfolio Returns by Tenor + Investment Products

1. **Process holdings from Returns by Tenor**:
   * Each holding includes `sinceBuyReturns` (cumulative return since purchase)
   * Use `calculatedPrice` from the response as total portfolio value
   * Calculate holding value: Match holdings with investment products to get current prices, or use `quantity * asset.currentTicker.price`
   * Calculate allocation percentage: `(holdingValue / calculatedPrice) * 100`
   * Sort holdings by value (descending) or alphabetically

2. **Group holdings** (optional):
   * By Asset Class: Group by `asset.assetClassType` (if available in investment products)
   * By Asset Type: Group by `asset.isStock` vs `asset.isETF`
   * Ungrouped: Show flat list

3. **Display individual asset returns**:
   * Show `sinceBuyReturns` for each holding (convert to percentage: `sinceBuyReturns * 100`)
   * Display asset details from the `asset` object in each holding (ISIN, name, symbol)

4. **Build components**:
   * Pie Chart: Aggregate allocations by asset class or type
   * Asset List: Display individual holdings with:
     * Asset name (from Returns by Tenor or investment products)
     * Allocation percentage
     * Current value
     * Quantity held
     * Returns since buy

#### Component 4: Asset Class Filters

**Data Source**: Portfolio Returns by Tenor + Investment Products

1. Extract unique asset classes/types from holdings (using investment products data)
2. Create filter buttons/chips for each asset class
3. When filter selected:
   * Filter holdings by selected asset class
   * Update pie chart and asset list
   * Recalculate totals

## Complete Initialization Flow

```
1. Load Screen
   ↓
2. Fetch User Portfolios (GET /portfolios)
   ├─→ Empty: Show empty portfolio message (STOP)
   └─→ Has portfolios: Continue to step 3
   ↓
3. Extract primary portfolioId
   ↓
4. Parallel Fetch:
   ├─→ Prices by Tenor (GET /portfolios/{id}/prices-by-tenor)
   ├─→ Returns by Tenor (GET /portfolios/{id}/with-returns-by-tenor)
   └─→ Investment Products (GET /investment-products)
   ↓
5. Process Holdings Data:
   ├─→ Match holdings with investment products
   ├─→ Calculate holding values
   ├─→ Calculate allocations
   ├─→ Group by asset class
   └─→ Build pie chart data
   ↓
6. Process Chart Data:
   ├─→ Parse time series for default timeframe
   └─→ Render chart
   ↓
7. Render Components:
   ├─→ Portfolio value display
   ├─→ Performance chart
   ├─→ Asset class filters
   ├─→ Pie chart
   └─→ Holdings list
```

## Refresh Flow

When user pulls to refresh or returns to screen:

1. Invalidate cached data (if using caching)
2. Re-fetch in parallel:
   * Prices by Tenor
   * Returns by Tenor
   * Investment Products (if needed)
3. Update all components with new data

## Data Dependencies

* **Returns by Tenor**: Required for holdings breakdown, performance metrics, and individual asset returns
* **Prices by Tenor**: Required for chart visualization
* **Investment Products**: Optional, enhances holdings with current prices and metadata

## See also

* API Reference → Portfolios API → `GET /portfolios`
* API Reference → Portfolios API → `GET /portfolios/{id}/prices-by-tenor`
* API Reference → Portfolios API → `GET /portfolios/{id}/with-returns-by-tenor`
* API Reference → Investment Products API → `GET /investment-products`
