Forum Discussion

StockTrader's avatar
StockTrader
Regular Visitor
3 years ago
Solved

Need Help with LIFO Stock Profit/Loss Calculation

Hi, I am new to DAX and need some help calculating LIFO-based method for stock trade P&L.   I'd appreciate any hints to fix the code. Few things to point out:   1) I am relying on Table2 for LIFO...
  • StockTrader's avatar
    3 years ago

    In case someone else needs this, here is the solution:

     

    Add one column, LIFOTEMP:

     

    LIFOTemp = 
    VAR Previous_buys=Filter(Table2,[Ticker]=earlier([Ticker])&&[Transaction_Date]<=earlier([Transaction_Date])&&[Order_Action]="buy")
    VAR Previous_sales=SUMX(Filter(Table2,[Ticker]=earlier([Ticker])&&[Transaction_Date]<=earlier([Transaction_Date])&&[Order_Action]="sale"),[Quantity])
    var x=SUMX(Filter(Table2,[Ticker]=earlier([Ticker])&&[Transaction_Date]<=earlier([Transaction_Date])&&[Order_Action]="buy"),[Quantity])-Previous_sales
    VAR Previous_buys_balance=ADDCOLUMNS(ADDCOLUMNS(ADDCOLUMNS(Previous_buys,"Cumulative",SUMX(Filter(Previous_buys,[Transaction_Date]<=earlier([Transaction_Date])),[Quantity])),"Balance Left",IF([Cumulative]-x<=0,0,IF([Cumulative]-x>Table2[Quantity],Table2[Quantity],[Cumulative]-x))),"valu",[Balance Left]*Table2[value per unit])
    var nn=SUMX(Filter(Table2,[Ticker]=earlier([Ticker])&&[Transaction_Date]<=earlier([Transaction_Date])&&[Order_Action]="sale"),[Quantity]*Table2[value per unit])
    var re=IF(Table2[Order_Action]="sale", nn-SUMX(Previous_buys_balance,[valu]))
    return re

    Then this column would have the calculation:

    Cost Basis with LIFO calc = var z=filter(Table2,[Ticker]=earlier([Ticker])&&[Transaction_Date]<earlier([Transaction_Date])&&[Order_Action]="sale")
    var zzzz=MAXX(z,'Table2'[Transaction_Date])
    var ddd=MAXX(FILTER(z,'Table2'[Transaction_Date]=zzzz),Table2[LIFOTemp])
    var re=IF(Table2[Order_Action]="sale", Table2[LIFOTemp]-ddd)
    return re

     

    This is what the table would look like: