Power Pivot and Closing Price - dax

I am trying to use power pivot to analyze a stock portfolio at any point in time.
The data model is:
transactions table with buy and sell transactions
historical_prices table with the closing price of each stock
security_lookup table with the symbol and other information about the stock (whether it’s a mutual fund, industry, large cap, etc.).
One to many relationships link the symbol column in security_lookup to the transactions and historical_prices tables.
I am able to get the cost basis to work correctly by doing sumx(transactions, quantity*price). However, I’m not able to get the current value of my holdings. I have a measure called “Current Price” which finds the most recent closing price by
Current Price :=
CALCULATE (
LASTNONBLANK ( Historical_prices[close], min[close] ),
FILTER (
Historical_Prices,
Historical_prices[date] = LASTDATE ( historical_prices[date] )
)
)
However, when I try to find the current value of a security by using
Current Value = sumx(transactions,transactions[quantity]*[Current Price])
the total is not accurate. I'd appreciate suggestions on a way to find the current value of a position. Preferably using sumx or an iterator function so that the subtotals are accurate.

The problem with your Current Value measure is that you are evaluating [Current Price] within the row context of the transactions table (since SUMX is an iterator), so it's only seeing the date associated with that row instead of the last date. Or more precisely, that row's date is the last date in the measure's filter context.
The simplest solution is probably to calculate the Current Price outside of the iterator using a variable and then pass that constant in so you don't have to worry about row and filter contexts.
Current Value =
VAR CurrentPrice = [Current Price]
RETURN SUMX(transactions, transactions[quantity] * CurrentPrice)

Related

HOW TO REFERENCE A MEASURE IN A FILTER (DAX)

I have created a measure
Report_Day = MAX(DATE_LT[Date])-2
I want to create measures where they reference this measure so i can just change -2 to -1 and the rest of measures work depending on the reporting date.
when i use this measure:
Day_outlet_Txns = CALCULATE(
[outlet_Dep_Txns],
FILTER(ALL(DATE_LT),[Report_Day])
)
i get a value equal to tatal transactions in a table yet i want for transactions of that report day.
When i try something else
Day_outlet_Txns = CALCULATE(
[Issuer_Dep_Txns],
FILTER(ALL(DATE_LT), DATE_LT=[Report_Day])
)
i get an error: The expression refers to multiple columns. Multiple columns cannot be converted to a scalar value.
enter image description here

Need to filter result set in DAX Power BI

I have following simple relationship:
I have created following visuals in Power BI:
I want to show Store Name, Orders (by Salesman selected in slicer) and Total Orders in that Store (ignoring Salesman selected in slicer). I have created two very simple measure (can be seen in above visual) and used in matrix visuals. Visual is showing All stores while I want to show only those stores where Salesman X (selected salesman in slicer) have orders i.e. I don't want Store B row.
while solving, I suspected that it is due to fact that visual is not cross filtering. I used crossfilter but it made no difference. data can be seen in below image:
Please guide. Thanks in advance.
Try to change [Total Orders] to this measure, but keep [Total Orders].
IF( ISBLANK([Orders Count]), BLANK(), [Total Orders])
By Adding VALUES('Order'[Store ID]) in measure solved the problem. complete measure definition is as follows:
Total Orders = CALCULATE(
count('Order'[Order ID]),
REMOVEFILTERS(Salesman[Salesman Name]),
VALUES('Order'[Store ID]))
This issues the problem but I could not understand how? Because VALUES bring only those stores where salesman has Order. But when salesman removed from the filter context by REMOVEFILTERS, then how come VALUES bring only stores where salesman have orders?
a) You intend to utilize Store.salesmanName from Store in a slicer, meaning whatever is selected from there, you intend that selection to be applied on Order to give you the Order.StoreName. So when X is selected only A and C are returned.
b) Once that selection happens, you intend DAX to return the total count of each Order.StoreName whether it has a corresponding Store.salesmanID in Order.salesmanID or not. In other words, in this layer of the analysis, you want the previous selection to remain applied in the outer loop but to be ignored in the inner loop.
To be able to do that, you can do this,
totalCount =
VAR _store =
MAX ( 'Order'[storeID] ) //what is the max store ID
VAR _count =
CALCULATE (
COUNT ( 'Order'[SalesmanId] ),
FILTER ( ALL ( 'Order' ), 'Order'[storeID] = _store ) //remove any filters and apply the value from above explicitly in the filter
)
RETURN
_count

Power BI DAX measure: Count occurences of a value in a column considering the filter context of the visual

I want to count the occurrences of values in a column. In my case the value I want to count is TRUE().
Lets say my table is called Table and has two columns:
boolean value
TRUE() A
FALSE() B
TRUE() A
TRUE() B
All solutions I found so far are like this:
count_true = COUNTROWS(FILTER(Table, Table[boolean] = TRUE()))
The problem is that I still want the visual (card), that displays the measure, to consider the filters (coming from the slicers) to reduce the table. So if I have a slicer that is set to value = A, the card with the count_true measure should show 2 and not 3.
As far as I understand the FILTER function always overwrites the visuals filter context.
To further explain my intent: At an earlier point the TRUE/FALSE column had the values 1/0 and I could achieve my goal by just using the SUM function that does not specify a filter context and just acts within the visuals filter context.
I think the DAX you gave should work as long as it's a measure, not a calculated column. (Calculated columns cannot read filter context from the report.)
When evaluating the measure,
count_true = COUNTROWS ( FILTER ( Table, Table[boolean] = TRUE() ) )
the first argument inside FILTER is not necessarily the full table but that table already filtered by the local filter context (including report/page/visual filters along with slicer selections and local context from e.g. rows/column a matrix visual).
So if you select Value = "A" via slicer, then the table in FILTER is already filtered to only include "A" values.
I do not know for sure if this will fix your problem but it is more efficient dax in my opinion:
count_true = CALCULATE(COUNTROWS(Table), Table[boolean])
If you still have the issue after changing your measure to use this format, you may have an underlying issue with the model. There is also the function KEEPFILTERS that may apply here but I think using KEEPFILTERS is overcomplicating your case.

DAX formula to subtract columns

I am trying to calculate month over month difference but it makes data negative.
I created a measure, but it makes source data negative.
CALCULATE (
COUNTA ( SOURCE_DATA[COLUMN] ),
FILTER ( SOURCE_DATA, SOURCE_DATA[YYYYMM] = "201906" )
)
- (
CALCULATE (
COUNTA ( SOURCE_DATA[COLUMN] ),
FILTER ( SOURCE_DATA, SOURCE_DATA[YYYYMM] = "201905" )
)
)
The outcome is correct, but it changes data in previous month to negative.
This is due to the filter context and the way you've written the measure.
Look at the visual table. For the field corresponding to Column = 201905 and row = GA you get -16 813. This is because the context of the visual table tells CALCULATE to COUNTA(SOURCE_DATA[Column]) only when MtM = GA and Columns = 201905. However, adding the FILTER you also tell CALCULATE to keep these criteria AND also make sure that SOURCE_DATA[Column] = 201906 in the first calculate and 201905 in the second one.
This results in CALCULATE looking for rows where Column is both 201905 and 201906 at the same time. Or in other words you generate a venn diagram with no overlapping fields. Therefore the first calculate evaluates to 0 and the second to 16 813, so that the measure is actually evaluating 0-16813 = -16 813.
Since you didn't post any description of your data model I can inly guess what it looks like. However, since you're filtering on the SOURCE_DATA table I guess you don't use a Calendar table. This you should do! Have a calendar with a 1:* (1-to-many) relationship with the SOURCE_DATA and do filtering on the calendar. In addition you can have dynamically calculated day/week/month/year offsets so that you can create measures which don't have to be updated when there's a new month.
I think this video can be helpful: sqlbi videolecture
Also, have a look at this article: sqlbi filter in calculate

how to make sub total and grand total blank using DAX in tabular model?

12 Month Qty:=CALCULATE (
[Qty],
DATESINPERIOD (
Calendar[Date] ,
MAX(Calendar[Date]),
-12, Month
)
)
currently i have that formula for my measurement.
However i would like to make all sub totals and grad totals to be blank. Therefore i would need to put ISFILTERED function properly. i wrapped formula with if(ISFILTERED()) and it did not work well. So how can i implement ISFILTERED function correctly? or if I have to use different formula what formula should i use for this situation?
Based on your comments on the original question:
ISFILTERED() has to take a column as its argument, not a measure. ISFILTERED() will tell you if a filter has been applied (via a pivot table row, column, filter, or slicer) to a specific column in your model. Thus you can use it to suppress evaluation of a measure at certain levels of the hierarchy.
Say you have a measure that you want to display as a BLANK when at the subcategory level of a hierarchy that goes Category>SubCategory>Item:
IF(
ISFILTERED(<table>[SubCategory])
,BLANK()
,[Measure]
)
This would return a blank anywhere that [SubCategory] column has a filter applied.
Edit for comment:
Whichever level of the hierarchy you want to blank is the column to reference in ISFILTERED().
I'll typically use this pattern with a date hierarchy to display different levels of aggregation, and I tend to prefer HASONEVALUE() as my test. I'll apply a series of these tests in a SWITCH() function. SWITCH() is merely syntactic sugar for nested IF()s - you can look it up if you need a reference.
Thus:
MyConditionalMeasure:=
SWITCH( TRUE()
,HASONEVALUE(DimDate[Date]
// This means we're at the date level of the hierarchy
,[BaseMeasure] // The measure to evaluate at that first level
,HASONEVALUE(DimDate[Month])
// This is true for a month or a date only, but we've
// already captured the date possibility above
,[Month-appropriate Aggregation of BaseMeasure]
,HASONEVALUE(DimDate[Year])
// Again, true for a single date or a single month, but
// we've already covered those, so the year level is all
// that's left
,[Year-appropriate Aggregation of BaseMeasure]
,BLANK() // The last argument is taken as a final ELSE
// condition, capturing anything we didn't cover above,
// which would include the grand total - this will blank the
// grand total, or e.g. DimDate[Decade] since that is a
// coarser granularity than we covered with our tests above

Resources