# Chart analysis

> Trendlines (linear, exponential, logarithmic, polynomial, power, moving average) with forecasts, technical indicators in panes, and empty-point handling.

Canonical: https://salmonui.dev/docs/data-visualization/chart-analysis

## Trendlines

`series.trendlines` adds fitted lines to a series:

```tsx
{ xField: 'x', yField: 'y', trendlines: [{ kind: 'polynomial', order: 3, forecast: { forward: 5 }, name: 'Trend' }] }
```

`kind` is `'linear'`, `'exponential'`, `'logarithmic'`, `'polynomial'`
(`order` 2 to 6), `'power'` or `'movingAverage'` (`period`); the math
lives in the internal chart engine. `forecast: { forward,
backward }` extends the line, `intercept` forces it through `(0,
intercept)`, `name` and `color` label it; each trendline gets its own
legend entry and tooltip. `markers` (`true` or marker options,
default off) draws points on the line, one per data point up to 256 on a
fitted line; `tooltip: false` leaves the line out of the tooltip and
keyboard focus (default: the series' `tooltip`).

### Live demo: Trendlines and empty points

Live demo: https://salmonui.dev/demos/data-visualization/chart-trendlines

Fit a linear, exponential, logarithmic, polynomial, power or moving-average trendline with a forecast, a forced intercept and markers, and choose how missing values are drawn.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { NumberField } from '@salmonui/inputs/number-field';
import { Select } from '@salmonui/dropdowns/select';
import { Chart } from '@salmonui/charts/chart';
import type { ChartTrendline } from '@salmonui/charts/chart';

const sales = Array.from({ length: 24 }, (_, i) => ({ month: i + 1, units: Math.round(40 + 3.2 * i + 0.08 * i * i + 9 * Math.sin(i * 1.9)) }));
// Missing readings (null) in a sensor log.
const readings = [12, 14, null, 17, 19, null, null, 18, 16, 15, null, 13].map((value, i) => ({ hour: `${8 + i}:00`, value }));

type Kind = ChartTrendline['kind'];
type Empty = 'gap' | 'zero' | 'drop' | 'average';

export default function ChartTrendlinesDemo() {
  const [kind, setKind] = useState<Kind>('polynomial');
  const [order, setOrder] = useState(2);
  const [forward, setForward] = useState(6);
  const [intercept, setIntercept] = useState(false);
  const [markers, setMarkers] = useState(false);
  const [empty, setEmpty] = useState<Empty>('gap');
  return (
    <div className="demo-stack">
      <div className="demo-toolbar">
        <label>
          Trendline
          <Select aria-label="Trendline" data={(['linear', 'exponential', 'logarithmic', 'polynomial', 'power', 'movingAverage'] as const).map((k) => ({ value: k, label: k }))} value={kind} onValueChange={(value) => value != null && setKind(value as Kind)} />
        </label>
        <label>
          Order
          <NumberField aria-label="Order" min={2} max={6} value={order} onValueChange={(next) => next != null && setOrder(next)} disabled={kind !== 'polynomial'} style={{ inlineSize: '6em' }} />
        </label>
        <label>
          Forecast forward
          <NumberField aria-label="Forecast forward" min={0} max={12} value={forward} onValueChange={(next) => next != null && setForward(next)} disabled={kind === 'movingAverage'} style={{ inlineSize: '6em' }} />
        </label>
        <Checkbox checked={intercept} onCheckedChange={(checked) => setIntercept(checked)} disabled={kind !== 'linear' && kind !== 'polynomial' && kind !== 'exponential'}>Intercept at 30</Checkbox>
        <Checkbox checked={markers} onCheckedChange={(checked) => setMarkers(checked)}>Trendline markers</Checkbox>
      </div>
      <Chart
        title="Monthly units with a trendline"
        data={sales}
        height={300}
        xAxis={{ title: 'Month' }}
        series={[
          {
            type: 'scatter',
            name: 'Units',
            xField: 'month',
            yField: 'units',
            trendlines: [
              {
                kind,
                order,
                period: 3,
                forecast: kind === 'movingAverage' ? undefined : { forward },
                intercept: intercept ? 30 : undefined,
                name: `Trend (${kind})`,
                markers,
              },
            ],
          },
        ]}
      />
      <div className="demo-toolbar">
        <label>
          Empty points
          <Select aria-label="Empty points" data={[{ value: 'gap', label: 'gap' }, { value: 'zero', label: 'zero' }, { value: 'drop', label: 'drop' }, { value: 'average', label: 'average' }]} value={empty} onValueChange={(value) => value != null && setEmpty(value as Empty)} />
        </label>
      </div>
      <Chart
        title="Sensor readings with missing values"
        data={readings}
        height={240}
        legend={false}
        series={[{ type: 'line', name: 'Reading', xField: 'hour', yField: 'value', markers: true, emptyPoints: empty }]}
      />
    </div>
  );
}
```

## Technical indicators

`indicators` computes indicators over a series, reactively (a new array is
a new layout; there is no refresh method):

```tsx
import { technicalIndicators } from '@salmonui/charts/chart/indicators';

<Chart
  data={prices}
  panes={{ rows: ['70%', '30%'] }}
  axes={[{ id: 'oscillator', direction: 'y', pane: { row: 1 }, min: 0, max: 100 }]}
  series={[{ id: 'price', type: 'candle', xField: 'date', openField: 'open', highField: 'high', lowField: 'low', closeField: 'close', volumeField: 'volume' }]}
  indicators={[
    { kind: 'sma', seriesId: 'price', period: 20 },
    { kind: 'bollinger', seriesId: 'price', period: 20, deviations: 2 },
    { kind: 'rsi', seriesId: 'price', yAxis: 'oscillator', zones: { upper: 70, lower: 30 } },
  ]}
  features={[technicalIndicators]}
/>
```

| `kind` | Options | Drawn as |
| --- | --- | --- |
| `'sma'`, `'ema'`, `'tma'` | `period` (14), `field` (`'close'`, `'open'`, `'high'`, `'low'`) | a line on the series axis |
| `'momentum'`, `'rsi'` | `period`, `zones` (RSI: 70 / 30) | a line; zones are two axis lines and a band |
| `'atr'`, `'accumulationDistribution'` | `period`; A/D reads `series.volumeField` | a line |
| `'bollinger'` | `period` (20), `deviations` (2) | a range area and the middle line |
| `'macd'` | `fastPeriod` (12), `slowPeriod` (26), `signalPeriod` (9), `display: 'line' \| 'histogram' \| 'both'` | MACD and signal lines, histogram columns |
| `'stochastic'` | `kPeriod` (14), `dPeriod` (3), `zones` (80 / 20) | %K and %D lines |

The moving averages and Bollinger bands share the price axis. Every other
kind goes to `indicator.yAxis`, usually an axis in its own pane
(`panes`, `axis.pane`, see [Chart axes](https://salmonui.dev/docs/data-visualization/chart-axes)), or to a
generated secondary axis when none is named. `name` and `color`
(a data color) label and color it; each indicator series has a legend
entry and tooltip.

## Loading

Indicators are an opt-in feature: pass `features={[technicalIndicators]}` from
`@salmonui/charts/chart/indicators`. The feature renders on the server and
the client alike; a chart without it never loads the indicator code (and
warns in development when `indicators` is set). Trendlines are part of
`@salmonui/charts/chart` itself.

### Live demo: Technical indicators

Live demo: https://salmonui.dev/demos/data-visualization/chart-indicators

Moving averages and Bollinger bands over a candle series, and RSI, momentum, ATR, accumulation distribution, MACD or stochastic in a lower pane, with zones and MACD display options.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { NumberField } from '@salmonui/inputs/number-field';
import { Select } from '@salmonui/dropdowns/select';
import { Chart } from '@salmonui/charts/chart';
import type { ChartIndicator } from '@salmonui/charts/chart';
import { technicalIndicators } from '@salmonui/charts/chart/indicators';

const prices = Array.from({ length: 90 }, (_, i) => {
  const open = 50 + 6 * Math.sin(i / 9) + i / 10 + 1.5 * Math.sin(i * 1.3);
  const close = open + 1.4 * Math.sin(i * 2.1);
  return {
    date: new Date(Date.UTC(2026, 3, 1 + i)),
    open: Math.round(open * 100) / 100,
    close: Math.round(close * 100) / 100,
    high: Math.round((Math.max(open, close) + 0.8 + (i % 3) * 0.3) * 100) / 100,
    low: Math.round((Math.min(open, close) - 0.7 - (i % 4) * 0.25) * 100) / 100,
    volume: 5000 + ((i * 1777) % 4000),
  };
});

type Overlay = 'none' | 'sma' | 'ema' | 'tma' | 'bollinger';
type Oscillator = 'rsi' | 'momentum' | 'atr' | 'accumulationDistribution' | 'macd' | 'stochastic';

export default function ChartIndicatorsDemo() {
  const [overlay, setOverlay] = useState<Overlay>('bollinger');
  const [period, setPeriod] = useState(20);
  const [oscillator, setOscillator] = useState<Oscillator>('macd');
  const [macdDisplay, setMacdDisplay] = useState<'line' | 'histogram' | 'both'>('both');
  const [zones, setZones] = useState(true);

  const indicators: ChartIndicator[] = [];
  if (overlay !== 'none') indicators.push({ kind: overlay, seriesId: 'price', period, deviations: 2, name: overlay === 'bollinger' ? 'Bollinger' : overlay.toUpperCase() });
  indicators.push({
    kind: oscillator,
    seriesId: 'price',
    yAxis: 'oscillator',
    period: 14,
    fastPeriod: 12,
    slowPeriod: 26,
    signalPeriod: 9,
    display: macdDisplay,
    kPeriod: 14,
    dPeriod: 3,
    zones,
  });

  return (
    <div className="demo-stack">
      <div className="demo-toolbar">
        <label>
          Price overlay
          <Select aria-label="Price overlay" data={[{ value: 'none', label: 'none' }, { value: 'sma', label: 'SMA' }, { value: 'ema', label: 'EMA' }, { value: 'tma', label: 'TMA' }, { value: 'bollinger', label: 'Bollinger bands' }]} value={overlay} onValueChange={(value) => value != null && setOverlay(value as Overlay)} />
        </label>
        <label>
          Period
          <NumberField aria-label="Period" min={2} max={50} value={period} onValueChange={(next) => next != null && setPeriod(next)} style={{ inlineSize: '6em' }} />
        </label>
        <label>
          Lower pane
          <Select aria-label="Lower pane" data={[{ value: 'rsi', label: 'RSI' }, { value: 'momentum', label: 'Momentum' }, { value: 'atr', label: 'ATR' }, { value: 'accumulationDistribution', label: 'Accumulation / distribution' }, { value: 'macd', label: 'MACD' }, { value: 'stochastic', label: 'Stochastic' }]} value={oscillator} onValueChange={(value) => value != null && setOscillator(value as Oscillator)} />
        </label>
        <label>
          MACD display
          <Select aria-label="MACD display" data={[{ value: 'line', label: 'line' }, { value: 'histogram', label: 'histogram' }, { value: 'both', label: 'both' }]} value={macdDisplay} onValueChange={(value) => value != null && setMacdDisplay(value as 'line' | 'histogram' | 'both')} disabled={oscillator !== 'macd'} />
        </label>
        <Checkbox checked={zones} onCheckedChange={(checked) => setZones(checked)} disabled={oscillator !== 'rsi' && oscillator !== 'stochastic' && oscillator !== 'momentum'}>Zones</Checkbox>
      </div>
      <Chart
        title="Technical indicators"
        data={prices}
        height={420}
        timeZone="UTC"
        locale="en-US"
        features={[technicalIndicators]}
        panes={{ rows: ['65%', '35%'] }}
        xAxis={{ format: 'MMMd' }}
        axes={[{ id: 'oscillator', direction: 'y', pane: { row: 1 }, title: oscillator === 'accumulationDistribution' ? 'A/D' : oscillator.toUpperCase() }]}
        series={[{ id: 'price', type: 'candle', name: 'Price', xField: 'date', openField: 'open', highField: 'high', lowField: 'low', closeField: 'close', volumeField: 'volume' }]}
        indicators={indicators}
      />
    </div>
  );
}
```

## Empty points

`series.emptyPoints` decides what a missing value does: `'gap'` (default)
breaks the line, `'zero'` plots 0, `'average'` the mean of the neighbors,
`'drop'` skips the point.

The trendlines demo above also switches `emptyPoints`. `ChartTrendline`
and `ChartIndicator` are in the [API reference](https://salmonui.dev/docs/reference/charts/chart),
`technicalIndicators` in
[`@salmonui/charts/chart/indicators`](https://salmonui.dev/docs/reference/charts/chart-indicators).
