Metadata-Version: 2.4
Name: zakat-calculator
Version: 0.0.1
Summary: Zakat calculator
Project-URL: Homepage, https://github.com/qcri/zakat-calculator
Project-URL: Issues, https://github.com/qcri/zakat-calculator/issues
Author-email: QCRI <qcri@hbku.edu.qa>
License: BSD 3-Clause License
        
        Copyright (c) 2025-2026, Qatar Computing Research Institute - HBKU.
        All rights reserved.
        
        Redistribution and use in source and binary forms, with or without
        modification, are permitted provided that the following conditions are met:
        
        1. Redistributions of source code must retain the above copyright notice, this
           list of conditions and the following disclaimer.
        
        2. Redistributions in binary form must reproduce the above copyright notice,
           this list of conditions and the following disclaimer in the documentation
           and/or other materials provided with the distribution.
        
        3. Neither the name of the copyright holder nor the names of its
           contributors may be used to endorse or promote products derived from
           this software without specific prior written permission.
        
        THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
        AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
        IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
        DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
        FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
        DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
        SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
        CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
        OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
        OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
License-File: LICENSE
Keywords: calculator,fiqh,islamic,nisab,shariah,zakah,zakat
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: BSD License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Requires-Dist: requests>=2.28
Description-Content-Type: text/markdown

# Zakat Calculator

[![CI](https://github.com/qcri/zakat-calculator/actions/workflows/ci.yml/badge.svg)](https://github.com/qcri/zakat-calculator/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/zakat-calculator)](https://pypi.org/project/zakat-calculator/)
[![License](https://img.shields.io/badge/license-BSD--3--Clause-blue)](LICENSE)
[![Python](https://img.shields.io/badge/python-3.10%2B-blue)](https://pypi.org/project/zakat-calculator/)

A Python calculator for Zakat computation.

## Supported Asset Types

- **Cash**: cash on hand and bank accounts
- **Gold & Silver**: converted to monetary value using provided prices per gram
- **Business assets**: inventory and receivables
- **Stocks**: stocks and investments
- **Agricultural produce**: irrigated (5% rate) and rain-fed (10% rate) with separate Nisab of 653 kg
- **Livestock**: camels, cattle, and sheep/goats with detailed schedules
- **Recoverable debts**: optionally included in zakatable wealth

## Supported Rules

- Nisab threshold using lower of gold (85g) or silver (595g) equivalent
- Standard 2.5% rate on cash, gold, silver, business assets, and stocks
- Debt and expense deductions before calculation
- Separate agricultural Nisab (weight-based or monetary approximation)
- Livestock schedules for camels (5+), cattle (30+), and sheep/goats (40+)

## Live Market Prices

Built-in `MarketPrices` class fetches live gold/silver prices, exchange rates, and crypto prices with a fallback chain:
1. Primary API
2. Backup API
3. Hardcoded defaults

## Installation

```bash
pip install zakat-calculator
```

Or directly from GitHub:

```bash
pip install git+https://github.com/qcri/zakat-calculator.git
```

## Quick Start

```python
from decimal import Decimal
from zakat_calculator import ZakatCalculator

calc = ZakatCalculator(
    gold_price_per_gram=Decimal("95.00"),
    silver_price_per_gram=Decimal("1.05"),
    currency="USD",
)

result = calc.calculate(
    cash=Decimal("50000"),
    gold_grams=Decimal("100"),
    stocks_value=Decimal("25000"),
    debts_you_owe=Decimal("5000"),
)

print(f"Nisab threshold: {result.nisab_threshold:.2f} {result.currency}")
print(f"Zakat obligatory: {result.is_zakat_obligatory}")
print(f"Zakat due: {result.zakat_due:.2f} {result.currency}")
```

## Live Market Prices Usage

```python
from zakat_calculator import MarketPrices, ZakatCalculator
from decimal import Decimal

mp = MarketPrices()
gold = mp.get_gold_price_per_gram()
silver = mp.get_silver_price_per_gram()

calc = ZakatCalculator(
    gold_price_per_gram=Decimal(str(gold.value)),
    silver_price_per_gram=Decimal(str(silver.value)),
)
```

## Livestock Zakat

```python
result = calc.calculate_livestock_zakat(
    camels=30,
    cattle=45,
    sheep_goats=150,
)

for animal_type in ["camels_zakat", "cattle_zakat", "sheep_goat_zakat"]:
    info = result[animal_type]
    if info["zakat_applicable"]:
        print(f"{animal_type}: {info['details']}")
```

## API Reference

### `ZakatCalculator`

```python
ZakatCalculator(
    gold_price_per_gram: Decimal,    # current gold price per gram in your currency
    silver_price_per_gram: Decimal,  # current silver price per gram in your currency
    currency: str = "USD",           # ISO 4217 currency code
)
```

### `calculate(...) -> ZakatCalculation`

```python
calc.calculate(
    cash=Decimal("0"),
    gold_grams=Decimal("0"),
    silver_grams=Decimal("0"),
    business_assets=Decimal("0"),
    stocks_value=Decimal("0"),
    agricultural_irrigated=Decimal("0"),
    agricultural_rainfed=Decimal("0"),
    agricultural_produce_kg=Decimal("0"),
    debts_you_owe=Decimal("0"),
    recoverable_debts=Decimal("0"),
)
```

All parameters are optional and default to `0`. Pass only what applies.

**Input parameters** (all optional, default `0`):

| Parameter | Type | Description |
|-----------|------|-------------|
| `cash` | `Decimal` | Cash on hand and bank balances |
| `gold_grams` | `Decimal` | Gold weight in grams |
| `silver_grams` | `Decimal` | Silver weight in grams |
| `business_assets` | `Decimal` | Inventory and trade receivables |
| `stocks_value` | `Decimal` | Market value of stocks and investments |
| `agricultural_irrigated` | `Decimal` | Value of irrigated crops (5% rate) |
| `agricultural_rainfed` | `Decimal` | Value of rain-fed crops (10% rate) |
| `agricultural_produce_kg` | `Decimal` | Produce weight in kg (for Nisab check) |
| `debts_you_owe` | `Decimal` | Liabilities deducted from zakatable wealth |
| `recoverable_debts` | `Decimal` | Money owed to you (optional inclusion) |

**Returned `ZakatCalculation` fields:**

| Field | Type | Description |
|-------|------|-------------|
| `total_zakatable_wealth` | `Decimal` | Total wealth subject to Zakat |
| `nisab_threshold` | `Decimal` | Minimum threshold in the given currency |
| `zakat_due` | `Decimal` | Total Zakat amount due |
| `zakat_rate` | `Decimal` | Effective rate applied (e.g. `0.025` for 2.5%) |
| `is_zakat_obligatory` | `bool` | Whether wealth exceeds Nisab |
| `currency` | `str` | Currency code used for the calculation |
| `breakdown` | `dict` | Asset-by-asset Zakat amounts |
| `calculation_notes` | `list[str]` | Notes, warnings, and Nisab details |

### `calculate_livestock_zakat(camels=0, cattle=0, sheep_goats=0) -> dict`

Calculates Zakat on livestock using classical Islamic schedules.

**Returned dict keys:**

| Key | Description |
|-----|-------------|
| `camels_zakat` | `{"zakat_applicable": bool, "details": str}` |
| `cattle_zakat` | `{"zakat_applicable": bool, "details": str}` |
| `sheep_goat_zakat` | `{"zakat_applicable": bool, "details": str}` |

Minimum thresholds: 5 camels, 30 cattle, 40 sheep/goats.

### `MarketPrices`

```python
MarketPrices(
    metal_providers=[GoldPriceOrgProvider(), KitcoProvider()],
    bulk_rate_providers=[ExchangeRateApiProvider()],
    single_rate_providers=[XeProvider()],
    crypto_providers=[CoinGeckoProvider()],
)
```

| Method | Returns | Description |
|--------|---------|-------------|
| `get_gold_price_per_gram()` | `MarketPriceResult` | Live gold price in USD/gram |
| `get_silver_price_per_gram()` | `MarketPriceResult` | Live silver price in USD/gram |
| `get_exchange_rate(code)` | `MarketPriceResult` | USD value of 1 unit of `code` |
| `get_crypto_price(symbol)` | `MarketPriceResult` | Live crypto price in USD |
| `refresh()` | `None` | Clear cache, force re-fetch |

**`MarketPriceResult` fields:** `value`, `source`, `is_live`, `timestamp`, `warning`

## Custom Market Price Providers

By default, the library fetches live prices from `goldprice.org` → `kitco.com` (metals), `exchangerate-api.com` → `xe.com` (exchange rates), and `coingecko.com` (crypto). You can replace or extend any of these by passing your own provider:

```python
from zakat_calculator import MarketPrices, KitcoProvider

class MyGoldProvider:
    name = "my-api"

    def fetch(self) -> dict:
        import requests
        data = requests.get("https://my-api.com/metals").json()
        return {
            "gold_per_gram": data["gold_usd_per_oz"] / 31.1035,
            "silver_per_gram": data["silver_usd_per_oz"] / 31.1035,
        }

# MyGoldProvider is tried first, KitcoProvider is the fallback
mp = MarketPrices(metal_providers=[MyGoldProvider(), KitcoProvider()])
```

Built-in providers you can mix and match:

| Provider | Type | Source |
|----------|------|--------|
| `GoldPriceOrgProvider` | Metals | goldprice.org |
| `KitcoProvider` | Metals | kitco.com |
| `ExchangeRateApiProvider` | Exchange rates (bulk) | exchangerate-api.com |
| `XeProvider` | Exchange rates (single) | xe.com |
| `CoinGeckoProvider` | Crypto | coingecko.com |

## Testing

```bash
python -m unittest discover -s tests

# Run live market price tests (requires network)
RUN_LIVE_TESTS=1 python -m unittest discover -s tests
```

## Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md) for how to set up your environment, run the pre-commit hooks, and submit a pull request.
