Created
January 23, 2019 21:42
-
-
Save kurtbrose/ac2c4ffb451f785e785c1dbb01635550 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ''' | |
| line interpolation class for doing a linear regression | |
| ''' | |
| import numpy as np | |
| import pandas | |
| import attr | |
| @attr.s | |
| class Line(object): | |
| ''' | |
| I can't hold all this math in my head | |
| ''' | |
| m, b = attr.ib(), attr.ib() | |
| @classmethod | |
| def from_time_indexed_series(cls, s): | |
| 'pandas.Series whose index are timestamps' | |
| x = s.index.to_series().astype('int64') | |
| m, b = np.polyfit(x, s, 1) # degree 1 polynomial aka line | |
| return cls(m, b) | |
| def eval_at(self, x): | |
| return self.m * x + self.b | |
| def zero(self): | |
| 'find x such that y=0' | |
| # x * m + b = 0 | |
| # x * m = -b | |
| # x = -b/m | |
| return - self.b / self.m | |
| def plot(self, over, **kw): | |
| ''' | |
| plot the line such that it overlaps with over series | |
| ''' | |
| ns_ix = s.index.astype('int64') | |
| return pandas.Series({ | |
| over.index[0]: self.eval_at(ns_ix[0]), | |
| over.index[-1]: self.eval_at(ns_ix[-1]) | |
| }).plot(**kw) | |
| def intersect(self, other): | |
| 'find intersection with other line' | |
| assert isinstance(other, Line) | |
| # for the mathematically challenged like me: | |
| # x * self.m + self.b = x * other.m + other.b | |
| # x * (self.m - other.m) = other.b - self.b | |
| # x = (other.b - self.b) / (self.m - other.m) | |
| return pandas.Timestamp((other.b - self.b) / (self.m - other.m)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment