Kaanta / example_optimize.py
Oluwaferanmi
This is the latest changes
66d6b11
raw
history blame
9.45 kB
# example_optimize.py
"""
Example usage of the Tax Optimization API
Demonstrates how to send transaction data and get optimization recommendations
"""
import requests
import json
from datetime import datetime, timedelta
# API endpoint (adjust if running on different host/port)
BASE_URL = "http://localhost:8000"
OPTIMIZE_ENDPOINT = f"{BASE_URL}/v1/optimize"
# Example: Individual with employment income
def example_employed_individual():
"""Example: Employed individual with salary and some deductions"""
# Simulate 12 months of transactions
transactions = []
# Monthly salary (Jan - Dec 2025)
for month in range(1, 13):
date_str = f"2025-{month:02d}-28"
# Salary credit
transactions.append({
"type": "credit",
"amount": 500000,
"narration": "SALARY PAYMENT FROM ABC COMPANY LTD",
"date": date_str,
"balance": 750000,
"metadata": {
"basic_salary": 300000,
"housing_allowance": 120000,
"transport_allowance": 60000,
"bonus": 20000
}
})
# Pension deduction (8% of basic = 24,000)
transactions.append({
"type": "debit",
"amount": 24000,
"narration": "PENSION CONTRIBUTION TO XYZ PFA RSA",
"date": date_str,
"balance": 726000
})
# NHF deduction (2.5% of basic = 7,500)
transactions.append({
"type": "debit",
"amount": 7500,
"narration": "NHF CONTRIBUTION DEDUCTION",
"date": date_str,
"balance": 718500
})
# Annual life insurance premium (paid in January)
transactions.append({
"type": "debit",
"amount": 50000,
"narration": "LIFE INSURANCE PREMIUM PAYMENT",
"date": "2025-01-15",
"balance": 700000
})
# Monthly rent payments
for month in range(1, 13):
transactions.append({
"type": "debit",
"amount": 150000,
"narration": "RENT PAYMENT TO LANDLORD",
"date": f"2025-{month:02d}-05",
"balance": 550000
})
# Prepare request
payload = {
"user_id": "user_12345",
"transactions": transactions,
"taxpayer_profile": {
"taxpayer_type": "individual",
"employment_status": "employed",
"location": "Lagos"
},
"tax_year": 2025,
"tax_type": "PIT",
"jurisdiction": "state"
}
print("=" * 80)
print("EXAMPLE: Employed Individual Tax Optimization")
print("=" * 80)
print(f"\nSending {len(transactions)} transactions for analysis...")
print(f"Annual gross income: ₦{500000 * 12:,.0f}")
print(f"Current pension: ₦{24000 * 12:,.0f}/year")
print(f"Current life insurance: ₦50,000/year")
print(f"Annual rent paid: ₦{150000 * 12:,.0f}")
# Send request
try:
response = requests.post(OPTIMIZE_ENDPOINT, json=payload, timeout=120)
response.raise_for_status()
result = response.json()
# Display results
print("\n" + "=" * 80)
print("OPTIMIZATION RESULTS")
print("=" * 80)
print(f"\nTax Summary:")
print(f" Baseline Tax: ₦{result['baseline_tax_liability']:,.2f}")
print(f" Optimized Tax: ₦{result['optimized_tax_liability']:,.2f}")
print(f" Potential Savings: ₦{result['total_potential_savings']:,.2f}")
print(f" Savings Percentage: {result['savings_percentage']:.1f}%")
print(f"\nIncome & Deductions:")
print(f" Total Annual Income: ₦{result['total_annual_income']:,.2f}")
print(f" Current Deductions:")
for key, value in result['current_deductions'].items():
if key != 'total':
print(f" - {key.replace('_', ' ').title()}: ₦{value:,.2f}")
print(f" Total: ₦{result['current_deductions']['total']:,.2f}")
print(f"\nRecommendations ({result['recommendation_count']}):")
for i, rec in enumerate(result['recommendations'][:5], 1):
print(f"\n {i}. {rec['strategy_name']}")
print(f" Savings: ₦{rec['annual_tax_savings']:,.2f}")
print(f" Description: {rec['description']}")
print(f" Risk: {rec['risk_level'].upper()} | Complexity: {rec['complexity'].upper()}")
if rec['implementation_steps']:
print(f" Next Steps:")
for step in rec['implementation_steps'][:3]:
print(f" • {step}")
print(f"\nTransaction Analysis:")
ts = result['transaction_summary']
print(f" Total Transactions: {ts['total_transactions']}")
print(f" Categorized: {ts['categorized']} ({ts.get('categorization_rate', 0)*100:.1f}%)")
print(f" High Confidence: {ts['high_confidence']}")
# Save full result to file
with open("optimization_result_example.json", "w") as f:
json.dump(result, f, indent=2)
print(f"\n[SUCCESS] Full results saved to: optimization_result_example.json")
except requests.exceptions.RequestException as e:
print(f"\n[ERROR] {e}")
if hasattr(e, 'response') and e.response is not None:
print(f"Response: {e.response.text}")
def example_self_employed():
"""Example: Self-employed individual with business income"""
transactions = []
# Business income (irregular payments)
business_payments = [
("2025-01-15", 800000, "CLIENT PAYMENT - PROJECT A"),
("2025-02-20", 1200000, "INVOICE PAYMENT - CLIENT B"),
("2025-03-10", 600000, "CONSULTING FEE - CLIENT C"),
("2025-04-25", 950000, "PROJECT PAYMENT - CLIENT D"),
("2025-06-15", 1100000, "SALES REVENUE - JUNE"),
("2025-08-30", 750000, "CLIENT PAYMENT - PROJECT E"),
("2025-10-12", 1300000, "INVOICE SETTLEMENT - CLIENT F"),
]
for date_str, amount, narration in business_payments:
transactions.append({
"type": "credit",
"amount": amount,
"narration": narration,
"date": date_str,
"balance": amount
})
# Voluntary pension contributions
for month in [1, 4, 7, 10]:
transactions.append({
"type": "debit",
"amount": 100000,
"narration": "VOLUNTARY PENSION CONTRIBUTION",
"date": f"2025-{month:02d}-15",
"balance": 500000
})
payload = {
"user_id": "user_67890",
"transactions": transactions,
"taxpayer_profile": {
"taxpayer_type": "individual",
"employment_status": "self_employed",
"location": "Abuja"
},
"tax_year": 2025,
"tax_type": "PIT"
}
print("\n" + "=" * 80)
print("EXAMPLE: Self-Employed Individual")
print("=" * 80)
try:
response = requests.post(OPTIMIZE_ENDPOINT, json=payload, timeout=120)
response.raise_for_status()
result = response.json()
print(f"\n[SUCCESS] Optimization completed!")
print(f" Baseline Tax: ₦{result['baseline_tax_liability']:,.2f}")
print(f" Potential Savings: ₦{result['total_potential_savings']:,.2f}")
print(f" Recommendations: {result['recommendation_count']}")
except requests.exceptions.RequestException as e:
print(f"\n[ERROR] {e}")
def example_minimal():
"""Minimal example with just a few transactions"""
payload = {
"user_id": "test_user",
"transactions": [
{
"type": "credit",
"amount": 400000,
"narration": "MONTHLY SALARY",
"date": "2025-01-31",
"balance": 400000
},
{
"type": "debit",
"amount": 32000,
"narration": "PENSION DEDUCTION",
"date": "2025-01-31",
"balance": 368000
}
],
"tax_year": 2025
}
print("\n" + "=" * 80)
print("EXAMPLE: Minimal Transaction Set")
print("=" * 80)
try:
response = requests.post(OPTIMIZE_ENDPOINT, json=payload, timeout=60)
response.raise_for_status()
result = response.json()
print(f"\n[SUCCESS] Analysis completed!")
print(f" Income: ₦{result['total_annual_income']:,.2f}")
print(f" Tax: ₦{result['baseline_tax_liability']:,.2f}")
print(f" Savings Opportunity: ₦{result['total_potential_savings']:,.2f}")
except requests.exceptions.RequestException as e:
print(f"\n[ERROR] {e}")
if __name__ == "__main__":
print("\nKaanta Tax Optimization API - Examples\n")
print("Make sure the API is running: uvicorn orchestrator:app --reload --port 8000\n")
# Run examples
example_employed_individual()
# Uncomment to run other examples:
# example_self_employed()
# example_minimal()
print("\n" + "=" * 80)
print("✅ Examples completed!")
print("=" * 80)