LightningChart JS TraderTime-Series Moving Average Indicator

ArticleImplementation of the Time Series Moving Average indicator with LightningChart JS Trader.

Written by a human | Updated on April 24th, 2025

Introduction to Time-Series Moving Average Indicator

The time-series moving average (TSMA), also known as Least Squares Moving Average, is a popular technical indicator used in both trading and forecasting. In financial markets, it helps traders smooth out price data and identify trends, while in time series analysis, it is used to predict future values by averaging past data. The time series moving average indicator is crucial for filtering out short-term fluctuations and highlighting the underlying trend, allowing traders and analysts to make more informed decisions.

This approach is particularly valuable in volatile markets, where price or value can swing sharply over short periods. By applying the moving average time series method, one can observe the broader direction of a market or data set, making it easier to spot trends and reversals. The significance of moving averages in time series extends beyond trading—it is also a core part of forecasting and predictive analysis in various fields like economics, meteorology, and inventory management.

Types of TSMA

Time-Series-Moving-Average-Deco

The moving average time series model is part of the larger framework of time series forecasting models, where past data points are used to predict future values. The simplest form of this model involves calculating the average of a fixed number of past values. The moving average model time series is particularly useful for capturing patterns and trends without the noise of short-term fluctuations.

In time series forecasting, the moving average model helps estimate the future behavior of data based on the assumption that future values depend, to some extent, on past values. This model is often combined with other time series models like ARIMA (AutoRegressive Integrated Moving Average) to form more sophisticated forecasting tools.

Time Series Moving Average Model vs Other Models

While the moving average time series model is effective in smoothing data, it differs from other models like the autoregressive (AR) model. In an AR model, future values are predicted based on past values and their relationships, while the moving average method in time series purely averages past data points. This makes the TSMA model simpler but potentially less responsive to rapid changes compared to more complex models.

For traders, the moving average time series analysis is often favored because of its simplicity and ease of implementation. However, the choice of model depends on the specific data being analyzed and the objectives of the analysis.

Moving Average Method in Time Series Forecasting

The time series moving average method involves taking the average of a fixed number of past data points. This moving average is recalculated for each new data point, dropping the oldest value and incorporating the most recent one. For example, in a 5-day moving average, the sum of the last five data points is divided by five to produce the current value of the moving average. This process is repeated as new data comes in, providing a constantly updated view of the trend.

The method of moving averages in time series is useful for detecting patterns over time, making it particularly suitable for markets and economic data, where past behavior often informs future movements.

Time-Series Moving Average Formula

TSMA fits a linear regression line through the past prices and uses it to predict the next value. It is more complex but offers a unique way to smooth data over time (periodCount: default number = 25).

The Time Series Moving Average (TSMA) is based on the idea of fitting a straight line through a set of data points (in this case, stock prices) over a specific period and using that line to predict future values. Let’s break it down into a simple approach:

To simplify, you can think of TSMA as taking the prices over a certain period, fitting a trend line (a straight line that best represents the data), and predicting the next value based on this trend. Here’s a simple formula you can use to calculate the slope (rate of change):

Time-Series-Moving-Average-Slope-Formula

Then, to calculate the next value (TSMA), use:

Time-Series-Moving-Average-Next-Value-Formula

Example of TSMA Calculation (5-Day):

Prices over the last 5 days: 100, 102, 104, 106, 108

Step 1: Calculate the slope:

Time-Series-Moving-Average-Slope-Formula-Example

Step 2: Predict the price for the next day (Day 6):

Time-Series-Moving-Average-Next-Value-Formula-Example

Result: The predicted price for Day 6 using the Time Series Moving Average (TSMA) is 110.

The Role of LightningChart JS Trader in Financial Analysis

Trader-JS-page

Financial analysis involves examining historical data to forecast future trends, make informed decisions, and assess risk. In this domain, applications like LightningChart JS Trader serve a critical role by providing real-time, high-performance data visualization tools that help traders and analysts better interpret complex datasets. It enables traders to track market trends using built-in indicators.

The platform’s ability to handle large datasets and real-time updates makes it essential for fast decision-making in dynamic markets. Additionally, its customization options allow users to create tailored charts and apply statistical indicators, enhancing both the precision of analysis and risk management. This tool helps streamline financial analysis and supports more informed, data-driven trading strategies.

Implementation with LightningChart JS Trader

Advanced charting platforms like LightningChart JS offer traders a range of technical indicators, including the Time Series Moving Average indicator. LightningChart JS allows traders to create interactive, high-performance charts, ensuring real-time data visualization. This platform is particularly useful for traders who rely on technical indicators such as Time Series Moving Average indicator to make quick, informed decisions.

Step 1: Get LightningChart JS Trader

To begin, you’ll need access to LightningChart JS Trader. This library provides the tools necessary to create advanced technical indicators, including the Time Series Moving Average indicator. Visit the LightningChart JS Trader page to download the required components and to review the documentation.

Step 2: Review the Interactive Example

LightningChart JS Trader includes interactive examples that demonstrate how to create custom technical indicators. Start by reviewing the documentation, focusing on how to integrate the Time Series Moving Average indicator into your chart setup. The interactive examples will guide you through the process of setting up the Time Series Moving Average indicator, from importing the necessary modules to modify the chart settings.

Step 3: Code Explanation

In this step, we will break down the code that creates the chart with the Time Series Moving Average indicator, as shown in the image, using LightningChart JS Trader. The code demonstrates how to initialize a trading chart, apply the Time Series Moving Average indicator, and customize its appearance.

Time-Series-Moving-Average-Chart

Here’s a detailed breakdown of each section:

A. Importing the Required Libraries:

   const lcjsTrader = require('@arction/lcjs-trader')
   const lcjs = require('@arction/lcjs')
   const { Themes } = lcjs
  • lcjsTrader: This library provides access to the LightningChart JS Trader functionalities, allowing you to create advanced financial charts.
  • lcjs: The main LightningChart JS library is used for general charting functionality.
  • Themes: A property within lcjs that provides access to pre-built themes. In this case, we are using the darkGold theme to style the chart.

B. Initializing the Trading Chart:

lcjsTrader.trader(TRADER_LICENSE).then(async (trader) => {
    // Create a trading chart.
    const tradingChart = trader.tradingChart({ loadFromStorage: false, colorTheme: Themes.darkGold })
  • trader(TRADER_LICENSE): Initializes the LightningChart JS Trader with the provided license key (TRADER_LICENSE). This is required to access the charting functionalities for financial data.

Note you can request a LightningChart JS Trader trial license, which is free.

  • tradingChart(): This function creates a trading chart with certain options. In this example:
  • loadFromStorage: false: This disables the loading of previously stored chart data from local storage, ensuring a fresh chart setup.
  • colorTheme: Themes.darkGold: This applies the darkGold theme to the chart which influences the background color, grid lines, and other visual elements.

C. Adding and Customizing the Indicator

    // Add a Time Series Moving Average indicator
    const tsma25 = tradingChart.indicators().addTimeSeriesMovingAverage()
    tsma25.setPeriodCount(25)
    tsma25.setLineColor('#80FFFF')
    tsma25.setLineWidth(2)
  • addTimeSeriesMovingAverage(): Adds Time Series Moving Average (TSMA) indicator. TSMA, also known as Least Squares Moving Average, is a moving average based on a linear regression line.
  • setPeriodCount(25): The number of time periods (n) used to calculate the indicator.
  • setLineColor('#80FFFF'): Changes the color of the TSMA line to light cyan for better chart visualization.
  • setLineWidth(2): Adjusts the thickness of the TSMA line to 2 pixels, making it easier to distinguish on the chart.

D. Loading Data from a CSV File

    // Reading data from a file.
    await fetch(`${document.head.baseURI}examples/assets/0000/Alphabet Inc (GOOGL).csv`).then((res) => res.text()).then((text) => {
        tradingChart.readCsvString(text, 'Alphabet Inc (GOOGL)')
    })
  • fetch(): This function retrieves a CSV file containing historical data for Alphabet Inc. (GOOGL). The CSV file includes pricing information for the company’s stock, which is plotted on the chart.
  • readCsvString(): This function reads the CSV data and interprets it as pricing data for Alphabet Inc. The second argument (‘Alphabet Inc (GOOGL)’) sets the label for the chart, as seen at the top of the chart image.

E. Setting the Currency for the Chart

    tradingChart.setCurrency('USD')
   })
  • setCurrency('USD'): This sets the currency of the chart to USD, ensuring that the pricing data is interpreted and displayed in US dollars.

Advantages and Limitations of the Time-Series Moving Average

Advantages:

  • Simplicity: The time series moving average indicator is easy to calculate and interpret, making it accessible to both novice and experienced traders.
  • Trend Identification: It effectively highlights the general direction of a market, helping traders focus on long-term trends and ignore short-term volatility.
  • Versatility: The moving average time series model can be applied to various time frames, making it adaptable to different markets and datasets.
  • Smoothing Effect: It helps remove the “noise” of short-term price movements, providing a clearer view of the underlying trend.

Limitations:

  • Lagging Nature: Like other moving average indicators, the TSMA is a lagging indicator. It only reflects past data, which means it can sometimes give delayed signals during rapid market movements.
  • Less Responsive: The moving average time series analysis method gives equal weight to all data points, making it less sensitive to recent changes compared to other methods like the Exponential Moving Average (EMA).
  • Limited Predictive Power: While useful for identifying trends, the TSMA may not always predict future reversals or price movements accurately, especially in highly volatile markets.

Conclusion

The time series moving average is a crucial tool in both technical analysis and time series forecasting. It provides traders and analysts with a method to smooth out price data and identify trends over time. This moving average time series model is widely used in markets to filter out noise and focus on the broader direction of prices. However, it is essential to be aware of its limitations, particularly its lagging nature and reduced sensitivity to recent data.

Incorporating LightningChart JS Trader can enhance the analysis process by offering real-time, high-performance visualizations, making it easier for traders to track moving averages and make informed decisions.

Key Takeaways:

  • The time series moving average helps smooth data, making it ideal for identifying trends in both trading and forecasting.
  • The moving average method in time series offers a simple yet powerful tool for analyzing historical data and predicting future movements.
  • While useful for smoothing out volatility, the time series moving average indicator can lag in fast-moving markets.
  • LightningChart JS Trader offers enhanced charting capabilities, making it easier to visualize and apply moving averages in real-time trading strategies.
Omid Ahmad

Ahmad Omid

Data Science Developer

LinkedIn icon
divider-light

Continue learning with LightningChart

Lighting

This article covers basics of Lighting in Data Visualization.

High-Performance WPF Charts : The Truth

What about manufacturers’ claims about Fastest rendering charts? There are a lot of false marketing terms used in the industry, so we are going to tell the truth, based on facts that anyone can reproduce and verify.