simple-statistics / simple-statistics

simple statistics for node & browser javascript
https://simple-statistics.github.io/
ISC License
3.38k stars 224 forks source link

Linear Regression with time series data? #719

Open hbcondo opened 4 months ago

hbcondo commented 4 months ago

Hi, are there any recommendations on how to use the linearRegression method for finding the slope of a regression line for time series data? For example, the x-coordinate value would be a JavaScript Date object so how would you pass that in when the data parameters just accept an array of numbers? Any insights on this is appreciated.

tmcw commented 4 months ago

Dates in JavaScript can be cast to number by using the + operator or using .getTime(). I'd recommend casting your dates to strings, running the linear regression algorithm, and then you can cast back to dates using the date constructor with the numbers.

hbcondo commented 4 months ago

Thank you for this prompt reply; much appreciated. I passed-in the number of milliseconds returned by .getTime() into the linearRegression method but since its value is so large, the slope value retuned is too small and is expressed in scientific notation (ex. -9.483616519037679e-8). To adjust for this, I converted milliseconds to days which returned readable numbers (ex. -8.14423076923077)

I'm still reviewing how this works but wanted to report back and see if there is by chance any further guidance on using time series data with this library's linear regression function.