Trendline, Moving Average and Ratio Filters

Demonstrates how use Linear Trend, Moving Average and Ratio Filters with filter chaining, using SciChart.js, High Performance JavaScript Charts

src/drawExample.ts
import { appTheme } from "./appTheme";
import { RandomWalkGenerator } from "./RandomWalkGenerator";

import {
    EAxisAlignment,
    ECoordinateMode,
    EHorizontalAnchorPoint,
    EVerticalAnchorPoint,
    ELegendOrientation,
    ELegendPlacement,
    NumberRange,
    FastLineRenderableSeries,
    LegendModifier,
    MouseWheelZoomModifier,
    NumericAxis,
    SciChartSurface,
    XyDataSeries,
    XyLinearTrendFilter,
    XyMovingAverageFilter,
    XyRatioFilter,
    XyScaleOffsetFilter,
    ZoomExtentsModifier,
    ZoomPanModifier,
    NativeTextAnnotation,
    EWrapTo,
    EMultiLineAlignment,
} from "scichart";

const RATIO_YAXIS_ID = "RatioYAxisId";

export const drawExample = async (rootElement: string | HTMLDivElement) => {
    const { sciChartSurface, wasmContext } = await SciChartSurface.create(rootElement, {
        theme: appTheme.SciChartJsTheme,
    });

    sciChartSurface.xAxes.add(
        new NumericAxis(wasmContext, {
            axisTitle: "X Axis",
        })
    );

    sciChartSurface.yAxes.add(
        new NumericAxis(wasmContext, {
            axisAlignment: EAxisAlignment.Left,
            axisTitle: "Original Data Y Axis",
            growBy: new NumberRange(0.1, 0.1),
        })
    );

    sciChartSurface.yAxes.add(
        new NumericAxis(wasmContext, {
            axisAlignment: EAxisAlignment.Right,
            axisTitle: "Ratio Axis",
            id: RATIO_YAXIS_ID,
            growBy: new NumberRange(0.1, 0.1),
            visibleRange: new NumberRange(-20, 20),
        })
    );

    // Create an original Data Series with some X,Y data
    const data1 = new RandomWalkGenerator().Seed(420).getRandomWalkSeries(500);
    const originalDataSeries = new XyDataSeries(wasmContext, {
        xValues: data1.xValues,
        yValues: data1.yValues,
        dataSeriesName: "Original",
    });
    sciChartSurface.renderableSeries.add(
        new FastLineRenderableSeries(wasmContext, {
            strokeThickness: 3,
            stroke: appTheme.VividSkyBlue,
            dataSeries: originalDataSeries,
        })
    );

    // Compute a moving average using filters API and apply to the chart
    sciChartSurface.renderableSeries.add(
        new FastLineRenderableSeries(wasmContext, {
            stroke: appTheme.VividRed,
            strokeThickness: 3,
            dataSeries: new XyMovingAverageFilter(originalDataSeries, {
                length: 10,
                dataSeriesName: "Moving Average (10)",
            }),
        })
    );

    // Compute a moving average using filters API and apply to the chart
    sciChartSurface.renderableSeries.add(
        new FastLineRenderableSeries(wasmContext, {
            stroke: appTheme.VividOrange,
            strokeThickness: 3,
            dataSeries: new XyMovingAverageFilter(originalDataSeries, {
                length: 20,
                dataSeriesName: "Moving Average (20)",
            }),
        })
    );

    // Compute an offset of the original series
    const offsetSeries = new XyScaleOffsetFilter(originalDataSeries, {
        offset: -0.5,
        scale: 2,
        dataSeriesName: "Offset -0.5 / Scaled x2",
    });
    sciChartSurface.renderableSeries.add(
        new FastLineRenderableSeries(wasmContext, {
            stroke: appTheme.VividSkyBlue + "33",
            strokeThickness: 3,
            dataSeries: offsetSeries,
        })
    );

    // Compute a trendline
    sciChartSurface.renderableSeries.add(
        new FastLineRenderableSeries(wasmContext, {
            stroke: appTheme.MutedPurple,
            strokeDashArray: [3, 3],
            strokeThickness: 3,
            dataSeries: new XyLinearTrendFilter(originalDataSeries, { dataSeriesName: "Linear Trendline" }),
        })
    );

    // Compute a ratio between the trendline & the original series
    sciChartSurface.renderableSeries.add(
        new FastLineRenderableSeries(wasmContext, {
            strokeThickness: 3,
            stroke: appTheme.MutedRed,
            yAxisId: RATIO_YAXIS_ID,
            dataSeries: new XyRatioFilter(originalDataSeries, {
                divisorSeries: offsetSeries,
                dataSeriesName: "Ratio (Original vs. Offset)",
            }),
        })
    );

    // Add a title over the chart with information
    sciChartSurface.annotations.add(
        new NativeTextAnnotation({
            x1: 0.02,
            y1: 0.02,
            xCoordinateMode: ECoordinateMode.Relative,
            yCoordinateMode: ECoordinateMode.Relative,
            horizontalAnchorPoint: EHorizontalAnchorPoint.Left,
            verticalAnchorPoint: EVerticalAnchorPoint.Top,
            fontSize: 18,
            opacity: 0.55,
            textColor: appTheme.ForegroundColor,
            text: "SciChart.js supports dynamic transforms like Moving Averages, Trendlines, Ratios",
            wrapTo: EWrapTo.ViewRect,
            multiLineAlignment: EMultiLineAlignment.Left,
        })
    );

    // Optional: add some chartmodifiers for interaction and to show the legend
    sciChartSurface.chartModifiers.add(
        new MouseWheelZoomModifier(),
        new ZoomPanModifier({ enableZoom: true }),
        new ZoomExtentsModifier(),
        new LegendModifier({ placement: ELegendPlacement.BottomLeft, orientation: ELegendOrientation.Horizontal })
    );

    return { sciChartSurface, wasmContext };
};

Trendline, Moving Average and Ratio Filters in JavaScript

Overview

This example demonstrates how to integrate SciChart.js with a JavaScript application to create a high-performance financial chart that applies dynamic data transformations. It showcases advanced technical analysis filters including Moving Average, Linear Trendline and Ratio filters, while also configuring dual y-axes for displaying both the original and transformed data.

Technical Implementation

The chart is initialized asynchronously using SciChart.js’s native asynchronous API, where a WebAssembly context is created by calling SciChartSurface.create and loading Wasm. Data is generated using a random walk generator and then processed through several filters, including two distinct Moving Average filters with different lengths, an offset and scale filter, a Linear Trendline filter, and finally, a Ratio filter that computes the ratio between the original data series and its transformed version. The filter chaining demonstrates how multiple data transformations can be applied step-by-step as described in the Transforming Data with Filters documentation.

Features and Capabilities

The implementation includes several advanced features such as:

  • Dual y-axis configuration to clearly distinguish between original data and ratio values, following best practices outlined in the Tutorial 08 - Adding Multiple Axis guide.
  • Interactive chart modifiers like MouseWheelZoomModifier, ZoomPanModifier, ZoomExtentsModifier and a LegendModifier that enhance user interactivity. More details on these can be found in the MouseWheelZoomModifier Documentation.
  • Annotations using the NativeTextAnnotation to overlay descriptive text with relative coordinates, adding additional context to the chart.

Integration and Best Practices

The example demonstrates best practices for integrating SciChart.js into a JavaScript project. Developers can follow the step-by-step asynchronous initialization process as detailed in the Getting Started with SciChart JS guide. Furthermore, resource cleanup is handled through a destructor function that properly disposes of chart objects, ensuring efficient memory management as recommended in the Memory Best Practices | JavaScript Chart Documentation. This implementation not only highlights the usage of dynamic filter chaining and dual-axis configuration, but also shows how to optimize performance when working with WebAssembly-powered charts.