Excel BI - PowerQuery Challenge 250

excel-challenges
power-query
Calculate Finish Stock and Starting Stock.
Published

March 24, 2026

Illustration for Excel BI - PowerQuery Challenge 250

Challenge Description

Calculate Finish Stock and Starting Stock.

Solutions

library(tidyverse)
library(readxl)

path = "Power Query/PQ_Challenge_250.xlsx"
input = read_excel(path, range = "A1:E9")
test  = read_excel(path, range = "A14:F22")

result  = input %>%
  group_by(Product) %>%
  mutate(`Finish Stock` = cumsum(ifelse(row_number() == 1, `Starting Stock`, 0) + `In Stock` - `Out Stock`),
         `Starting Stock` = ifelse(row_number() == 1, `Starting Stock`, lag(`Finish Stock`)))

all.equal(result, test, check.attributes = FALSE)
#> [1] TRUE
  • Logic:

    • Reads the workbook range needed for the challenge

    • Aggregates or ranks values at the relevant grouping level

    • Builds helper columns that drive the final output

  • Strengths:

    • The R solution stays close to the workbook logic and keeps the transformation compact.
  • Areas for Improvement:

    • The code assumes the workbook layout and selected ranges remain stable.
  • Gem:

    • The best part of the solution is choosing the right intermediate shape before formatting the final output.
import pandas as pd

path = "PQ_Challenge_250.xlsx"
input = pd.read_excel(path, usecols="A:E", nrows=9)
test = pd.read_excel(path, usecols="A:F", skiprows=13, nrows=9)

def update_stocks(df):
    df["Finish Stock"] = df["Starting Stock"].where(df.index == df.index[0], 0) + df["In Stock"] - df["Out Stock"]
    df["Finish Stock"] = df["Finish Stock"].cumsum()
    df["Starting Stock"] = df["Starting Stock"].where(df.index == df.index[0], df["Finish Stock"].shift())
    return df

result = input.groupby("Product", group_keys=False).apply(update_stocks)
result = result[["Product", "Quarter", "Starting Stock", "In Stock", "Out Stock", "Finish Stock"]]
result["Starting Stock"] = result["Starting Stock"].astype('int64')
result["Finish Stock"] = result["Finish Stock"].astype('int64')


print(result.equals(test)) # True
  • Logic:

    • Reads the workbook range needed for the challenge

    • Aggregates or ranks values at the relevant grouping level

  • Strengths:

    • The Python version follows the same workbook rule in a direct pandas-oriented implementation.
  • Areas for Improvement:

    • As with the R version, any workbook layout change would require small adjustments.
  • Gem:

    • The implementation stays close to the source challenge instead of adding unnecessary abstraction.

Difficulty Level

This task is moderate:

  • It combines reshaping, grouping, or parsing steps that are common in Power Query style problems.

  • The main challenge is reproducing the workbook output structure exactly.