DAX Calculate Year To Date - Year to Previous Month (year change) - excel

Trying to figure out how to calculate the equivalent to YTD but up til previous month when year changes.
For example:
Date | Value
2018-10 | 100
2018-11 | 100
2018-12 | 100
2019-01 | 100
2019-02 | 100
2019-03 | 100
Results expected:
When 2019-03 is selected
YTD = 300 (accumulated from 2019-01- to 2019-03)
Previous month accumulated = 200 (accumulated from 2019-01 to 2019-02)
When 2019-01 is selected
YTD = 100
Previous month accumulated = 300 (accumulated from 2018-10 to 2018-12)
I've tried:
Value_Accum_PreviousMonth:=TOTALYTD([Value];Calendar[Date]) - [Value]
but with the change of year, it doesn't work
Any ideas?

Disclaimer - I created this solution using Power BI. The formula should transfer over to Excel/PowerPivot, but it may require some minor tweaks.
While the time intelligence functions of DAX are super useful, I seem to be drawn towards the manual approach of calculating YTD, prior year, etc. With that in mind, this is how I would solve your problem.
First, I would make a measure that is a simply sum of your Value column. Having this measure is just nice down the road; not an absolute necessity.
Total Value = SUM(Data[Value])
Next, for use to calculate YTD manually based of the prior month, we need to know two things, 1) what is the target month (i.e. the prior month) and 2) what is the year of that month.
If you are going to use those values anywhere else, I would put them into there own measure and use them here. If this is the only place they will be used, I like to use variables to calculate these kinds of values.
The first value we need is the selected (or max date in cases of no selection).
VAR SelectedDate = MAX(Data[Date])
With that date, we can calculate the TargetYear and TargetMonth. Both of them are simple IF statements to catch the January/December crossover.
VAR TargetYear = IF(MONTH(SelectedDate) = 1, YEAR(SelectedDate) - 1, YEAR(SelectedDate))
VAR TargetMonth = IF(MONTH(SelectedDate) = 1, 12, MONTH(SelectedDate) - 1)
Having all of the values we need, we write a CALCULATE statement that filters the data to the TargetYear and month is less than or equal to TargetMonth.
CALCULATE([Total Value], FILTER(ALL(Data), YEAR([Date]) = TargetYear && MONTH([Date]) <= TargetMonth))
Putting it all together looks like this.
Prior Month YTD =
VAR SelectedDate = MAX(Data[Date])
VAR TargetYear = IF(MONTH(SelectedDate) = 1, YEAR(SelectedDate) - 1, YEAR(SelectedDate))
VAR TargetMonth = IF(MONTH(SelectedDate) = 1, 12, MONTH(SelectedDate) - 1)
RETURN
CALCULATE([Total Value], FILTER(ALL(Data), YEAR([Date]) = TargetYear && MONTH([Date]) <= TargetMonth))

Related

Trying to show a full years amount based on a smaller fraction of the year's total

this is my first post.
Right now, I have a limited set of data ranging from the beginning of this financial year until now. I'm trying to show what a full year's worth of that data would look like.
For example, if the number is at 10, and the data range is from 1/07/2021 - 30/12/2021 (half the year), then the end output should be 20. Or for example, turn a 12 with 3/4 of the year date range to 16 for a full years' worth.
However, my current formula would end up with 15 (10 + "half") rather than (10 + 10)
Right now this is what I have, but I know there's something off on my logic, as the output is smaller than it should be:
D1+((364-(F1-E1))/365)*D1
where E1 is the start date and F1 is the end date, and d1 is the number for that date range
Thanks in advance
endDate - startDate will give you the number of days the data covers.
(endDate - startDate) / 365 will give you what fraction of a year the sample represents.
Let’s say this works out to be 30%, or 0.30.
annualValue * 0.30 = periodValue and therefore we know that periodValue / 0.30 = annualValue.
So there it is, the cell you want the Annual Value in should be:
= periodValue / ( ( endDate - startDate) / 365 )
I will leave it to you to replace each of the three named values in my example to be the correct cell references. I suspect that’s probably:
=D1/((F1-E1)/365) which is the same as (D1*365)/(F1-E1).
The easy way to remember this is that it’s just cross-multiplication.
periodValue / days is proportionate to annualValue / 365. Thus periodValue / days = annualValue / 365. Cross-multiply and you get periodValue * 365 = annualValue * days. Divide both sides by days and you get `annualValue = (periodValue * 365)/days.

Calculation of index returns for specific timeframe for each row using (as an option) for loop

I am not too experienced with programming, and I got stuck in a research project in the asset management field.
My Goal:
I have 2 dataframes,- one containing aside from others columns "European short date"," SP150030after", "SP1500365before" (Screenshot) and second containing column "Dates" and "S&P 1500_return"(Screenshot). For each row in the first dataframe, I want to calculate cumulative returns of S&P 1500 for 365 days before the date in column "European short date" and cumulative returns of S&P 1500 for 30 days after the date in column "European short date" and put these results in columns "SP150030after" and "SP1500365before".
These returns are to be calculated using a second Dataframe. "S&P 1500_return" column in the second data frame for each date represents "daily return of S&P 1500 market index + 1". So, for example to get cumulative returns over 1 year before 31.12.2020 in first dataframe, I would have to calculate the product of values in column "S&P 1500_return" from the second dataframe for each day present (trading day) in the dataframe 2 during the period 31.12.2019 - 30.12.2020.
What I have tried so far:
I turned "European short date" in DataFrame 1 and "Date" in Dataframe 2 to be index fields and though about approaching my goal through "for" loop. I tried to turn "European short date" to be "List" to use it to iterate through the dataframe 1, but I get the following error: "/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:18: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead".
Here is my code so far:
Main_set = pd.read_excel('...')
Main_set = pd.DataFrame(Main_set)
Main_set['European short date'] = pd.to_datetime(Main_set['European short date'], format='%d.%m.%y', errors='coerce').dt.strftime('%Y-%m-%d')
Main_set = Main_set.set_index('European short date')
Main_set.head(5)
Indexes = pd.read_excel('...')
Indexes = pd.DataFrame(Indexes)
Indexes['Date'] = pd.to_datetime(Indexes['Date'], format='%d.%m.%y', errors='coerce').dt.strftime('%Y-%m-%d')
Indexes = Indexes.set_index('Date')
SP1500DailyReturns = Indexes[['S&P 1500 SUPER COMPOSITE - PRICE INDEX']]
SP1500DailyReturns['S&P 1500_return'] = (SP1500DailyReturns['S&P 1500 SUPER COMPOSITE - PRICE INDEX'] / SP1500DailyReturns['S&P 1500 SUPER COMPOSITE - PRICE INDEX'].shift(1))
SP1500DailyReturns.to_csv('...')
Main_set['SP50030after'] = np.zeros(326)
import math
dates = Main_set['European short date'].to_list()
dates.head()
for n in dates:
Main_set['SP50030after'] = math.prod(arr)
Many thanks in advance!
In case it will be useful for someone, I solved the problem by using a for loop and dividing the problem in more steps:
for n in dates:
Date = pd.Timestamp(n)
DateB4 = Date - pd.Timedelta("365 days")
DateAfter = Date + pd.Timedelta("30 days")
ReturnsofPeriodsBackwards = SP1500DailyReturns.loc[str(DateB4) : str(Date), 'S&P 1500_return']
Main_set.loc[str(Date), 'SP500365before'] = np.prod(ReturnsofPeriodsBackwards)
ReturnsofPeriodsForward = SP1500DailyReturns.loc[str(Date) : str(DateAfter), 'S&P 1500_return']
Main_set.loc[str(Date), 'SP50030after'] = np.prod(ReturnsofPeriodsForward)

How could I bring in a simply cell of Excel a value related to the last day of a month, from a PowerPivot DataModel?

I have a Data model in Excel imported with PowerPivot with over 8 million rows and I need to bring in a simple cell the value of the Price corresponding to the last day of the month (or quarter) registered in the base data. For Example:
Power Pivot Data:
Date
Price
26/06/2019 12:00:00 a. m.
50
27/06/2019 12:00:00 a. m.
54
28/06/2019 12:00:00 a. m.
58
01/07/2019 12:00:00 a. m.
55
02/07/2019 12:00:00 a. m.
60
I want to be able to look for the date, in my case: "30/06/2019" (or the number of the month), and the returned value would be the price of the last day registered in that month, in this case: "58". Just like a Vlookup function with Approximate match (TRUE) would do.
I've tried with Cube Formulas :
*CUBEMEMBER("ThisWorkbookDataModel";"[Price].[Date].&["&TEXT(A1;"YYYY-MM-DDTHH:MM:SS")&"]")
*CUBEMEMBER("ThisWorkbookDataModel";"[Measures].[Sum of Price]")
*CUBEVALUE("ThisWorkbookDataModel";B1;B2)
But with this method, I only achieve to bring the price if I use the exact day.
You can write a measure to access the last price and then call that measure in your cube formula. Something like this:
LastPrice =
VAR CurrentDate = SELECTEDVALUE ( Price[Date] )
VAR LastDate = CALCULATE ( MAX ( Price[Date] ), Price[Date] <= CurrentDate )
RETURN
CALCULATE ( SUM ( Price[Price] ), Price[Date] = LastDate )

How can i only select the parameters corresponding to each month automatically?

I have a table that includes data from two entire years, and i need to calculate the notification rate month by month in those two years. Because of that, i want to do the calculation with the data corresponding to one month.
In the example below i want to obtain the number of times a certain velocity appears in each month, so for example: if I select 1M/s, for January of 2017 the program should return 2, and 0 for the other months.
I have obtained the result for 1 month, but i want to change the start and finish of the counter each time the month changes automatically
numero1 = 1
numero2 = 1
parametro = ActiveWorkbook.Sheets("Hoja4").Cells(4, 3)
'Velocidad
If parametro = ("Velocidad") Then
archivoConsulta = ActiveWorkbook.Sheets("Hoja4").Cells(4, 4)
**For cont1 = 4 To 32**
parametro_avi = Sheets("hoja1").Cells(cont1, 56)
If parametro_avi = archivoConsulta Then
numero1 = numero1 + 1
End If
Next cont1

How to get Budget amount from the beginning of the year through current day in Power BI

I need to calculate Projected Premium by Insurance Type.
The formula for calculation is:
Sum(Budget) - Sum(Budget thru current Day) * (1+BudgetVariance) + TotalPremium
BudgetVariance = (Premium - Budget tru current Day) / Budget tru current Day
Basically I got all variables I need (Thanks to Joe), but some of them don't calculate properly:
BudgetMTD =
VAR DaysOfMonth = MAXX(Dates, DAY(EOMONTH(Dates[Date], 0)))
VAR BudgetPerDayForMonth = SUM(BudgetData[Amount]) / DaysOfMonth
VAR DaysInMonthToToday = MAXX(Dates,
IF(Dates[Date] < TODAY(), DAY(Dates[Date]),
IF(Dates[Date] > TODAY(), 0,
DAY(TODAY())
)))
RETURN BudgetPerDayForMonth * DaysInMonthToToday
BudgetMTD should be 25,882,308 but it displays 30,148,763 (which is the total for 12 months).
Also BudgetVarianceMTD displays correctly for each month, but in a card I need it as:
(Premium - Budget tru current Day) / Budget tru current Day
Which is:
28,505,823 - 25,882,308 / 25,882,308 = 0.10136326
just a hint to get from beginning of the year to current day
DATEDIFF(month, '2017/01/01', GETDATE()) AS d

Resources