2

I am using TradingView and calculating moving average using

linreg(close, 20, 1)

# close: current closing price
# 20: is the lookback period
# 1: is the offset

I couldn't find a way to calculate and get their exact result in Pandas. Here is how my dataframe looks like:

db['20 Moving Average'] = db['Close'].rolling(20).mean()
db[['Date', 'Open', 'High', 'Low', 'Close', '20 Moving Average']].tail(10).reset_index(drop=True)

    Date                Open    High    Low     Close   20 Moving Average
0   2018-07-13 11:00:00 1.16311 1.16366 1.16128 1.16268 1.166573
1   2018-07-13 12:00:00 1.16268 1.16380 1.16161 1.16353 1.166384
2   2018-07-13 13:00:00 1.16349 1.16379 1.16213 1.16246 1.166088
3   2018-07-13 14:00:00 1.16247 1.16348 1.16186 1.16266 1.165766
4   2018-07-13 15:00:00 1.16267 1.16469 1.16251 1.16450 1.165579
5   2018-07-13 16:00:00 1.16455 1.16487 1.16373 1.16419 1.165408
6   2018-07-13 17:00:00 1.16418 1.16692 1.16397 1.16667 1.165388
7   2018-07-13 18:00:00 1.16667 1.16731 1.16589 1.16667 1.165350
8   2018-07-13 19:00:00 1.16668 1.16776 1.16652 1.16735 1.165357
9   2018-07-13 20:00:00 1.16734 1.16762 1.16663 1.16762 1.165394
10  2018-07-13 21:00:00 1.16762 1.16829 1.16739 1.16768 1.165459

What i am trying to do is get the 20th Linear moving average of each row. For Simple moving average, i am using the following code:

db['20 Moving Average'] = db['Close'].rolling(20).mean()

Is there a way to calculate 20 Linear Average same way i did for MA?

Thanks

EDIT: This is not a duplicate. I am trying to get last 20 days linear regression to each row.

Don Coder
  • 526
  • 5
  • 24
  • What do you mean by TradingView and Linear Average? Are these proprietary terms? – Spinor8 Jul 17 '18 at 14:53
  • sorry confusing you. TradingView is the platform i am using. I am just trying to calculate 20 day linear regression for each row, – Don Coder Jul 17 '18 at 14:57
  • There used to be a rolling linear regression in pandas but it has been removed. You can take a look at some alternatives. https://stackoverflow.com/questions/37317727/deprecated-rolling-window-option-in-ols-from-pandas-to-statsmodels – Spinor8 Jul 17 '18 at 15:08
  • 1
    Possible duplicate of [Deprecated rolling window option in OLS from Pandas to Statsmodels](https://stackoverflow.com/questions/37317727/deprecated-rolling-window-option-in-ols-from-pandas-to-statsmodels) – Spinor8 Jul 17 '18 at 15:09
  • why do you say they're different? Can we see the output from tradingview? – Yuca Jul 17 '18 at 15:22
  • @DonCoder is this very different from a 20-day `AR(20)` model? Statsmodels [offers an implementation](http://www.statsmodels.org/dev/generated/statsmodels.tsa.ar_model.AR.html#statsmodels.tsa.ar_model.AR). Once you fix the constant term to zero, effectively you'd end up with a linear regression over past terms. – Nelewout Jul 17 '18 at 20:33

0 Answers0