How to calculate SMA in Swift
SMA helps traders identify trends and make buy/sell decisions by smoothing out short-term price fluctuations.
To calculate the Simple Moving Average (SMA) in Swift based on trading data, you can use a for loop to iterate through the data and keep track of the sum of the last "n" data points, where "n" is the number of periods in the SMA. Then, divide that sum by "n" to get the average.
Here is some sample code to calculate a 10-period SMA:
let data = [3.0, 4.0, 5.0, 4.5, 4.0, 5.5, 6.0, 5.5, 5.0, 4.5]
let n = 10
var sma = 0.0
for i in 0..<n {
sma += data[i]
}
sma /= Double(n)
print(sma) // 4.75
You can also use the reduce
function to calculate the sum of the last "n" data points and then divide by "n".
let sma = data.suffix(n).reduce(0, +) / Double(n)
This is a basic example, but you can also use other functionalities like map
and filter
to pre-process the data before calculating SMA.