AI Insights

Linear Regression C#

When looking at time series data, such as a stream of prices, it can often be useful to establish a general trend and represent this with a single number. This can be achieved using a linear regression calculation.

Take this series of prices:
4.8, 4.8, 4.5, 3.9, 4.4, 3.6, 3.6, 2.9, 3.5, 3.0, 2.5, 2.2, 2.6, 2.1, 2.2

If you plot on an Excel graph and add a linear trend line, you should get something like this:

We can do the same thing in code:

  1. using System;
  2. class Regression
  3. {
  4.     static void Main(string[] args)
  5.     {
  6.         double[] values = { 4.8, 4.8, 4.5, 3.9, 4.4, 3.6, 3.6, 2.9, 3.5, 3.0, 2.5, 2.2, 2.6, 2.1, 2.2 };
  7.         double xAvg = 0;
  8.         double yAvg = 0;
  9.         for (int x = 0; x < values.Length; x++)
  10.         {
  11.             xAvg += x;
  12.             yAvg += values[x];
  13.         }
  14.         xAvg = xAvg / values.Length;
  15.         yAvg = yAvg / values.Length;
  16.         double v1 = 0;
  17.         double v2 = 0;
  18.         for (int x = 0; x < values.Length; x++)
  19.         {
  20.             v1 += (x – xAvg) * (values[x] – yAvg);
  21.             v2 += Math.Pow(x – xAvg, 2);
  22.         }
  23.         double a = v1 / v2;
  24.         double b = yAvg – a * xAvg;
  25.         Console.WriteLine(“y = ax + b”);
  26.         Console.WriteLine(“a = {0}, the slope of the trend line.”, Math.Round(a, 2));
  27.         Console.WriteLine(“b = {0}, the intercept of the trend line.”, Math.Round(b, 2));
  28.         Console.ReadLine();
  29.     }
  30. }

Now you have the slope of the trend line, this can be used as an input for neural networks analysing time series data.

For a complete explanation of linear regression see Wikipedia.

Contact us if you would like to learn more about using AI and machine learning in your business.

Or, follow us on Twitter for more updates like this.


« »

Talk to an expert

Book a call with one of our AI strategists now!

CONTACT US