Skip to main content

A simple Python library for inventory stock calculations

Project description

Inventory Calculator

A simple, lightweight Python library for inventory stock calculations. Perfect for e-commerce, warehouse management, and inventory tracking applications.

Features

  • Low Stock Detection - Instantly check if items need reordering
  • Reorder Calculations - Smart recommendations for restocking
  • Stock Validation - Prevent negative stock and invalid transactions
  • Stock Status - Get clear status: OUT_OF_STOCK, LOW_STOCK, NORMAL, OVERSTOCKED
  • Transaction Simulation - Preview transaction effects before committing
  • Zero Dependencies - Pure Python, no external packages required

Installation

From Source (Local Development)

cd inventory-calculator
pip install -e .

From PyPI (After Publishing)

pip install inventory-calculator

Quick Start

Basic Usage

from inventory_calculator import is_low_stock, calculate_reorder_quantity

# Check if stock is low
if is_low_stock(current_quantity=5, min_stock_level=10):
    print("Stock is low!")

# Calculate reorder quantity
reorder = calculate_reorder_quantity(
    current_quantity=5,
    min_stock_level=20,
    max_stock_level=100
)
print(f"Reorder {reorder} units")

Using the StockCalculator Class

from inventory_calculator import StockCalculator

# Create calculator instance
calculator = StockCalculator(
    current_quantity=50,
    min_stock_level=10,
    max_stock_level=200,
    unit_price=25.99
)

# Check stock status
if calculator.is_low_stock():
    print("Time to reorder!")
    print(f"Order quantity: {calculator.calculate_reorder_quantity()}")

# Get detailed status
print(f"Status: {calculator.get_stock_status()}")
print(f"Stock value: ${calculator.calculate_stock_value():.2f}")
print(f"Stock level: {calculator.get_stock_percentage():.1f}%")

# Get all info as dictionary
info = calculator.to_dict()
print(info)

Transaction Validation

from inventory_calculator import validate_transaction, StockValidationError

try:
    # This will raise an error - trying to remove more than available
    validate_transaction(
        transaction_type='OUT',
        quantity=100,
        current_stock=50
    )
except StockValidationError as e:
    print(f"Transaction error: {e}")

Simulating Transactions

from inventory_calculator import StockCalculator

calculator = StockCalculator(current_quantity=50, min_stock_level=10)

# Simulate removing 45 units
result = calculator.simulate_transaction('OUT', 45)

print(f"Original: {result['original_quantity']}")
print(f"After transaction: {result['new_quantity']}")
print(f"Will be low stock: {result['will_be_low_stock']}")
print(f"Can execute: {result['can_execute']}")

API Reference

Functions

is_low_stock(current_quantity, min_stock_level)

Check if stock is at or below minimum level.

Returns: bool

calculate_reorder_quantity(current_quantity, min_stock_level, max_stock_level=None, safety_factor=1.5)

Calculate recommended reorder quantity.

Returns: int

calculate_stock_value(quantity, unit_price)

Calculate total value of stock.

Returns: float

get_stock_status(current_quantity, min_stock_level, max_stock_level=None)

Get stock status as string.

Returns: str - One of: 'OUT_OF_STOCK', 'LOW_STOCK', 'NORMAL', 'OVERSTOCKED'

validate_transaction(transaction_type, quantity, current_stock, field_name='quantity')

Validate a stock transaction.

Raises: StockValidationError if invalid

StockCalculator Class

Methods

  • is_low_stock() - Check if stock is low
  • is_out_of_stock() - Check if completely out of stock
  • is_overstocked() - Check if exceeds maximum
  • get_stock_status() - Get status string
  • calculate_reorder_quantity(safety_factor=1.5) - Calculate reorder amount
  • calculate_stock_value() - Get total stock value
  • can_fulfill_order(quantity) - Check if order can be fulfilled
  • get_stock_percentage() - Get stock as percentage of max
  • simulate_transaction(type, quantity) - Preview transaction effects
  • to_dict() - Get all data as dictionary

Real-World Examples

Django Model Integration

from django.db import models
from inventory_calculator import is_low_stock, validate_transaction, StockValidationError

class Product(models.Model):
    name = models.CharField(max_length=200)
    quantity = models.IntegerField(default=0)
    min_stock_level = models.IntegerField(default=10)

    @property
    def is_low_stock(self):
        return is_low_stock(self.quantity, self.min_stock_level)

class Transaction(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    transaction_type = models.CharField(max_length=3)  # IN or OUT
    quantity = models.IntegerField()

    def clean(self):
        try:
            validate_transaction(
                self.transaction_type,
                self.quantity,
                self.product.quantity
            )
        except StockValidationError as e:
            from django.core.exceptions import ValidationError
            raise ValidationError({'quantity': str(e)})

Flask API

from flask import Flask, jsonify
from inventory_calculator import StockCalculator

app = Flask(__name__)

@app.route('/api/products/<int:product_id>/stock-info')
def get_stock_info(product_id):
    # Get product from database
    product = get_product_from_db(product_id)

    # Use calculator
    calculator = StockCalculator(
        current_quantity=product.quantity,
        min_stock_level=product.min_stock,
        unit_price=product.price
    )

    return jsonify(calculator.to_dict())

Automated Reorder System

from inventory_calculator import StockCalculator

def check_and_create_purchase_orders():
    products = Product.objects.all()

    for product in products:
        calculator = StockCalculator(
            current_quantity=product.quantity,
            min_stock_level=product.min_stock_level,
            max_stock_level=product.max_stock_level
        )

        if calculator.is_low_stock():
            reorder_qty = calculator.calculate_reorder_quantity()

            # Create purchase order
            PurchaseOrder.objects.create(
                product=product,
                quantity=reorder_qty,
                status='PENDING'
            )

            print(f"Created PO for {product.name}: {reorder_qty} units")

Use Cases

  • E-commerce platforms - Monitor product availability
  • Warehouse management - Track inventory levels
  • POS systems - Real-time stock validation
  • Manufacturing - Raw material tracking
  • Retail - Multi-location inventory
  • Supply chain - Automated reordering

Why This Library?

This library was extracted from a production Django inventory management system to provide a reusable, framework-agnostic solution for common inventory calculations.

Benefits:

  • No framework dependencies
  • Battle-tested logic
  • Simple API
  • Well documented
  • Fully tested
  • Type hints included

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT License - see LICENSE file for details

Author

Your Name - GitHub

Changelog

1.0.0 (2024)

  • Initial release
  • Core stock calculation features
  • Transaction validation
  • Stock status detection

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

inventory_calculator-1.0.0.tar.gz (9.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

inventory_calculator-1.0.0-py3-none-any.whl (11.3 kB view details)

Uploaded Python 3

File details

Details for the file inventory_calculator-1.0.0.tar.gz.

File metadata

  • Download URL: inventory_calculator-1.0.0.tar.gz
  • Upload date:
  • Size: 9.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for inventory_calculator-1.0.0.tar.gz
Algorithm Hash digest
SHA256 069f80c91cbb332ea7d5c30ff65f2fba33ef6f0952e42639735731c9e7ccca01
MD5 2c9b8353a5c113204aa383eb762a00fb
BLAKE2b-256 e8cd88fc843861451f7fead3d45d1e4451bdd10924cd76eead8942290e149109

See more details on using hashes here.

File details

Details for the file inventory_calculator-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for inventory_calculator-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 4129ca0aa694b1559fbdb54a8b800be5510a64bcf02bc4b44608fa8234bdfc5a
MD5 b3493f227c35d0faa804b9536aceb4e3
BLAKE2b-256 f0bd8372ac67d9bc5d30bc8989e372bea09810293d1a2fd4c1f8ce4789e2f512

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page