Videos
» pip install pandas-ta
I used talib to calculate the slope and intercept on the closing prices, then realised talib offers the full calc also. The result looks to be same as TradingView (just eyeballing).
Did the following in jupyterlab:
import pandas as pd
import numpy as np
import talib as tl
from pandas_datareader import data
%run "../../plt_setup.py"
asset = data.DataReader('^AXJO', 'yahoo', start='1/1/2015')
n = 270
(asset
.assign(linreg = tl.LINEARREG(asset.Close, n))
[['Close', 'linreg']]
.dropna()
.loc['2019-01-01':]
.plot()
);
I was soaring with this question for a very long time, as a result I made such a function, it calculates linear regression as on the TradingView function ta.linreg() in PineScript:
import numpy as np
def np_shift(array: np.ndarray, offset: int = 1, fill_value=np.nan):
result = np.empty_like(array)
if offset > 0:
result[:offset] = fill_value
result[offset:] = array[:-offset]
elif offset < 0:
result[offset:] = fill_value
result[:offset] = array[-offset:]
else:
result[:] = array
return result
def Linreg(source: np.ndarray, length: int, offset: int = 0):
size = len(source)
linear = np.zeros(size)
for i in range(length, size):
sumX = 0.0
sumY = 0.0
sumXSqr = 0.0
sumXY = 0.0
for z in range(length):
val = source[i-z]
per = z + 1.0
sumX += per
sumY += val
sumXSqr += per * per
sumXY += val * per
slope = (length * sumXY - sumX * sumY) / (length * sumXSqr - sumX * sumX)
average = sumY / length
intercept = average - slope * sumX / length + slope
linear[i] = intercept
if offset != 0:
linear = np_shift(linear, offset)
return linear
Be sure to use:
import pandas_ta as ta
And I've used it like your examples with ema, with the exception my OHLC is all lower case. Check your actual syntax: it is close or Close?
df.ta.ema(df['close'], length=14, offset=None, append=True)
When you pass the dataframe to pandas_ta it will find the close column so you do not need to specify it. "Close". (KeyError: 'Close') is caused by the column label. You will have to rename the column to 'close' from 'Close'.
import pandas_ta as ta
df[SMA 10] = df.ta.sma(10)
df[SMA 50] = df.ta.sma(50)
df[SMA 100] = df.ta.sma(100)
Alternatively, you could do it this way as well.
sma10 = df.ta.sma(10)
sma50 = df.ta.sma(50)
sma100 = df.ta.sma(100)
df = pd.concat([df, sma10, sma50, sma100], axis=1)