Skip to content

Instantly share code, notes, and snippets.

@cbaragao
Created April 3, 2025 00:57
Show Gist options
  • Save cbaragao/1d5ec0ecf9ea1a9557ffd075b7b4f012 to your computer and use it in GitHub Desktop.
Save cbaragao/1d5ec0ecf9ea1a9557ffd075b7b4f012 to your computer and use it in GitHub Desktop.
// Moving Average
#r "Microsoft.VisualBasic"
using Microsoft.VisualBasic;
using System.Text.RegularExpressions;
// Select a measure
var offsetMeasure = Model.SelectMeasure();
// Select an offset column
string offsetColumn = SelectColumn(Model.Tables["Dates"].Columns.Where(
col => col.Name.Contains("Offset") & (col.Name.Contains("Week") | col.Name.Contains("Month") | col.Name.Contains("Quarter"))))
.Name;
// Get the interval
string strInterval = Interaction.InputBox(
Prompt: "Enter the interval for the offset calculation:", Title: "Interval",
DefaultResponse: "3");
if (strInterval == "") {
Error("No interval provided");
return;
}
string dax = @"
VAR __CurrentOffset = SELECTEDVALUE( Dates[" + offsetColumn + @"] )
VAR __MovAvg =
CALCULATE(
[" + offsetMeasure.Name + @"],
FILTER(
ALL(Dates),
Dates[" + offsetColumn + @"] <= __CurrentOffset &&
Dates[" + offsetColumn + @"] <= __CurrentOffset -" + strInterval + @" + 1
)
)
RETURN
__MovAvg
";
// Split by CamelCase
var words = Regex.Matches(offsetColumn, @"[A-Z][a-z]*")
.Cast<Match>()
.Select(m => m.Value)
.ToList();
// Initialize variable
string period = "";
// Get the middle part (e.g., "Year", "Day", "Month")
if (words.Count == 3) {
period = words[1];
}
// Build measure name
string measureName =
strInterval + " " + period + " MA - " + offsetMeasure.Name;
// Add the measure
Model.Tables["1M"].AddMeasure(measureName, dax, "TI\\Moving Averages").FormatDax();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment