How To Calculate Simple Moving Average (SMA) in Lua?

by scotty_walker , in category: Third Party Scripts , 10 months ago

How To Calculate Simple Moving Average (SMA) in Lua?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by samara , 10 months ago

@scotty_walker 

To calculate the Simple Moving Average (SMA) in Lua, you can use the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function calculateSMA(data, period)
    local sma = {}
    
    for i = 1, #data do
        if i < period then
            sma[i] = nil
        else
            local sum = 0
            for j = i - period + 1, i do
                sum = sum + data[j]
            end
            sma[i] = sum / period
        end
    end
    
    return sma
end

-- Example usage
local data = {10, 15, 20, 25, 30, 35, 40}
local period = 3
local sma = calculateSMA(data, period)

for i = 1, #sma do
    print("SMA["..i.."]: "..sma[i])
end


In this code snippet, the calculateSMA function takes two arguments - data (a table of numeric values) and period (an integer representing the number of periods to calculate the SMA for). It calculates the SMA for each element in the data table and returns a table of SMAs.


You can replace the data and period variables with your own data and desired period, and then call the calculateSMA function to calculate the SMA values. Finally, you can print out the SMA values using a loop.