Python  

How to Find Marshall–Edgeworth Index Number using Python

Table of Contents

  • Introduction

  • What Is the Marshall–Edgeworth Index?

  • Why It Matters: A Real-World Scenario in Renewable Energy Pricing

  • Step-by-Step Calculation Method

  • Complete Python Implementation with Test Cases

  • Best Practices and Common Pitfalls

  • Conclusion

Introduction

In economics and data analysis, index numbers help us measure changes in prices, quantities, or values over time. Among the many types of index numbers, the Marshall–Edgeworth Index stands out for its balanced approach—it uses both base-period and current-period quantities as weights, offering a more realistic reflection of market dynamics than simpler indices like Laspeyres or Paasche.

This article explains how to compute the Marshall–Edgeworth Index with clarity, demonstrates its real-world relevance in the renewable energy sector, and provides a clean, tested Python implementation.

What Is the Marshall–Edgeworth Index?

The Marshall–Edgeworth Price Index compares the total cost of purchasing a basket of goods using average quantities from both the base period and the current period. It’s defined as:

qa

Where

  • p0​ = prices in the base period

  • p1​ = prices in the current period

  • q0​ = quantities in the base period

  • q1​ = quantities in the current period

This symmetric weighting reduces bias and is especially useful when consumption patterns shift significantly—like in fast-evolving markets.

Why It Matters: A Real-World Scenario in Renewable Energy Pricing

Imagine you’re an energy policy analyst tracking the cost evolution of solar panel installations across two years:

  • Base Year (2022): High demand for monocrystalline panels; polycrystalline panels are being phased out.

  • Current Year (2024): New thin-film technology enters the market; quantities shift dramatically.

Using a traditional Laspeyres index (which only uses 2022 quantities) would overstate inflation because it ignores the drop in polycrystalline usage. The Paasche index (using only 2024 quantities) might understate historical costs.

The Marshall–Edgeworth Index bridges this gap by averaging quantities from both years, giving a fairer picture of true price change in a transitioning market—critical for subsidy planning, tariff adjustments, and investment forecasting.

PlantUML Diagram

Step-by-Step Calculation Method

  1. Collect data: Prices and quantities for each item in both periods.

  2. Compute average quantity: q0​+q1​ for each item.

  3. Calculate weighted current cost: ∑p1​⋅(q0​+q1​)

  4. Calculate weighted base cost: ∑p0​⋅(q0​+q1​)

  5. Divide and multiply by 100 to get the index number.

Complete Python Implementation with Test Cases

from typing import List
import unittest

def marshall_edgeworth_index(
    base_prices: List[float],
    current_prices: List[float],
    base_quantities: List[float],
    current_quantities: List[float]
) -> float:
    """
    Calculate the Marshall–Edgeworth Price Index.
    
    Args:
        base_prices: Prices in the base period
        current_prices: Prices in the current period
        base_quantities: Quantities in the base period
        current_quantities: Quantities in the current period
        
    Returns:
        Marshall–Edgeworth Index as a float (e.g., 105.3 for 5.3% increase)
        
    Raises:
        ValueError: If input lists have mismatched lengths or non-positive values
    """
    if not (len(base_prices) == len(current_prices) == 
            len(base_quantities) == len(current_quantities)):
        raise ValueError("All input lists must have the same length.")
    
    if len(base_prices) == 0:
        raise ValueError("Input lists cannot be empty.")
    
    # Validate non-negative inputs (prices/quantities should be >= 0)
    for arr, name in [(base_prices, "base_prices"), 
                      (current_prices, "current_prices"),
                      (base_quantities, "base_quantities"),
                      (current_quantities, "current_quantities")]:
        if any(x < 0 for x in arr):
            raise ValueError(f"All values in {name} must be non-negative.")

    numerator = 0.0
    denominator = 0.0
    
    for p0, p1, q0, q1 in zip(base_prices, current_prices, base_quantities, current_quantities):
        avg_qty = q0 + q1
        numerator += p1 * avg_qty
        denominator += p0 * avg_qty

    if denominator == 0:
        raise ValueError("Denominator is zero—no valid base-period expenditure.")

    return (numerator / denominator) * 100


class TestMarshallEdgeworthIndex(unittest.TestCase):
    
    def test_basic_case(self):
        # Simple case: two goods
        base_p = [10, 20]
        curr_p = [12, 22]
        base_q = [5, 3]
        curr_q = [6, 4]
        
        result = marshall_edgeworth_index(base_p, curr_p, base_q, curr_q)
        # Numerator = 12*(5+6) + 22*(3+4) = 132 + 154 = 286
        # Denominator = 10*(5+6) + 20*(3+4) = 110 + 140 = 250
        # Index = (286 / 250) * 100 = 114.4
        self.assertAlmostEqual(result, 114.4, places=1)

    def test_no_change(self):
        prices = [5, 10]
        quantities = [2, 4]
        result = marshall_edgeworth_index(prices, prices, quantities, quantities)
        self.assertEqual(result, 100.0)

    def test_empty_input(self):
        with self.assertRaises(ValueError):
            marshall_edgeworth_index([], [], [], [])

    def test_mismatched_lengths(self):
        with self.assertRaises(ValueError):
            marshall_edgeworth_index([1], [1, 2], [1], [1])

    def test_zero_denominator(self):
        with self.assertRaises(ValueError):
            marshall_edgeworth_index([0, 0], [1, 1], [1, 1], [1, 1])


if __name__ == "__main__":
    # Example: Solar panel cost tracking
    print("=== Marshall–Edgeworth Index: Renewable Energy Example ===")
    
    # Base year (2022): Monocrystalline, Polycrystalline
    base_prices_2022 = [300, 200]        # $/panel
    base_quantities_2022 = [1000, 500]   # units installed
    
    # Current year (2024): Monocrystalline, Thin-film (polycrystalline phased out)
    current_prices_2024 = [280, 180]     # prices dropped
    current_quantities_2024 = [1200, 800]  # shift in tech adoption
    
    # Adjust polycrystalline quantity to 0 in 2024
    me_index = marshall_edgeworth_index(
        base_prices=[300, 200],
        current_prices=[280, 180],
        base_quantities=[1000, 500],
        current_quantities=[1200, 0]  # no more poly panels
    )
    
    print(f"Marshall–Edgeworth Price Index (2022 → 2024): {me_index:.2f}")
    print(f"Interpretation: Overall solar panel costs changed by {me_index - 100:.2f}%")
    
    # Run tests
    unittest.main(argv=[''], exit=False, verbosity=2)
c

Best Practices and Common Pitfalls

  • Validate inputs: Ensure all lists are the same length and contain non-negative numbers.

  • Handle zero quantities: It’s okay for q1​=0 (item discontinued), but avoid zero prices unless justified.

  • Don’t confuse with Laspeyres/Paasche: Marshall–Edgeworth uses the sum of quantities, not averages—though conceptually it’s symmetric.

  • Use for transitional markets: Ideal when consumer behavior or technology shifts rapidly (e.g., EVs, AI hardware, green tech).

Conclusion

The Marshall–Edgeworth Index isn’t just a textbook formula—it’s a practical tool for analysts navigating real-world economic shifts. By incorporating data from both time periods, it delivers a balanced, less biased measure of price change, especially valuable in dynamic sectors like renewable energy. With the provided Python function, you can compute it reliably, test edge cases, and apply it confidently to your own datasets. Whether you're evaluating policy impacts or tracking supply chain costs, mastering this index adds precision to your economic insights.