BAKO Blog

Predicting Stock Prices Using Machine Learning

2022-07-20

In this post we will show you how to train supervised model based on TensorFlow.js to predict stock prices. First of all our backend fetches price rates of certain stock from Tiingo API. We cleanup data by adding missing weekends running a cycle through all the days since starting date and adding friday rates to saturdays and sundays. We then save clean data in our database.

Further we prepare a TensorFlow.js model as seen in the code below. It has 3 layers, input shape in our case is 30 days, output - 1 unit to provide the change in price since last day price rate. We choose Adam optimizer and Mean Squared Error loss function for our model. Then we train the model by running with the window through the whole array of historical price rates and feeding the values to the model. Afterwards we predict a month into the future calculating each day price rate by combining the previously predicted period with historical price rates to achieve a consistent window of price rates to feed to the model.

let rates;

await (() => {
    return new Promise(resolve => {
        firebase.database().ref('data/' + version + '/' + item + '/history').once('value').then(result => {
            rates = result.val();
            resolve();
        });
    });
})();

const model = tf.sequential({
    layers: [
        tf.layers.dense({units: 64, inputShape: [window]}),
        tf.layers.dense({units: 64}),
        tf.layers.dense({units: 1}),
    ]
});
model.compile({optimizer: 'adam', loss: 'meanSquaredError'});

for (i = window; i < rates.length - 1; i++) {
    const result = await model.fit(tf.tensor(rates.slice(i - window, i)).expandDims(), tf.tensor([rates[i+1]-rates[i]]));
}

const prediction = [];

for (i = 0; i < window; i++) {
    const result = await model.predict(tf.tensor(rates.slice(rates.length - window + i, rates.length).concat(prediction)).expandDims()).data();
    i ? prediction.push(prediction[i - 1] + result[0]) : prediction.push(rates[rates.length - 1] + result[0]);
}

await (() => {
    return new Promise(resolve => {
        firebase.database().ref('data/' + version + '/' + item + '/prediction').set(prediction).then(resolve);
    });
})();

functions.logger.log('Predicted ' + item);
                    

Finally we save our prediction into our database again. You can check our daily predictions on BAKO Forecasting. If you would like to know more details about this solution make sure to contact us by the address at the bottom of the page.

Get in touch

blog@bako.co

BAKO