puzzler
puzzler

Reputation: 343

How to add a column of simple moving average of another column to a Julia data frame

I have a Julia data frame where one column is called 'close' and I want to add another column to the data frame called 'sma' which is a simple moving average of 'close'. Thanks to anyone who can help!

I noticed a problem in the code amrod. It doesn't account for the first length of SMA that doesn't have enough previous data points for a good SMA and also gives double the SMA that is asked for. I changed it to input zeros up to that point, I also changed the variable names when I was figuring out how it works.

function makeSMA(data, SMA)
    len = length(data)
    y = Vector{Float64}(len)
    for i in 1:SMA-1
        y[i] = NaN
    end
    for i in SMA:len
        y[i] = mean(data[i-(SMA-1):i])
    end
    return y
end

Upvotes: 0

Views: 1226

Answers (1)

amrods
amrods

Reputation: 2131

check this:

function ma{T <: Real}(x::Vector{T}, wind::Int)
    len = length(x)
    y = Vector{Float64}(len)
    for i in 1:len
        lo = max(1, i - wind)
        hi = min(len, i + wind)
        y[i] = mean(x[lo:hi])
    end
    return y
end

x = collect(1:100)
y = ma(x, 4)

then you can hcat(x, y).

EDIT: If you want a backwards-looking MA you can use something like

function ma{T <: Real}(x::Vector{T}, wind::Int)
    len = length(x)
    y = Vector{Float64}(len)
    for i in 1:len
        if i < wind
            y[i] = NaN
        else
            y[i] = mean(x[i - wind + 1:i])
        end
    end
    return y
end

Upvotes: 2

Related Questions