1

Problem: I am trying to calculate share profit based FIFO method for Buy and Sell transactions. Here is the actual result (calculated manually in Excel) Please note this is just for only a stock, I have many other stocks in my data. Here is the image of manual calculation

My solution: First of all I created an Index column to sort the data based on date and then based on transactions - 1st Buys and then Sells (I have multiple transactions on the same date). After that I added an DateTime column to bifurcate multiple entries on same date. Based on this DateTime column, I have written a DAX query but it is not giving correct result.

Here is the screenshot of Power BI output. I have highlighted incorrect values in Yellow.

Code:

VAR myunits = ABS(Data[Quantity])
VAR Previous_buys =
    FILTER (
        Data,
        [Code] = EARLIER ( [Code] )
            && [DateTime] < EARLIER ( [DateTime] )
            && [type] = "buy"
    )
VAR Previous_sales =
    ABS(SUMX (
        FILTER (
            Data,
            [Code] = EARLIER ( [Code] )
                && [DateTime] < EARLIER ( [DateTime] )
                && [type] = "sell"
        ),
        [Quantity]
    ))
VAR Previous_buys_balance =
    ADDCOLUMNS (
        ADDCOLUMNS (
            Previous_buys,
            "Cumulative", SUMX ( FILTER ( Previous_buys, [DateTime] <= EARLIER ( [DateTime] ) ), [Quantity] )
        ),
        "Balance Left", [Quantity]
            - IF (
                [Cumulative] < Previous_sales,
                [Quantity],
                VAR previouscumulative = [Cumulative] - [Quantity]
                RETURN
                    IF ( Previous_sales > previouscumulative, Previous_sales - previouscumulative )
            )
    )
VAR CostUsed =
    ADDCOLUMNS (
        ADDCOLUMNS (
            Previous_buys_Balance,
            "MyCumulatives", SUMX (
                FILTER ( Previous_buys_balance, [DateTime] <= EARLIER ( [DateTime] ) ),
                [Balance Left]
            )
        ),
        "Balance Used", IF (
            [MyCumulatives] < myunits,
            [MyCumulatives],
            VAR previouscumulatives = [MyCumulatives] - [Balance Left]
            RETURN
                IF ( myunits > previouscumulatives, myunits - previouscumulatives )
        )
    )
RETURN
    IF (
        [type] = "sell",
        ABS([Quantity]) * [unit price ($)]
            - SUMX ( CostUsed, [Balance Used] * [unit price ($)] )
    )
Bhushan Z
  • 11
  • 2

0 Answers0