Excel BI - PowerQuery Challenge 368

excel-challenges
power-query
Calculate Net Trade Value
Published

March 24, 2026

Illustration for Excel BI - PowerQuery Challenge 368

Challenge Description

Calculate Net Trade Value

Solutions

library(tidyverse)
library(readxl)

path <- "Power Query/300-399/368/PQ_Challenge_368.xlsx"
input <- read_excel(path, range = "A1:C23")
test <- read_excel(path, range = "E1:F6")

result = input %>%
  separate_wider_delim(
    cols = Transaction_Info,
    delim = "|",
    names = c("Company", "Type", "Detail", "Time")
  ) %>%
  separate_wider_delim(
    cols = Fee_Info,
    delim = ";",
    names = c("Leverage", "Fee")
  ) %>%
  separate_wider_delim(
    cols = Detail,
    delim = "@",
    names = c("Quantity", "Price")
  ) %>%
  mutate(
    Leverage = str_extract(Leverage, "\\d+") %>% as.numeric(),
    Fee = as.numeric(str_remove(str_extract(Fee, "\\d+\\.?\\d*%"), "%")),
    Price = as.numeric(Price),
    Quantity = as.numeric(Quantity)
  ) %>%
  mutate(
    Trade_value = Price * Quantity,
    Eff_trade_value = Trade_value * Leverage,
    Fee = Eff_trade_value * Fee / 100,
    Net_trade_value = Trade_value + (Fee * if_else(Type == "BUY", -1, 1))
  ) %>%
  summarise(
    `Net Trade Value` = round(sum(Net_trade_value, na.rm = TRUE), 0),
    .by = Trader_ID
  ) %>%
  janitor::adorn_totals(where = "row")

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

    • Uses direct pattern parsing where the workbook encodes logic in text

  • 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
import numpy as np

path = "Power Query/300-399/368/PQ_Challenge_368.xlsx"
input = pd.read_excel(path, usecols="A:C", nrows=23)
test = pd.read_excel(path, usecols="E:F", nrows=5)

input = (
    input
    .assign(
        **dict(zip(
            ['Company','Type','Detail','Time'],
            input['Transaction_Info'].str.split('|', expand=True).T.values
        )),
        **dict(zip(
            ['Leverage','Fee'],
            input['Fee_Info'].str.split(';', expand=True).T.values
        ))
    )
)

qty_price = input['Detail'].str.split('@', expand=True)
input[['Quantity','Price']] = qty_price
input[['Quantity','Price']] = input[['Quantity','Price']].apply(pd.to_numeric, errors='coerce')

input['Leverage'] = input['Leverage'].str.extract(r'(\d+)').astype(float)
fee_pct = input['Fee'].str.extract(r'(\d+\.?\d*)')[0].astype(float)

trade = input['Price'] * input['Quantity']
eff_trade = trade * input['Leverage']
fee = eff_trade * fee_pct / 100

input['Net_trade_value'] = trade + fee * np.where(input['Type'].eq('BUY'), -1, 1)

result = (
    input.groupby('Trader_ID', as_index=False)['Net_trade_value']
    .sum()
    .round(0)
)

result.loc[len(result)] = ['Total', result['Net_trade_value'].sum()]
result['Net_trade_value'] = result['Net_trade_value'].astype('int64')
result.columns = test.columns

print(result.equals(test))
# 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

    • Uses direct pattern parsing where the workbook encodes logic in text

  • 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.