2

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)
Najib Noer
  • 23
  • 2

2 Answers2

4

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.

Nils Gudat
  • 13,222
  • 3
  • 39
  • 60
  • My bad, thank you, especially for a detailed explanation. Unexpectedly, the function is only correct for the first run, I try different syntax using `select()` or `transform()`, and the error is persisted. After some inspection, I figure out that the function replaces the "qty" column of the original df every time I apply the function. I test the equivalent function on R again, it returns the correct result no matter how much I applied the function to the same df – Najib Noer Jun 10 '22 at 01:23
0

Ok, the second problem of changing original df that result in incorrect result can be solved by copy(df):

out = select(copy(df), [:qty, :price] => vwacost => :avgcost)

thus, the original df will not change and the result will consistent over time.

Najib Noer
  • 23
  • 2