I'm attempting to calculate a stochastic index (current - min of period)/(max of period - min of period) but the calculation takes upwards of 5 minutes for 1000 records. Is there any way to optimize this or should I do calculations in VBA?
Power Query:
let
Source = Sql.Database(".\SQLEXPRESS01", "DatabaseName"),
wantedTable = Source{[Schema="dbo",Item="L_Futures_Only"]}[Data],
contractFilter = Table.StopFolding(Table.SelectRows(wantedTable, each [codeID] = "020601")),
selectedColumns = Table.SelectColumns(contractFilter,{"recordDate","comm_positions_long_all","comm_positions_short_all","contract_units","codeID"},MissingField.Ignore),
dateSorted = Table.Sort(selectedColumns, {"recordDate", Order.Descending}),
retrievedQuantity = Table.AddColumn(dateSorted, "Quantity", each Number.FromText(Text.Select([contract_units],{"0".."9","."} ) ) ),
comm_NET = Table.AddColumn(retrievedQuantity, "comm_NET", each [comm_positions_long_all] - [comm_positions_short_all]),
[COLOR=rgb(209, 72, 65)] STOCH = (tbl as table , monthsInPast as number, currentValue as number, currentDate as date) as nullable number =>
let
// tbl consists of 2 columns. Dates in column 1 and values in column 2.
wantedName = Table.ColumnNames(tbl){1},
dateInPast = Date.AddMonths(currentDate, monthsInPast),
valueList = Table.Column(Table.SelectRows(tbl, each [recordDate] <= currentDate and [recordDate] >= dateInPast), wantedName),
minValue = List.Min(valueList),
output = Number.Round( ((currentValue - minValue) / (List.Max(valueList) - minValue)) * 100, 0)
in
output,[/COLOR]
[COLOR=rgb(147, 101, 184)]netCommSelection = Table.SelectColumns(comm_NET,{"recordDate","comm_NET"})[/COLOR],
commThreeYear = Table.AddColumn(comm_NET, "Commercial 3YI", each STOCH(netCommSelection, -36, [comm_NET], [recordDate])),
commOneYear = Table.AddColumn(commThreeYear, "Commercial 1YI", each STOCH(netCommSelection, -12, [comm_NET], [recordDate]))
in
commOneYear