I'm trying to program the smma (smoothed moving average) in Python. I take the formula from a pine script in tradingview.
smma = 0.0
smma := na(smma[1]) ? ta.sma(src, length) : (smma[1] * (length - 1) + src) / length
So, when there's no previous smma value, we're supposed to take the simple moving average of (src,length). The next calculations is according to (smma[1] * (length - 1) + src) / length. smmma[1] being the previous smma value.
This is my code:
def smma(src, length):
smma = 0.0
dataLength = len(src)
lookbackPeriod = dataLength - length
#first value of smma is the sma of src and length
#Convert list to dataframe
df = pd.DataFrame(src, columns = ['hl2'])
smma = df.rolling(window=length).mean()
smma = float(smma.iloc[-1])
log.info(f"First smma value = {smma}")
lookbackPeriod = dataLength - length + 1 #calculate smma for the other values
while (lookbackPeriod < dataLength):
smma = (smma * (length - 1) + float(src[lookbackPeriod])) / length
log.info(f"lookback = {lookbackPeriod} src[lookbackPeriod] = {src[lookbackPeriod]} smma = {smma}")
lookbackPeriod = lookbackPeriod + 1
return smma
The output for a period length of 5 looks like this:
[2021-11-07 12:26:21,701] First smma value = 61842.0
[2021-11-07 12:26:21,701] lookback = 196 src[lookbackPeriod] = 61817.25 smma = 61837.05
[2021-11-07 12:26:21,701] lookback = 197 src[lookbackPeriod] = 61883.5 smma = 61846.340000000004
[2021-11-07 12:26:21,701] lookback = 198 src[lookbackPeriod] = 61867.75 smma = 61850.621999999996
[2021-11-07 12:26:21,702] lookback = 199 src[lookbackPeriod] = 61838.0 smma = 61848.0976
src is in my case a list of 200 values. When I compare the value of the first smma with a sma, then it is correct compared to the value on Tradingview. The value for the final value of the smma is not correct compared to what I see on Tradingview. (I take in this case as source (high+low)/2 instead of close, but still, it doesn't show it correctly when I take that as a source in Tradingview)
Can someone spot what I'm doing wrong here?
Thanks a lot!
I've found the solution. You just need to calculate on a big enough sample size. In my case, calculating the smma for a period of 5 should not be run on 5 data points, but on a size of 200 I have the correct value. So, calculate the simple moving average on your first 5 data points and then start the smma calculation for the remaining 195 data points. The last value for the smma is the correct one which matches the value in Tradingview.