Forum Discussion
DAX - Stock average cost
Hey guys. I'm trying to compute some data from the stock market. The process is similar so commom inventory valuation and i've used lot's of insights from DAX PATTERNS website.
MODEL:
Model (simplified)
DATASET:
| Op. | date | stock | qty | price | balance |
| Buy | 18/09/2017 | AMZN | 3000 | 10,51 | 3000 |
| Sell | 29/11/2019 | AMZN | 500 | 37,76 | -500 |
| Buy | 02/12/2019 | AMZN | 500 | 37,5 | 500 |
| Sell | 04/12/2019 | AMZN | 500 | 37,13 | -500 |
| Buy | 06/12/2019 | AMZN | 500 | 37,38 | 500 |
| Sell | 15/01/2020 | AMZN | 75 | 41,94 | -75 |
| Sell | 15/01/2020 | AMZN | 400 | 41,94 | -400 |
| Buy | 16/01/2020 | AMZN | 400 | 42,02 | 400 |
| Buy | 16/01/2020 | AMZN | 75 | 42,1 | 75 |
| Sell | 04/03/2020 | AMZN | 3000 | 16,75 | -3000 |
DESIRED RESULT IN YELLOW:
Desired result
For instance, on 02/12/2019, my avg cost was 15.01, because of this operation (excel mode, sorry):
( (500* 37,5) + (2500*10,51) ) / 3000
**************************************
I've already computed dynamically the total stocks i own given a date, by this formula:
UnitsInStock =
IF (
MIN ( 'Date'[Date] )
<= CALCULATE ( MAX ( 'fOperation'[date] ); ALL ( 'fOperation' ) );
CALCULATE (
SUM ( 'fOperation'[balance] );
FILTER ( ALL ( 'Date'[Date] ); 'Date'[Date] <= MAX ( 'Date'[Date] ) )
)
)
****************
I want to compute dynamically the average cost too, but i'm not achieving that.
My inicial measure was :
Avg Price =
VAR FinancialAmount =
CALCULATE (
SUMX ( fOperation; fOperation[price] * fOperation[qty] );
fOperation[Op.] = "buy"
)
VAR UnitsInStock = [UnitsInStock]
RETURN
DIVIDE ( FinancialAmount; UnitsInStock )
***
But thats not correct.
For instance, on 02 / dec / 2019, i'd have, based in that measure:
Hope to find some clues here in the community.
Thanks in advance.
Cheers.
2 Replies
- AnonymousNot applicable
Hi brunofds ,
Can you explain about the calculate logic? I'm not quite understand the below formula.
( (500* 37,5) + (2500*10,51) ) / 3000
Best Regards,
Jay
Community Support Team _ Jay Wang
If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.
- PierreCA
Resolver I
Hello,
You may try that code to sort your data and compute new quantities.
Bu you gonna have to find a way to overpass the filter effect of the slicer on the calculation or the result will always be different according the dates chosen.
Good luck!VAR BuySale = Feuil2[B/S]
VAR DateEvent = Feuil2[date]
VAR StockName= Feuil2[StockName]VAR AverageValue = IF(
BuySale ="B",
Feuil2[TotalStockCost]/Feuil2[QuantiteAtEndTransaction],
CALCULATE(SUMX(Feuil2, Feuil2[TotalStockCost]/Feuil2[QuantiteAtEndTransaction]),
filter(Feuil2,MAX(Feuil2[date])<DateEven),
filter(Feuil2,Feuil2[StockName]=StockName)))
RETURN
AverageValue