A stock log might list four units received, three shipped, and two returned for the same item. Those movements tell you what changed. Add them to the starting count in order to see how many units were on hand before and after each transaction.

In pandas, sort the transactions by item and sequence, then use a running sum within each item. In this example, item A starts with 10 units and ends with 13. Item B has its own starting count.

Item A opens with 10 units, receives 4 to close at 14, ships 3 to close at 11, then receives 2 to close at 13.
The closing balance from one transaction becomes the opening balance for the next.Credit: MathBlog

Enter the starting counts and transactions

Each SKU is a stock-keeping identifier. The start Series gives the stock on hand before the first recorded transaction for each SKU. In the change column, receipts and returns are positive and shipments are negative. The four sample rows arrive out of sequence.

import pandas as pd

start = pd.Series({"A": 10, "B": 5})
moves = pd.DataFrame({
    "sku": ["A", "B", "A", "A"],
    "sequence": [2, 1, 3, 1],
    "change": [-3, -2, 2, 4],
})

if moves.duplicated(["sku", "sequence"]).any():
    raise ValueError("Use a unique transaction order within each SKU.")

moves = moves.sort_values(["sku", "sequence"]).reset_index(drop=True)
initial = moves["sku"].map(start)

if initial.isna().any():
    raise ValueError("Add a starting count for each SKU in the log.")

moves["closing"] = initial + moves.groupby("sku")["change"].cumsum()
moves["opening"] = moves["closing"] - moves["change"]

columns = ["sku", "sequence", "opening", "change", "closing"]
print(moves[columns].to_string(index=False))

Read the opening and closing counts

The running sum includes the current transaction, so adding it to the starting count gives the closing stock. Subtract the current change from that closing count to recover the stock immediately before the transaction.

sku  sequence  opening  change  closing
  A         1       10       4       14
  A         2       14      -3       11
  A         3       11       2       13
  B         1        5      -2        3

For A’s second transaction, the previous row closed at 14. The shipment changes the balance by −3, so this row opens at 14 and closes at 11. Item B’s first row instead starts at 5. The final balance for A also checks out directly: starting stock of 10 plus the net movement of 3 gives 13.

Check the order before using your own log

Use a sequence that reflects when the movements occurred. If you only have timestamps and two rows for one SKU share a timestamp, use a reliable transaction number to break the tie. A running balance can show a negative count if the starting stock is wrong, a receipt is missing, or a shipment was recorded out of order. Check the source records before changing the balance.

The result reflects the movements recorded in the log. Compare it with a physical count before treating it as the stock on the shelf. If your starting counts and movements sit in separate tables, see how to match two lists with pandas.

Further reading