C# Code Math.Net

Linear Regression with Math.NET and .Net Core 3.1

I recently decided to dust off an old stock data analysis tool that I build a couple years ago and have been updating some code to use readily available tools more, as opposed to hand rolling loads of code for math that i could do easily by hand but would inevitably be buggy and need maintenance if I wrote it from scratch. Enter linear regression.Part of the goal is to detect fluctuations of a particular type so I can research particular stocks in a targeted fashion, so I need a trend line calculation. Simple regression is fine for me, so I’m aiming for the old standby from algebra, y = mx + b. This is served nicely by the MathNet.Numerics library available on NuGet.

Spin up a new console app with a clever name…something like LinearRegressionExample of course. Then add the NuGet package called MathNet.Numerics. I use .Net Core 3.1 in mine but it targets mutliple .Net Frameworks, so it should work with just about anything you throw it at.

What I need is a slope and intercept. This is calculated and returned as a Tuple by the Fit.Line method. We’ll call it thusly in the main method of the sample program.

static void Main(string[] args)
      double[] ydata = new double[] { 157.0800, 158.9865, 158.1200, 155.1100 };
      double[] xdata = new double[] { 1, 2, 3, 4 };

      Tuple<double, double> p = Fit.Line(xdata, ydata);
      double b = p.Item1; 
      double m = p.Item2; 

Nothing Fancy, I just needed a simple test and a fast proof so I could write this into a library for reuse in multiple places in my project.  This particular example gives some long decimal values but that was expected…I did after all choose some MSFT stock data from a few days in Dec 2019 just to be closer to my intended use case.


By Jim Pusateri

Software Developer and Scientist

One reply on “Linear Regression with Math.NET and .Net Core 3.1”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s