Search code examples
juliastocktradingweighted-average

Weighted average cost of short-term stock trading


I'm new to programming and trying to learn Julia. I tried to compute the weighted average cost of short-term stock trading activities as I did before in R. I rewrite the code in Julia, unfortunately, it return the incorrect result in data frame format. I tried to investigate the result of each iteration step by changing return vwavg to println([volume[i], s, unitprice[i], value[i], t, vwavg[i], u]) and the output is correct. is it a problem with rounding? Really appreciate your help

# create trial dataset
df = DataFrame(qty = [3, 2, 2, -7, 4, 4, -3,-2, 4, 4, -2, -3],
                price = [100.0, 99.0, 101.0, 103.0, 95.0, 93.0, 90.0, 90.0, 93.0, 95.0, 93.0, 92.0])
# create function for weighted average cost of stock price
function vwacost(volume, unitprice)
    value = Vector{Float64}(undef, length(volume))
    vwavg = Vector{Float64}(undef, length(volume))
    for i in 1:length(volume)
        s = 0
        t = 0
        u = 0
        if volume[i]>0
            value[i] = (volume[i]*unitprice[i]) + t
            volume[i] = volume[i] + s
            vwavg[i] = value[i]/volume[i]
            u = vwavg[i]
            s = volume[i]
            t = value[i]
        else
            volume[i] = volume[i] + s
            value[i] = u * volume[i]
            s = volume[i]
            t = value[i]
            vwavg[i] = u
        end
    return vwavg
    end
end

out = transform(df, [:qty, :price] => vwacost)

Solution

  • Simple error:

        for i in 1:length(volume)
            ...
        return vwavg
        end
    

    should be:

        for i in 1:length(volume)
            ...
        end
        return vwavg
    

    You are currently returning the result after the first loop iteration, which is why your resulting vwawg vector has only one (the first) calculated entry, with all other entries being zero/whatever was in memory when you created the vwawg vector in the first place.