Predict Bitcoin price with ML.net


Prerequisites

Install packages

  • Banance.net - dotnet client for Binance. We will get live time prices from this excange, but the client has more functions. For example, it can set limit orders and so on.
  • Microsoft.ML and Microsoft.ML.TimeSeries - machine learning library from Microsoft and library with timeseries prediction engine
  • Spectre.Console - helper for creating beatifull console

Binance client

First of all, let’s try binance client. You need secret and key from binance.

var client = new BinanceClient(new BinanceClientOptions()
{
    ApiCredentials = new ApiCredentials("sOtUHvYU4uwLbEENnG7Sw8LNai2gMUQgOipRp8kHAPNSTs75J3wapfvWUxXpgdCi", "BSu5xyXMrbgVuQBJYpv2IQBFUh1mJd3j9GTRMoEqK02ljm7uyu1bcuDs6rWfQdGP")
});

For the beginning, let’s consider only btc busd price. To get price, use following method

var callResult = await client.Spot.Market.GetPriceAsync("BTCBUSD");
// Make sure to check if the call was successful
if (!callResult.Success)

Train predictor

Our predictor will learn after coin price is changed, however, for the beginnig we should provide some training data to get first trained model. I gathered some data for you. Note, don’t rely on it for training other algorithms, it is just for starting our predictor to learn on reliable data. For creating prediction engine, use following code:

        var mlContext = new MLContext(seed: 0);

        IDataView baseTrainingDataView = mlContext.Data.LoadFromTextFile<CoinPrice>("trainingData.csv", hasHeader: false, separatorChar: ',');

        var trainer = mlContext.Forecasting.ForecastBySsa(
            outputColumnName: nameof(CoinPricePrediction.Score),
            inputColumnName: nameof(CoinPrice.Price),
            windowSize: 60,
            seriesLength: 60 * 60 * 24,
            trainSize: 60 * 60 * 24,
            horizon: 5,
            confidenceLevel: 0.95f,
            confidenceLowerBoundColumn: "Features",
            confidenceUpperBoundColumn: "Features");
        
        ITransformer trainedModel = trainer.Fit(baseTrainingDataView);

        return trainedModel.CreateTimeSeriesEngine<CoinPrice, CoinPricePrediction>(mlContext);

There are several parameters you should know. All parameters descriptions you can find here. I just copy the most important

  • windowSize: This is the most important parameter that you can use to tune the accuracy of the model for your scenario. Specifically, this parameter is used to define a window of time that is used by the algorithm to decompose the time series data into seasonal/periodic and noise components. Typically, you should start with the largest window size that is representative of the seasonal/periodic business cycle for your scenario. For example, if the business cycle is known to have both weekly and monthly (e.g. 30-day) seasonalities/periods and the data is collected daily, the window size in this case should be 30 to represent the largest window of time that exists in the business cycle. If the same data also exhibits annual seasonality/periods (e.g. 365-day), but the scenario in which the model will be used is not interested in annual seasonality/periods, then the window size does not need to be 365. In this sample, the product data is based on a 12 month cycle where data is collected monthly – as a result, the window size used is 12.
  • seriesLength: This parameter specifies the number of data points that are used when performing a forecast.
  • trainSize: This parameter specifies the total number of data points in the input time series, starting from the beginning. Note that, after a model is created, it can be saved and updated with new data points that are collected.
  • horizon: This parameter indicates the number of time periods to predict/forecast. In this sample, we specify 2 to indicate that the next 2 months of product units will be predicated/forecasted.

Predict coin price

Now we can use our prediction engine to predict price.

var prediction = predictor.Predict(new CoinPrice { Price = lastPrice });

In our case, we use horizon parameter value as 5, so our prediction has 5 predicted numbers for 5 next minutes. As you can see, we pass for Predict method last price, so our prediction engine should learn because observable data is changed. Now we need to store our new model, in the case we want to continue at another time. We need only one line of code.

predictor.CheckPoint(mlContext, "TrainedModel");

It saves model to file TrainedModel. Later we can load trained model to prediciton engine in the following way.

if (File.Exists("TrainedModel"))
{
    // Load the forecast engine that has been previously saved.
    ITransformer forecaster;
    using (var file = File.OpenRead("TrainedModel"))
    {
        forecaster = mlContext.Model.Load(file, out DataViewSchema schema);
    }

    // We must create a new prediction engine from the persisted model.
    return forecaster.CreateTimeSeriesEngine<CoinPrice, CoinPricePrediction>(mlContext);
}

Result

As a result, we can in our console last prices and predictions for next 5 minutes

Conclusion

Today, we learned how to predict BTC price in live time with ML.net and 100 lines of code. Moreover, this algorithm learn and improve ourself after each prediciton. You can use this code to predict any other coin prices. As always, all source code and working solution you can find here.

Buy Me A Coffee

Related Posts

Avoid reflections of mappers and let Mapster generate mappers for you

Mapster generating tool for onion application

Throw exceptions from backend to frontend with blazor

One of advantages of using same code language on both frontend and backend

How to avoid violating of SOLID principles while extending service behaviours

Step by step extending service behaviour with decorator pattern respecting SOLID

Blazor render optimization

Best practices

.Net 6 brings application state to blazor webassembly server prerender

It kills strange blinking on screen

Must have libraries for blazor

List of best nuget packages

Blazor virtualize component

Lazy loading of big lists. Rendering optimization.

Blazor grpc - comunication optimization

Smaller and faster requests to your backend from blazor wasm

Free database for your blazor app

Don't pay for the cloud

Blazor common error component

Single component for showing errors on any page and component