BrianHicks/elm-trend/1.0.0

NOTE: this package is not compatible with Elm 0.19.1

Trend

Calculate trend lines given 2-dimensonal data.

linear : List ( Float, Float ) -> Result Error LinearFit

Plot a line through a series of points (x, y).

 linear [ (1, 1), (2, 2), (3, 3), (4, 4) ]
     --> Ok { slope = 1, intercept = 0 }

Use this in situations where the relationship between x and y is linear and has as few outliers as possible. A relationship is linear if it can be described accurately as y = x * slope + intercept. The easiest way to determine this is to look at a plot of your values. If they look roughly like a line, we're in business. But if your plot shows a curve or a random point cloud then don't trust the results of this function applied to them.

Examples of data which fit these criteria:

  • relationship of some value to time. For example, are bananas getting cheaper or more expensive as time goes on?
  • relationships where doing something more or less leads to doing something else more or less. For example, does smoking more decrease your life expectancy?

Statistically speaking, this is a least-squares regression.

type alias LinearFit =
{ slope : Float
, intercept : Float
}

A line plotted through points. Get one by passing your data to linear.

Make predictions using this and predictY and measure accuracy with goodnessOfFit.

Using Fits

goodnessOfFit : LinearFit -> List ( Float, Float ) -> Result Error Float

How good is the fit that linear generated? We can give you a confidence between 0 and 1 representing a percent confidence. Practically, we'll usually return a value between almost 0 and almost 1.

values : List (Float, Float)
values =
    [ (1, 1), (2, 2), (3, 3), (4, 4) ]


linear values
    |> Result.andThen (\fit -> goodnessOfFit fit values)
    --> Ok 1

Statistically speaking, this is the R-squared value of the linear regression.

predictY : LinearFit -> Float -> Float

Predict a value of y from a LinearFit calculated with linear and a value of x.

linear [ (1, 1), (2, 2), (3, 3), (4, 4) ]
    |> Result.map (\fit -> predictY fit 5)
    --> Ok 5

Errors

type Error
= NotEnoughData
| ResultWasNaN

Indicate that something has gone wrong in the caculation of a trend line. Specifically:

  • NotEnoughData: there was not enough data to calculate a trend. The number attached is the minimum number of points needed to calculate.
  • ResultWasNaN: this likely means you've tried to plot a point through a bunch of zeroes, or a bunch of values that are very very close to zero. If that's not the case, please open an issue.