March 31 - April 2, 2025, in Las Vegas, Nevada. Use code MSCUST for a $150 discount! Early bird discount ends December 31.
Register NowBe one of the first to start using Fabric Databases. View on-demand sessions with database experts and the Microsoft product team to learn just how easy it is to get started. Watch now
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 excel calculation: COvuG.png (888×312) (imgur.com)
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 (Aj2ZB.png (1270×290) (imgur.com)). 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 ($)] )
)
@AZFinserv
Can you share it with a sample pbix file, so we can test with it, there are too many steps to follow just by looking at the formula.
Paul
March 31 - April 2, 2025, in Las Vegas, Nevada. Use code MSCUST for a $150 discount!
Your insights matter. That’s why we created a quick survey to learn about your experience finding answers to technical questions.
Arun Ulag shares exciting details about the Microsoft Fabric Conference 2025, which will be held in Las Vegas, NV.
User | Count |
---|---|
124 | |
89 | |
84 | |
70 | |
51 |
User | Count |
---|---|
206 | |
143 | |
97 | |
79 | |
68 |