Metadata-Version: 2.5
Name: finance-types
Version: 0.1.0
Summary: Financial scalar types with optional Django and DRF fields
Author-email: Henrique Bastos <henrique@bastos.net>
License-Expression: MIT
License-File: LICENSE
Classifier: Framework :: Django :: 5.2
Classifier: Framework :: Django :: 6.0
Classifier: Framework :: Django :: 6.1
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Requires-Python: >=3.12
Requires-Dist: pycountry>=24.6.1
Provides-Extra: django
Requires-Dist: django-typed-fields<0.2.0,>=0.1.0; extra == 'django'
Requires-Dist: django<6.2,>=5.2; extra == 'django'
Provides-Extra: drf
Requires-Dist: django-typed-fields<0.2.0,>=0.1.0; extra == 'drf'
Requires-Dist: django<6.2,>=5.2; extra == 'drf'
Requires-Dist: djangorestframework<3.19,>=3.16; extra == 'drf'
Provides-Extra: formatting
Requires-Dist: babel<3,>=2.14; extra == 'formatting'
Description-Content-Type: text/markdown

# finance-types

Financial scalar types with optional Django and Django REST Framework fields.
Use validated country codes, currency codes, decimal amounts, percentages, and money in Python applications.
Install optional adapters for Django models, forms, and REST APIs.

## Install

```sh
pip install finance-types
pip install 'finance-types[formatting]'
pip install 'finance-types[django]'
pip install 'finance-types[drf]'
```

Core imports require only `pycountry`. They do not import Django, DRF, or Babel.

## Core example

```python
from decimal import Decimal, ROUND_DOWN
from finance_types import Country, Currency, Money, Percentage

assert Country("IR") == "IR"
assert Currency("IRR") == "IRR"
subtotal = Money("12.345", "USD")
assert round(subtotal).amount == Decimal("12.35")
assert (subtotal * 2).amount == Decimal("24.690")
assert Percentage("0.15").to_100() == Decimal("15")
truncated = subtotal.copy(rounding=ROUND_DOWN)
assert round(truncated).amount == Decimal("12.34")
assert truncated.copy().rounding == ROUND_DOWN
```

### Decimal contracts

`BoundedDecimal`, `NonNegativeAmount`, `PositiveAmount`, `Percentage`, and `Percentage100` are `Decimal` subclasses.
They reject Infinity, negative Infinity, NaN, and signaling NaN with `PrecisionError`.
Malformed numeric strings raise `ValueError`. Unsupported Python objects can raise `TypeError`.

| Type | Minimum | Maximum | Decimal places |
| --- | --- | --- | --- |
| `BoundedDecimal` | -999999999999999.99999 | 999999999999999.99999 | 5 |
| `NonNegativeAmount` | 0 | No finite upper bound | 2 |
| `PositiveAmount` | 0.01 | 999999999999999.99999 | 2 |
| `Percentage` | 0 | 1 | 6 |
| `Percentage100` | 0 | 100 | 6 |

String and Decimal inputs must fit the precision. Trailing zeros do not count toward precision.
Float inputs round before validation, using the active decimal context. Thus `NonNegativeAmount(1.234)` succeeds but `NonNegativeAmount("1.234")` fails.
Decimal context precision still limits quantization and arithmetic. Increase that precision for unusually large amounts.
If quantization produces NaN with the `InvalidOperation` trap disabled, construction raises `PrecisionError`.
With that trap enabled, insufficient context precision can raise `decimal.InvalidOperation`.

These are construction-only checks. Inherited arithmetic normally returns an unrestricted `Decimal`, not the original subtype.
Percentage addition is the exception: the left-hand implementation constructs and validates the same percentage type.
Inherited reverse addition and other operations still return `Decimal`.
`Percentage100.to_1()` can fail if conversion needs more than six fractional places.
For example, `Percentage100("0.000001").to_1()` raises `PrecisionError`; it does not round silently.

### Countries and currencies

`Country` and `Currency` are `str` subclasses backed by the installed `pycountry` catalog.
They require uppercase ASCII letters and exact ISO lengths: two for ISO 3166-1 countries, three for ISO 4217 currencies.
They do not normalize input or restrict valid ISO codes.
Malformed inputs raise `CountryFormatError` or `CurrencyFormatError`.
Well-formed unknown codes raise `CountryValueError` or `CurrencyValueError`.
The installed catalog determines the accepted codes.
Native string operations can return ordinary strings outside these constraints.

### Money

`Money` accepts finite Decimal, integer, and Decimal-compatible string amounts. It rejects floats.
Numeric strings use a decimal point, never process-locale grouping or separators.
Money validates its currency through `Currency` and allows zero and negative amounts.
Its default rounding is `ROUND_HALF_UP` for every currency, including USD.
Construction and arithmetic do not round the amount. `round(money)` uses its precision and rounding policy.
Precision zero is supported. `round(money, n)` overrides the rounding scale for that operation, not its stored precision setting.
Copies and arithmetic preserve explicit rounding. Addition, subtraction, and ordering require the same currency.
Equality compares amount and currency. Locale, precision, and rounding do not affect equality.
Money remains mutable and is deliberately unhashable. Attribute mutation can bypass constructor validation.

Localized formatting requires the `formatting` extra:

```python
from finance_types import Money

assert str(Money("10", "USD", locale_name="en_US")) == "$10.00"
```

Without Babel, localized formatting raises an explicit `ImportError`. Construction, arithmetic, and `repr()` still work.
Babel controls display conventions. Money controls rounding before that display step.

## Django models and forms

```python
from decimal import ROUND_HALF_EVEN
from django.db import models
from finance_types.django import CountryField, MoneyField, PercentageField

class Invoice(models.Model):
    country = CountryField()
    total = MoneyField(max_digits=12, decimal_places=2, rounding=ROUND_HALF_EVEN)
    tax_rate = PercentageField()

    class Meta:
        app_label = "billing"
```

`MoneyField` creates `total_amount` and `total_currency` columns, not a `total` column.
Its DecimalField component accepts zero and negative amounts.
Assignment rounds a copy of the supplied Money to the field's `decimal_places` and `rounding` policy:

```python
from finance_types import Money

invoice = Invoice(total=Money("1.225", "USD", precision=3))
assert invoice.total.amount == Money("1.22", "USD").amount
assert invoice.total.precision == 2
```

Only amount and currency persist. Per-instance locale, precision, and rounding do not persist.
Reads reconstruct the field's precision and rounding, with Money's default locale.
Assigning `None` clears both components. Any null component makes the compound value `None`.
Use `null=True` if the database must accept those null values.

`kw_amount` and `kw_currency` pass component options such as `db_index`, `null`, and `blank`.
Set precision through MoneyField itself, not through `kw_amount`.
The field preserves nondefault configuration in migrations.
Direct component assignment, `QuerySet.update()`, and SQL bypass compound assignment normalization.
Bulk operations persist the current component values; they do not repeat compound assignment normalization.
Use the compound attribute to normalize Money, and call model validation before saving when input is untrusted.
Django does not call `full_clean()` automatically during `save()`. Database enforcement depends on the backend.

`AmountField(max_digits=11, decimal_places=2)` is separate and retains positive-value validation.
`PercentageField` represents 0 to 1. `CurrencyField` and `CountryField` validate their ISO scalar types.
`CountryFormField` strips surrounding whitespace, preserves case, and validates the ISO country.
`CountryField` selects that form field for ModelForm.

## DRF serializers

```python
from rest_framework import serializers
from finance_types.drf import CountrySerializer, Percentage100Serializer

class QuoteSerializer(serializers.Serializer):
    country = CountrySerializer()
    tax_percent = Percentage100Serializer()

quote = QuoteSerializer(data={"country": "IR", "tax_percent": "100"})
assert quote.is_valid(), quote.errors
assert quote.validated_data["tax_percent"] == 1
assert quote.data["tax_percent"] == "100.000000"
```

`PercentageSerializer` accepts and represents 0 to 1.
`Percentage100Serializer` accepts 0 to 100, returns `Percentage` internally, and represents the 100 scale.
Conversions must fit the core's six-place fractional precision; the adapter does not silently discard extra digits.
Configured `decimal_places` counts significant fractional places, not zero padding added by the core.
For example, `PercentageSerializer(decimal_places=2, max_digits=3)` accepts `"0.1"` but rejects `"0.123"`.
Float inputs retain the core's round-before-validation policy.
Declare these fields explicitly on ModelSerializer too. This package does not change DRF's global field registry.

## Supported versions

Requires Python 3.12 or newer. Django adapters support Django 5.2, 6.0, and 6.1.
The `drf` extra requires `djangorestframework>=3.16,<3.19`.
The test matrix uses two stack profiles:

| Profile | Python | Django | DRF |
| --- | --- | --- | --- |
| latest | 3.15.2 | 6.1.3 | 3.18.3 |
| lts | 3.14.10 | 5.2.19 | 3.18.3 |

The `lts` profile selects Django's long-term support line. Python and DRF do not have equivalent LTS lines.
Each profile runs five isolated environments: core, formatting, Django, DRF, and full.
Core and formatting environments do not install Django, DRF, or `django-typed-fields`.
Django environments exclude DRF and Babel. DRF environments exclude Babel. Full environments include Babel.
Database tests use SQLite.

## Testing and contributions

Install Python 3.14.10 and 3.15.2, plus tox 4.53.0 in a virtual environment.
From a source checkout, run the complete matrix:

```sh
tox run
```

Tox builds and installs a wheel for each environment. Missing interpreters fail the run.
It keeps environments, caches, and test databases outside the checkout.
Set `TOX_WORK_DIR` to choose that directory (the default is `/tmp/finance-types-tox`).
Use `tox list` to inspect the environments or `tox run -e py315-full61-rest318` for the latest stack.

GitHub runs two compatibility jobs, one per profile. Each job runs all five environments through tox.
Push and pull request jobs build the target wheel with tox.
These jobs first fetch the public `henriquebastos/django-typed-fields` repository's `main` branch and record its commit SHA.
They build that dependency in runner scratch space and constrain its installation to the resulting wheel.
Core and formatting environments remain independent of that wheel.
Release jobs use published dependencies and test the exact prebuilt release wheel without rebuilding it.

The tests check optional dependency isolation, installed package locations, README examples, and dependency consistency.
Migration tests create and apply migrations, reconstruct historical models, check drift, reverse migrations, and apply them again.
The finance test suite manages Django directly and does not use pytest-django.

For a bug report, include a minimal example and the Python, Django, and DRF versions involved.
For a contribution, add a regression test and run the relevant tox environments before submitting a pull request.
Contact Henrique Bastos at <henrique@bastos.net> for project questions.

### Maintainer releases

Publish `django-typed-fields` first so that release tests can install its compatible version from PyPI.
Set the version in `pyproject.toml` and publish a GitHub release tagged `v{version}`.
The release workflow rejects prereleases and mismatched tags, builds distributions once, and tests that wheel across the full matrix.

To enable publication, register a PyPI Trusted Publisher and configure a protected GitHub environment with required approval.
Set the repository variable `PYPI_ENVIRONMENT` to that environment and `PYPI_PUBLISH_ENABLED` to `true`.
Only the publishing job receives an OIDC token. It publishes the tested wheel and source distribution without rebuilding them.

## License

MIT. Copyright 2026 Henrique Bastos. See [LICENSE](LICENSE).

## Thank you to Routable

[Routable](https://routable.com) sponsored the development of this library.
Working at [Routable](https://routable.com) is an awesome experience, with a developer-first culture that fosters innovation and growth.
If you're interested in joining a dynamic team, [check out our job opportunities here](https://routable.com/careers/)!

## Authors

- Henrique Bastos <henrique@bastos.net>
