gofinance

module
v1.4.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 11, 2026 License: MIT

README ยถ

๐Ÿ’ฐ GoFinance

A robust, type-safe Go library for financial calculations and money management. GoFinance provides comprehensive tools for handling complex financial mathematics including simple interest, compound interest, annuities, and precise monetary operations โ€” all built on its own zero-dependency, allocation-free decimal engine.


โœจ Features

๐Ÿ”ข Decimal Engine (decimal)
  • Fixed-point decimal type backed by a 128-bit coefficient: up to 19 digits after the decimal point, no float64 rounding surprises
  • Zero external dependencies and zero heap allocations for arithmetic
  • Native mathematical functions computed directly on the decimal representation:
    • Pow โ€” exact binary exponentiation for integer exponents (e.g. (1+i)^n), 120-bit fixed-point exp(eยทln x) for fractional ones
    • Sqrt โ€” Newton's integer iteration on the exact 256-bit radicand, always correctly rounded (exact for perfect squares)
    • Ln, Log, Log2, Log10 โ€” accurate to the full 19-digit precision
  • Banker's, half-away, half-toward, truncating and away-from-zero rounding modes
  • JSON marshaling/unmarshaling and exact string round-tripping
๐Ÿ’ต Money Management (money)
  • Precise monetary amounts built on the decimal engine
  • Multi-currency support with ISO 4217 codes, symbols, and per-currency precision
  • Currency-checked arithmetic (SafeAdd/SafeSub return ErrCurrencyMismatch)
  • Penny-exact allocation: split amounts by ratios or evenly without losing a cent (Allocate, AllocateEvenly)
  • Currency conversion with explicit exchange rates (Convert, ConvertFloat64)
๐Ÿ“Š Simple Interest (finance/simpleinterest)
  • Future value, present value, interest, rate, and period calculations
  • Fluent builder API with day/week/month/year time units
๐Ÿ”„ Compound Interest (finance/compositeinterest)
  • Future/present value and period calculations with flexible compounding frequencies (daily, monthly, bimonthly, quarterly, semi-annual, annual)
  • Rate conversions between periodic, nominal, effective annual, and anticipated rate types
๐Ÿ“ˆ Annuities (finance/annuities)
  • Payment, present/future value, rate, and period calculations
  • Full amortization schedule generation (BuildSchedule)
  • Optional chart rendering of schedules via finance/charts (go-echarts)

๐Ÿš€ Getting Started

Prerequisites
  • Go 1.26.4 or higher
Installation
go get github.com/yeferson59/gofinance
Quick Example: Money Management
package main

import (
    "fmt"

    "github.com/yeferson59/gofinance/money"
)

func main() {
    // $100.00 from an integer amount (10000) and a precision (2)
    m, err := money.New(10000, 2, money.USD)
    if err != nil {
        panic(err)
    }

    str, err := m.StringMoney()
    if err != nil {
        panic(err)
    }
    fmt.Println(str) // USD 100.00

    // Split $100.00 in the ratio 1:1:1 without losing a cent
    parts, err := m.Allocate(1, 1, 1)
    if err != nil {
        panic(err)
    }
    fmt.Println(parts[0].StringFixed(2), parts[1].StringFixed(2), parts[2].StringFixed(2))
    // 33.34 33.33 33.33
}
Quick Example: Decimal Math
package main

import (
    "fmt"

    "github.com/yeferson59/gofinance/decimal"
)

func main() {
    // Exact integer power: 30-year monthly compounding factor
    growth := decimal.MustFromString("1.005").
        MustPow(decimal.MustFromString("360"))
    fmt.Println(growth) // 6.0225752122632161841

    // Correctly rounded square root
    fmt.Println(decimal.MustFromString("2").MustSqrt())
    // 1.4142135623730950488

    // Natural logarithm at full 19-digit precision
    fmt.Println(decimal.MustFromString("2").MustLn())
    // 0.6931471805599453094
}
Quick Example: Compound Interest
package main

import (
    "fmt"

    "github.com/yeferson59/gofinance/finance/compositeinterest"
    "github.com/yeferson59/gofinance/money"
)

func main() {
    ci := compositeinterest.NewComposite().
        Present(1000, money.USD).
        Rate(0.05).
        Periods(12).
        Monthly().
        RateType(compositeinterest.RateEffectyPeriodic).
        MustBuild()

    future, err := ci.Future()
    if err != nil {
        panic(err)
    }
    fmt.Println("Future value:", future.StringFixed(2))
}
Quick Example: Annuities
package main

import (
    "fmt"

    "github.com/yeferson59/gofinance/finance/annuities"
    "github.com/yeferson59/gofinance/money"
)

func main() {
    // Monthly payment for a $300,000 loan at 6% over 360 months
    payment := annuities.NewAnnuity().
        Present(300000, money.USD).
        AnnualRate(0.06).
        Periods(360).
        Monthly().
        MustPayment()

    fmt.Println("Monthly payment:", payment.StringFixed(2))
}

More runnable examples live in examples/main.go.


๐ŸŽฏ Precision & Performance

The decimal engine performs every operation on a 128-bit integer coefficient, so results carry up to 19 exact fractional digits โ€” where float64-based math starts drifting after ~15-16 significant digits:

Expression float64 GoFinance decimal
1.005^12 1.0616778118644976 1.0616778118644995688 (exact)
ln(2) 0.6931471805599453 0.6931471805599453094
sqrt(2) 1.4142135623730951 1.4142135623730950488

Internally, Ln/Log*/Pow run on 120-bit binary fixed-point kernels (~36 internal decimal digits), integer Pow uses exact 38-significant-digit binary exponentiation, and Sqrt computes the integer square root of the exact 256-bit radicand โ€” so it is always correctly rounded.

Indicative benchmarks (Apple M1, make bench):

Operation Time Allocations
Add / Mul / Cmp ~20 ns 0
Div ~60 ns 0
Parse ~70 ns 0
Sqrt ~0.2-0.4 ยตs 0
Ln / Log10 ~0.2-0.7 ยตs 0
Pow ~0.5-0.8 ยตs 0

๐Ÿ“ฆ Project Structure

gofinance/
โ”œโ”€โ”€ decimal/                        # Fixed-point decimal engine (stdlib only)
โ”‚   โ”œโ”€โ”€ decimal128.go              # Core 128-bit coefficient arithmetic
โ”‚   โ”œโ”€โ”€ math.go                    # Native Pow, Sqrt, Ln, Log, Log2, Log10
โ”‚   โ”œโ”€โ”€ u128.go / u256.go          # 128/256-bit integer primitives
โ”‚   โ””โ”€โ”€ root.go                    # Public Decimal API
โ”‚
โ”œโ”€โ”€ money/                          # Money and currency handling
โ”‚   โ”œโ”€โ”€ money.go / root.go         # Core Money type and operations
โ”‚   โ”œโ”€โ”€ currency.go                # ISO 4217 currencies, symbols, precision
โ”‚   โ”œโ”€โ”€ allocate.go                # Penny-exact allocation
โ”‚   โ”œโ”€โ”€ convert.go                 # Currency conversion
โ”‚   โ””โ”€โ”€ decimal.go                 # money.Decimal wrapper for rates/factors
โ”‚
โ”œโ”€โ”€ finance/
โ”‚   โ”œโ”€โ”€ simpleinterest/            # Simple interest (fluent builder)
โ”‚   โ”œโ”€โ”€ compositeinterest/         # Compound interest and rate conversions
โ”‚   โ”œโ”€โ”€ annuities/                 # Annuities and amortization schedules
โ”‚   โ””โ”€โ”€ charts/                    # Amortization chart rendering (go-echarts)
โ”‚
โ”œโ”€โ”€ benchmarks/                     # Cross-package benchmark suites
โ”œโ”€โ”€ examples/                       # Runnable usage examples
โ”œโ”€โ”€ Makefile                        # Development tasks
โ””โ”€โ”€ .golangci.yaml                  # Linting configuration

๐Ÿ› ๏ธ Development

Setup
# Clone the repository
git clone https://github.com/yeferson59/gofinance.git
cd gofinance

# Install dependencies
go mod download
Available Commands
# Run linting
make lint

# Run tests with coverage report
make test

# Format code and run imports
make fmt

# Run benchmarks
make bench
Running Tests
go test -v ./...
Code Coverage
go test -coverpkg=./... -coverprofile=coverage.out ./...
go tool cover -html=coverage.out

๐Ÿ“š Key Concepts

Simple Interest

Simple interest is calculated on the principal amount only. The formula is:

  • Interest = Principal ร— Rate ร— Time

Use this when interest is not compounded.

Compound Interest

Compound interest is calculated on the principal plus accumulated interest. It's more common in real-world scenarios:

  • A = P(1 + r/n)^(nt)

Where:

  • A = Final amount
  • P = Principal
  • r = Annual rate
  • n = Compounding frequency
  • t = Time in years

GoFinance evaluates the (1 + r/n)^(nt) factor with exact binary exponentiation on the decimal engine, so compounding factors don't accumulate floating-point drift.

Annuities

An annuity is a series of equal payments made at regular intervals. Useful for loans, pensions, and investments.


๐Ÿ” Concurrency

Decimal and Money are immutable value types: every operation returns a new value and never mutates its receiver. They can be shared freely across goroutines without locks.


๐Ÿ“– Dependencies

The core packages (decimal, money, finance/...) depend only on the Go standard library.

  • github.com/go-echarts/go-echarts/v2 โ€” used exclusively by the optional finance/charts package
  • github.com/stretchr/testify โ€” testing utilities (dev dependency)

๐Ÿค Contributing

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

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

๐Ÿ“„ License

This project is open source and available under the terms specified in the repository.


๐Ÿ‘จโ€๐Ÿ’ป Author

Yeferson Toloza


๐Ÿ“ž Support

If you have questions or issues:


๐ŸŽฏ Roadmap

  • Additional financial instruments support
  • Performance optimizations (native decimal math, Knuth division, zero-allocation kernels)
  • Extended documentation with more examples
  • CLI tools for quick calculations
  • Web API wrapper

Happy calculating! ๐Ÿงฎ

Directories ยถ

Path Synopsis
finance
annuities
Package annuities provides functionality for annuity calculations.
Package annuities provides functionality for annuity calculations.
charts
Package charts renders amortization schedules produced by finance/annuities as go-echarts line charts (balance, principal, interest, cumulative interest, and payment composition over time).
Package charts renders amortization schedules produced by finance/annuities as go-echarts line charts (balance, principal, interest, cumulative interest, and payment composition over time).
compositeinterest
Package compositeinterest provides functionality for compound interest calculations.
Package compositeinterest provides functionality for compound interest calculations.
simpleinterest
Package simpleinterest provides calculations for simple interest financial formulas.
Package simpleinterest provides calculations for simple interest financial formulas.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL