๐ฐ 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
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.
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:
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.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature)
- Commit your changes (
git commit -m 'Add some amazing feature')
- Push to the branch (
git push origin feature/amazing-feature)
- 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! ๐งฎ