Time Series Forecasting with TensorFlow.js

Jul 20, 2023 | Data Science

Welcome to the fascinating world of Time Series Forecasting! In this article, we will explore how to pull stock prices from online APIs and perform predictions using Long Short Term Memory (LSTM) with the TensorFlow.js framework. Stock market trends can seem like a game of chance, but with machine learning, we can leverage past data to make more informed forecasts.

Table of Contents

Project Walkthrough

This project involves four main steps:

  1. Get stocks data from online API.
  2. Compute the simple moving average for a given time window.
  3. Train the LSTM neural network.
  4. Make predictions and compare them to actual values.

Get Stocks Data

To start our journey into stock prediction, we first need to gather time series data, which is essentially a sequence of numbers indexed in time order. One excellent source for this data is the Alpha Vantage Stock API. This API provides access to 20 years’ worth of stock price data for popular companies. For a deep dive into historical price events, refer to this article.

We will focus on the adjusted closing prices, which afford greater stability against stock splits compared to standard closing prices.

Simple Moving Average

Next, we need to calculate the Simple Moving Average (SMA), a method to identify trends over time by calculating the average of values within a selected time frame. Think of SMA as checking the average score of a soccer team over the last few matches to gauge how well they are doing. Here’s how we calculate it:

function ComputeSMA(data, window_size) {
    let r_avgs = [], avg_prev = 0;
    for (let i = 0; i <= data.length - window_size; i++) {
        let curr_avg = 0.00, t = i + window_size;
        for (let k = i; k < t && k < data.length; k++) {
            curr_avg += data[k][price];
        }
        curr_avg /= window_size;
        r_avgs.push({ set: data.slice(i, i + window_size), avg: curr_avg });
        avg_prev = curr_avg;
    }
    return r_avgs;
}

The output will smooth out the fluctuations in the data, helping to visualize the trend clearly.

Training Data

To prepare our training dataset, we will utilize the weekly stock prices along with the computed SMA. With a window size of 50 weeks, our dataset will consist of features (X) and corresponding labels (Y). The data will be split into a training set (70%) and a validation set (30%) for evaluation purposes.

Train Neural Network

At this juncture, we will create a model using TensorFlow.js. The architecture utilizes a Sequential model integrated with LSTM cells for deep learning, which allows the model to learn patterns from sequential data. You can think of this model like a chef who follows a recipe multiple times to perfect a complex dish.

async function trainModel(inputs, outputs, trainingsize, window_size, n_epochs, learning_rate, n_layers, callback) {
    const input_layer_shape = window_size;
    const model = tf.sequential();
    // Add layers and compile the model...
    const hist = await model.fit(xs, ys, { batchSize: rnn_batch_size, epochs: n_epochs, callbacks: { onEpochEnd: async (epoch, log) => callback(epoch, log) }} );
    return { model: model, stats: hist };
}

As the model trains, it adjusts itself to minimize errors in predicting future prices.

Validation

After training, we'll validate our model. This involves checking how well our model's predictions match up with unseen data points from the validation set. Ideally, the predicted line should closely track the actual price line.

Prediction

With our validated model, we can now predict future stock movements. We leverage our last 50 data points to estimate the price for the next day. It’s like predicting the outcome of a football match based on the last few games played.

Why isn't my Model Performing?

If your model isn't yielding the desired outcomes, don't panic! Here are some common troubleshooting steps:

  • The model might not have encountered similar data conditions in its training phase.
  • Ensure that your price data is properly scaled; LSTMs are quite sensitive to data scale.
  • Consider adding more features, such as trading indicators, to enhance model performance.
  • Alpha Vantage API also provides fundamental data that could improve predictions.

For more insights, updates, or to collaborate on AI development projects, stay connected with fxis.ai.

Conclusion

This exploration of Time Series Forecasting illustrates the exciting possibilities with machine learning and TensorFlow.js. By seamlessly integrating data gathering, moving average calculations, and predictions, we’ve taken substantial steps toward understanding stock market dynamics.

At fxis.ai, we believe that such advancements are crucial for the future of AI, as they enable more comprehensive and effective solutions. Our team is continually exploring new methodologies to push the envelope in artificial intelligence, ensuring that our clients benefit from the latest technological innovations.

In summary, this project not only serves as an educational tool but also lays the groundwork for further explorations in financial forecasting.

Stay Informed with the Newest F(x) Insights and Blogs

Tech News and Blog Highlights, Straight to Your Inbox