Python SDK for X-Finance-Util API
Project description
X-Finance Python SDK
A modern, type-safe Python SDK for interacting with the X-Finance-Util API. This SDK provides seamless access to financial calculation services including compound interest, loan payments, and investment return calculations.
✨ Features
- 🔧 Fully Typed: Complete type annotations with Pydantic models
- 🚀 Async Ready: Supports both synchronous and asynchronous operations
- 🛡️ Error Handling: Comprehensive exception hierarchy with detailed error messages
- 📦 Easy Installation: Simple pip installation with no heavy dependencies
- ⚡ Performance: Efficient HTTP connection pooling and request retry logic
- 📚 Documentation: Comprehensive docstrings and usage examples
📦 Installation
pip install xfinance-sdk
⚡ Quick Start
from xfinance import XFinanceClient
from xfinance.models.request import CompoundInterestRequest
from decimal import Decimal
# Initialize the client
client = XFinanceClient(
api_key="your-api-key",
api_secret="your-api-secret",
base_url="https://api.xfinanceutil.com" # Optional: defaults to production
)
try:
# Create a compound interest calculation request
request = CompoundInterestRequest(
principal=Decimal("10000.00"),
annual_rate=Decimal("5.5"),
years=10,
compounding_frequency=12
)
# Get the calculation result
response = client.calculate_compound_interest(request)
print(f"Final Amount: ${response.final_amount:,.2f}")
print(f"Total Interest: ${response.total_interest:,.2f}")
except Exception as e:
print(f"Calculation failed: {e}")
finally:
# Always close the client
client.close()
📋 API Reference
Available Calculations
Compound Interest
response = client.calculate_compound_interest(
CompoundInterestRequest(
principal=Decimal("10000.00"),
annual_rate=Decimal("5.5"),
years=10,
compounding_frequency=12
)
)
Loan Payment Calculation
response = client.calculate_loan_payment(
LoanCalculationRequest(
loan_amount=Decimal("300000.00"),
annual_rate=Decimal("3.5"),
term_years=30
)
)
Investment Returns
response = client.calculate_investment_returns(
InvestmentReturnsRequest(
initial_investment=Decimal("5000.00"),
monthly_contribution=Decimal("500.00"),
expected_annual_return=Decimal("7.0"),
years=20
)
)
🔧 Configuration
Client Options
client = XFinanceClient(
api_key="your-api-key",
api_secret="your-api-secret",
base_url="https://api.xfinanceutil.com", # Optional
timeout=30, # Request timeout in seconds
max_retries=3 # Maximum retry attempts
)
Environment Variables
You can also configure the client using environment variables:
export XFINANCE_API_KEY="your-api-key"
export XFINANCE_API_SECRET="your-api-secret"
export XFINANCE_BASE_URL="https://api.xfinanceutil.com"
# Client will automatically use environment variables
client = XFinanceClient()
🛡️ Error Handling
The SDK provides detailed exception handling:
from xfinance.exceptions import (
AuthenticationException,
ValidationException,
NetworkException,
RateLimitException,
XFinanceException
)
try:
response = client.calculate_compound_interest(request)
except AuthenticationException as e:
print(f"Authentication failed: {e}")
# Handle invalid API credentials
except ValidationException as e:
print(f"Invalid request: {e}")
# Handle invalid input parameters
except RateLimitException as e:
print(f"Rate limit exceeded: {e}")
# Implement retry logic with backoff
except NetworkException as e:
print(f"Network error: {e}")
# Handle connection issues
except XFinanceException as e:
print(f"API error: {e}")
# Handle other API errors
🔄 Async Support
For asynchronous applications:
import asyncio
from xfinance import AsyncXFinanceClient
async def main():
async with AsyncXFinanceClient("your-api-key", "your-api-secret") as client:
response = await client.calculate_compound_interest_async(request)
print(f"Async result: {response.final_amount}")
asyncio.run(main())
📊 Response Models
All responses are strongly typed Pydantic models:
# CompoundInterestResponse
response.final_amount # Decimal: Final amount after interest
response.total_interest # Decimal: Total interest earned
response.principal # Decimal: Original principal
response.annual_rate # Decimal: Annual interest rate used
response.years # int: Number of years
response.compounding_frequency # int: Compounding frequency
# LoanCalculationResponse
response.monthly_payment # Decimal: Monthly payment amount
response.total_interest # Decimal: Total interest paid
response.total_amount # Decimal: Total amount paid
response.loan_amount # Decimal: Original loan amount
response.annual_rate # Decimal: Annual interest rate used
response.term_years # int: Loan term in years
# InvestmentReturnsResponse
response.final_value # Decimal: Final investment value
response.total_contributions # Decimal: Total contributions made
response.total_returns # Decimal: Total returns earned
response.initial_investment # Decimal: Initial investment amount
response.monthly_contribution # Decimal: Monthly contribution amount
response.expected_annual_return # Decimal: Expected annual return rate
response.years # int: Number of years
🚀 Advanced Usage
Custom HTTP Client
import requests
from xfinance import XFinanceClient
# Use a custom session
session = requests.Session()
session.headers.update({"Custom-Header": "value"})
client = XFinanceClient(
api_key="your-key",
api_secret="your-secret",
session=session # Use custom session
)
Request Validation
from xfinance.utils.validation import validate_request
# Manual validation
try:
validate_request(your_request)
response = client.calculate_compound_interest(your_request)
except ValidationException as e:
print(f"Validation failed: {e}")
📚 Examples
Check out the examples directory for complete usage examples:
🔧 Development
Setup Development Environment
# Clone the repository
git clone https://github.com/martourez21/xfinance-python-sdk.git
cd xfinance-python-sdk
# Install development dependencies
pip install -e .[dev]
# Run tests
pytest
# Run linting
black src/ tests/ examples/
isort src/ tests/ examples/
flake8 src/ tests/
mypy src/
Running Tests
# Run all tests
pytest
# Run with coverage
pytest --cov=xfinance --cov-report=html
# Run specific test file
pytest tests/test_client.py -v
📊 Performance
The SDK includes built-in performance optimizations:
- Connection Pooling: Reuses HTTP connections for better performance
- Request Retry: Automatic retry for failed requests with exponential backoff
- Efficient Serialization: Optimized JSON serialization/deserialization
- Memory Efficiency: Minimal memory footprint with lazy loading
🤝 Contributing
We welcome contributions! Please see our Contributing Guide for details.
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🆘 Support
- Documentation: GitHub Repository
- Issues: GitHub Issues
- Email: nestorabiawuh@gmail.com
- Developer: Nestor Martourez
🔗 Links
Note: This SDK requires valid API credentials from X-Finance-Util. Sign up for an account to get your API keys.
Made with ❤️ by Nestor Martourez
📈 Versioning
This project uses Semantic Versioning. Given a version number MAJOR.MINOR.PATCH:
- MAJOR: Incompatible API changes
- MINOR: Backward-compatible functionality additions
- PATCH: Backward-compatible bug fixes
🔄 Changelog
See CHANGELOG.md for a history of changes and releases.
This SDK is independently developed by Nestor Martourez and is officially affiliated with X-Finance-Util.
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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file xfinance_sdk-1.0.1.tar.gz.
File metadata
- Download URL: xfinance_sdk-1.0.1.tar.gz
- Upload date:
- Size: 10.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
6b47bd22db6905860b490fdba83c0460cd886cd3387fba4eada9bfe2d4af9994
|
|
| MD5 |
d006be06ed11c67b60b053d028fa6be2
|
|
| BLAKE2b-256 |
adc7e4e9010f3eb27f8c24ccbe203386991ac10e84e53c2e2ac797d4ed220b4f
|
Provenance
The following attestation bundles were made for xfinance_sdk-1.0.1.tar.gz:
Publisher:
ci.yaml on martourez21/xfinance-python-sdk
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
xfinance_sdk-1.0.1.tar.gz -
Subject digest:
6b47bd22db6905860b490fdba83c0460cd886cd3387fba4eada9bfe2d4af9994 - Sigstore transparency entry: 447859116
- Sigstore integration time:
-
Permalink:
martourez21/xfinance-python-sdk@017f635d0d7b8f110c94ae0f4d4f7e9c86ef310e -
Branch / Tag:
refs/heads/main - Owner: https://github.com/martourez21
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
ci.yaml@017f635d0d7b8f110c94ae0f4d4f7e9c86ef310e -
Trigger Event:
push
-
Statement type:
File details
Details for the file xfinance_sdk-1.0.1-py3-none-any.whl.
File metadata
- Download URL: xfinance_sdk-1.0.1-py3-none-any.whl
- Upload date:
- Size: 7.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
4248f049b1f270de7888e1d010eda0954163d729066923d09ca5853a69dcc775
|
|
| MD5 |
ef03eb7e765182a1c892911ef85b210e
|
|
| BLAKE2b-256 |
b27254f147d56bc7a8a9bfa44aa280e778a4e60f2cccc1fe513211bfa8796138
|
Provenance
The following attestation bundles were made for xfinance_sdk-1.0.1-py3-none-any.whl:
Publisher:
ci.yaml on martourez21/xfinance-python-sdk
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
xfinance_sdk-1.0.1-py3-none-any.whl -
Subject digest:
4248f049b1f270de7888e1d010eda0954163d729066923d09ca5853a69dcc775 - Sigstore transparency entry: 447859141
- Sigstore integration time:
-
Permalink:
martourez21/xfinance-python-sdk@017f635d0d7b8f110c94ae0f4d4f7e9c86ef310e -
Branch / Tag:
refs/heads/main - Owner: https://github.com/martourez21
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
ci.yaml@017f635d0d7b8f110c94ae0f4d4f7e9c86ef310e -
Trigger Event:
push
-
Statement type: