Forum Discussion

sv11's avatar
sv11
Helper I
7 years ago
Solved

Moving Average Calculation

Hi, I am trying to calculate moving Average for the below data: Could someone help me with the DAX code for this calculation?   Thanks
  • Anonymous's avatar
    Anonymous
    7 years ago

    Anonymous ,

    Yes and no. Since you are asking about 50 and 200 day moving averages, I'm going to assume you are talking about stock data.  Since stocks dont trade everyday, we cannot use simple calculations like DatesInPeriod because that will look at all the dates in the period even weekends and such. So a 50 day moving average might really be just, say, 45.  so we need to use something else besides the date.

     

    I loaded some sample S&P data into Power Query, sorted oldest to newest, and added an new Index column.  This will be what we use for our start and end parameters.  Much easier to see in the file. If it asks when you open, I just grabbed some data from yahoo. 

     

    Anyhow, with all that loaded, our table looks like:

     

    Then we can write this measure:

    50 Day Average:=
    Var __Length= 50
    Var __CurrentIndex = MAX ( FactDailyData[Index] )
    Var __PrevIndex= __CurrentIndex - __Length
    
    RETURN
     
    If (__CurrentIndex >= __Length,  //this ensures we only get an average after enough data points
    AVERAGEX(
        FILTER( 
            ALL ( FactDailyData),
            __CurrentIndex>= FactDailyData[Index] 
            && 
            __PrevIndex< FactDailyData[Index]
        ), 
        FactDailyData[Close*])
     )

    This works as is since there's only one stock/index.  If there was more would have to add in something to the filters likes __CurrentStock = FactDailyData[Stock].  Just something to keep in mind.  

     

    Not a huge fan of filtering this table, so this maybe something better as a calculated column (done in power query or dax) or a dimension table with index and stock, or something along those lines.  But this method works:

     

    Final Table:

    Here's the file:

    https://1drv.ms/x/s!Amqd8ArUSwDS0Q2NWTxxU8HI9MIT