
Finance Manager
- 2.2k installs
- 432 repo stars
- Updated November 11, 2025
- ailabs-393/ai-labs-claude-skills
finance-manager is an agent skill that Comprehensive personal finance management system for analyzing transaction data, generating insights, creating visualiza.
About
A comprehensive toolkit for personal finance management that processes transaction data performs sophisticated financial analysis generates actionable insights and creates beautiful visual reports 1 Transaction Data Processing Extract financial data from PDFs CSVs or JSON files 2 Financial Analysis Calculate key metrics identify spending patterns and track savings 3 Visualization Generate interactive HTML reports with charts and graphs 4 Budget Recommendations Provide personalized actionable advice based on spending patterns 5 Trend Analysis Identify spending patterns anomalies and opportunities for optimization For PDF files bash python scripts extract_pdf_data py input pdf output csv For CSV JSON files Ensure data has columns Date Description Income category Type Amount Date format YYYY MM DD or parseable date string Amount Positive for income negative for expenses The finance manager skill documents workflows prerequisites and usage patterns grounded in its repository SKILL md Agents should follow the documented steps respect safety and permission notes and cite only capabilities described in the source It triggers on phrases matching the skill description and integrates with t.
- description: Comprehensive personal finance management system for analyzing transaction data, generating insights, creat
- A comprehensive toolkit for personal finance management that processes transaction data, performs sophisticated financia
- 1. **Transaction Data Processing**: Extract financial data from PDFs, CSVs, or JSON files
- See SKILL.md for finance-manager operational details.
- See SKILL.md for finance-manager operational details.
Finance Manager by the numbers
- 2,205 all-time installs (skills.sh)
- +27 installs in the week ending Aug 2, 2026 (Skillselion tracking)
- Ranked #498 of 16,556 AI & Agent Building skills by installs in the Skillselion catalog
- Security screen: MEDIUM risk (skills.sh audit)
- Data as of Aug 3, 2026 (Skillselion catalog sync)
finance-manager capabilities & compatibility
- Capabilities
- description: comprehensive personal finance mana · a comprehensive toolkit for personal finance man · 1. **transaction data processing**: extract fina · see skill.md for finance manager operational det
- Use cases
- orchestration
What finance-manager says it does
description: Comprehensive personal finance management system for analyzing transaction data, generating insights, creating visualizations, and providing actionable financial recommendations. Use when
A comprehensive toolkit for personal finance management that processes transaction data, performs sophisticated financial analysis, generates actionable insights, and creates beautiful visual reports.
1. **Transaction Data Processing**: Extract financial data from PDFs, CSVs, or JSON files
npx skills add https://github.com/ailabs-393/ai-labs-claude-skills --skill finance-managerAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 2.2k |
|---|---|
| repo stars | ★ 432 |
| Security audit | 2 / 3 scanners passed |
| Last updated | November 11, 2025 |
| Repository | ailabs-393/ai-labs-claude-skills ↗ |
What does finance-manager help with and when should an agent load it?
Comprehensive personal finance management system for analyzing transaction data, generating insights, creating visualizations, and providing actionable financial recommendations. Use when users need t
Who is it for?
Developers using finance-manager as documented in the skill repository.
Skip if: Skip when the task falls outside the finance-manager documented scope.
When should I use this skill?
Comprehensive personal finance management system for analyzing transaction data, generating insights, creating visualizations, and providing actionable financial recommendations. Use when users need t
What you get
Agent actions aligned with the finance-manager SKILL.md workflow and documented deliverables.
- Categorized finance JSON summary
- Savings rate and trend report
By the numbers
- Example output summarizes 15 transactions with a 69.96% savings rate
- Reports 6 expense categories including Housing at $1,200 and Food at $237.07
Files
Finance Manager
A comprehensive toolkit for personal finance management that processes transaction data, performs sophisticated financial analysis, generates actionable insights, and creates beautiful visual reports.
Core Capabilities
1. Transaction Data Processing: Extract financial data from PDFs, CSVs, or JSON files 2. Financial Analysis: Calculate key metrics, identify spending patterns, and track savings 3. Visualization: Generate interactive HTML reports with charts and graphs 4. Budget Recommendations: Provide personalized, actionable advice based on spending patterns 5. Trend Analysis: Identify spending patterns, anomalies, and opportunities for optimization
Workflow
1. Data Extraction and Preparation
For PDF files:
python scripts/extract_pdf_data.py <input.pdf> <output.csv>For CSV/JSON files:
- Ensure data has columns:
Date,Description,Income(category),Type,Amount - Date format: YYYY-MM-DD or parseable date string
- Amount: Positive for income, negative for expenses
2. Financial Analysis
Run comprehensive analysis on transaction data:
python scripts/analyze_finances.py <transactions.csv> > analysis_output.jsonOutput includes:
- Summary statistics (total income, expenses, net savings, savings rate)
- Spending trends (daily averages, top expenses, category percentages)
- Budget recommendations (personalized based on spending patterns)
- Visualization data (prepared for charting)
3. Report Generation
Create interactive HTML report with visualizations:
python scripts/generate_report.py <analysis_output.json> <report.html>Report features:
- Summary dashboard with key metrics
- Interactive pie chart showing spending by category
- Bar chart comparing income vs expenses over time
- Color-coded indicators (green for positive, red for negative)
- Personalized recommendations section
- Responsive design for all devices
4. Complete Workflow Example
# Extract data from PDF
python scripts/extract_pdf_data.py finance_data.pdf transactions.csv
# Analyze the data
python scripts/analyze_finances.py transactions.csv > analysis.json
# Generate visual report
python scripts/generate_report.py analysis.json financial_report.htmlKey Metrics and Benchmarks
Savings Rate
Savings Rate = (Total Income - Total Expenses) / Total Income × 100Benchmarks:
- Below 10%: Needs improvement
- 10-20%: Good
- 20-30%: Excellent
- Above 30%: Outstanding
Category Guidelines (% of income)
- Housing: 25-30%
- Transportation: 10-15%
- Food: 10-15%
- Utilities: 5-10%
- Savings: Minimum 20%
For detailed frameworks and methodologies, see references/financial_frameworks.md.
Analysis Features
Summary Statistics
- Total income and expenses for the period
- Net savings (can be positive or negative)
- Savings rate percentage
- Transaction count
- Date range covered
Spending Trends
- Daily average spending
- Top 5 largest expenses with details
- Category percentage breakdown
- Spending patterns over time
Budget Recommendations
The system generates personalized recommendations based on:
- Savings rate thresholds
- Category spending percentages
- Income diversification
- Budget guideline comparisons
Example recommendations:
- "⚠️ Your savings rate is below 10%. Consider reducing discretionary spending."
- "🍽️ Food spending is 18% of expenses. Consider meal planning to reduce costs."
- "✅ Excellent savings rate! You're on track for strong financial health."
Visualization Components
Category Spending Chart (Doughnut)
Shows proportional breakdown of expenses by category with color coding.
Income vs Expenses Chart (Bar)
Displays monthly comparison of income and expenses to identify cash flow trends.
Interactive Features
- Hover tooltips showing exact values
- Responsive design adapting to screen size
- Color-coded positive (green) and negative (red) indicators
Tips for Best Results
Data Quality
- Ensure all transactions are properly categorized
- Use consistent category names
- Include complete date information
- Verify amounts are correctly signed (+ for income, - for expenses)
Analysis Frequency
- Run monthly analysis for trend tracking
- Generate reports at month-end for review
- Compare month-over-month to identify changes
Action on Recommendations
- Prioritize recommendations by potential impact
- Set specific, measurable goals based on insights
- Track progress by re-running analysis regularly
Dependencies
All scripts require Python 3.7+ with standard libraries. Additional requirements:
For PDF extraction:
pip install pdfplumber --break-system-packagesFor data analysis:
pip install pandas --break-system-packagesAll visualization dependencies are loaded from CDN in the HTML output (Chart.js).
File Organization
finance-manager/
├── scripts/
│ ├── extract_pdf_data.py # PDF → CSV conversion
│ ├── analyze_finances.py # Financial analysis engine
│ └── generate_report.py # HTML report generator
└── references/
└── financial_frameworks.md # Detailed analysis methodologiesCustomization
Adding Custom Categories
Edit the category definitions in analyze_finances.py to match your tracking system.
Adjusting Thresholds
Modify recommendation thresholds in the generate_budget_recommendations() function to match personal goals.
Styling Reports
Customize the HTML_TEMPLATE in generate_report.py to adjust colors, fonts, or layout.
Common Use Cases
Monthly Review: "Analyze my October spending and create a report"
Budget Optimization: "Where am I spending too much money?"
Trend Analysis: "How does my spending this month compare to last month?"
Goal Setting: "What's my savings rate and how can I improve it?"
Category Insights: "Break down my food spending by transaction"
PDF Processing: "Extract all transactions from my bank statement PDF"
Best Practices
1. Consistent Categorization: Use the same category names across all transactions 2. Regular Analysis: Run monthly to spot trends early 3. Act on Insights: Use recommendations to make specific spending changes 4. Track Progress: Compare reports month-over-month 5. Verify Data: Always check extracted PDF data for accuracy before analysis
Reference Materials
For comprehensive financial frameworks, budgeting guidelines, and analysis methodologies, read:
view references/financial_frameworks.mdThis includes:
- The 50/30/20 budget rule
- Category spending benchmarks
- Financial health indicators
- Analysis workflow details
- Visualization best practices
- Recommendation logic
{
"summary": {
"total_income": 6770.0,
"total_expenses": 2033.86,
"net_savings": 4736.14,
"savings_rate": 69.95775480059085,
"expense_by_category": {
"Food": 237.07,
"Health": 92.3,
"Housing": 1200.0,
"Shopping": 124.99,
"Transportation": 225.0,
"Utilities": 154.5
},
"income_by_source": {
"Consulting Income": 1200.0,
"Freelance Project": 750.0,
"Investment Dividend": 320.0,
"Salary Deposit": 4500.0
},
"transaction_count": 15,
"date_range": {
"start": "2025-10-15",
"end": "2025-11-04"
}
},
"trends": {
"daily_average_spending": 96.85047619047619,
"top_expenses": [
{
"Date": "2025-10-22",
"Description": "Coffee Shop",
"Amount": 12.5
},
{
"Date": "2025-10-15",
"Description": "Pharmacy",
"Amount": 42.3
},
{
"Date": "2025-11-03",
"Description": "Gas Station",
"Amount": 45.0
},
{
"Date": "2025-10-24",
"Description": "Gym Membership",
"Amount": 50.0
},
{
"Date": "2025-10-28",
"Description": "Internet Bill",
"Amount": 65.0
}
],
"category_percentages": {
"Food": 11.656161191035764,
"Health": 4.538168802179108,
"Housing": 59.001111187594034,
"Shopping": 6.145457406114482,
"Transportation": 11.062708347673881,
"Utilities": 7.596393065402732
}
},
"recommendations": [
"\u2705 Excellent savings rate! You're on track for strong financial health.",
"\u2705 Great job diversifying your income streams!"
],
"visualization_data": {
"category_spending": {
"Food": 237.07,
"Health": 92.3,
"Housing": 1200.0,
"Shopping": 124.99,
"Transportation": 225.0,
"Utilities": 154.5
},
"daily_trend": [
{
"date": "2025-10-15",
"amount": 42.3
},
{
"date": "2025-10-20",
"amount": 180.0
},
{
"date": "2025-10-22",
"amount": 12.5
},
{
"date": "2025-10-24",
"amount": 50.0
},
{
"date": "2025-10-27",
"amount": 124.99
},
{
"date": "2025-10-28",
"amount": 65.0
},
{
"date": "2025-11-01",
"amount": 1200.0
},
{
"date": "2025-11-02",
"amount": 245.82
},
{
"date": "2025-11-03",
"amount": 45.0
},
{
"date": "2025-11-04",
"amount": 68.25
}
],
"monthly_comparison": [
{
"month": "2025-10",
"income": 1520.0,
"expenses": 474.79
},
{
"month": "2025-11",
"income": 5250.0,
"expenses": 1559.07
}
]
}
}
export default async function finance_manager(input) {
console.log("🧠 Running skill: finance-manager");
// TODO: implement actual logic for this skill
return {
message: "Skill 'finance-manager' executed successfully!",
input
};
}
{
"name": "@ai-labs-claude-skills/finance-manager",
"version": "1.0.0",
"description": "Claude AI skill: finance-manager",
"main": "index.js",
"files": [
"."
],
"license": "MIT",
"author": "AI Labs"
}Financial Analysis Reference Guide
Personal Finance Frameworks
The 50/30/20 Budget Rule
A simple budgeting framework that allocates:
- 50% - Needs (housing, utilities, groceries, transportation, insurance)
- 30% - Wants (dining out, entertainment, shopping, hobbies)
- 20% - Savings and debt repayment
Key Financial Metrics
Savings Rate
Savings Rate = (Total Income - Total Expenses) / Total Income × 100Benchmarks:
- Below 10%: Concerning, needs improvement
- 10-20%: Good, room for optimization
- 20-30%: Excellent
- Above 30%: Outstanding
Expense Ratio by Category
Housing: 25-30% of income Transportation: 10-15% of income Food: 10-15% of income Utilities: 5-10% of income Healthcare: 5-10% of income Entertainment: 5-10% of income Savings: Minimum 20% of income
Cash Flow Analysis
Positive Cash Flow: Income > Expenses (building wealth) Negative Cash Flow: Income < Expenses (depleting savings or accumulating debt)
Financial Health Indicators
1. Emergency Fund: 3-6 months of expenses saved 2. Debt-to-Income Ratio: Should be below 36% 3. Net Worth Growth: Should increase month-over-month 4. Investment Rate: At least 15% of gross income for retirement
Transaction Data Schema
Standard Fields
Date: YYYY-MM-DD format
Description: String describing the transaction
Income: Category (Income, Food, Housing, Transportation, Utilities, Health, Shopping, etc.)
Type: Income or Expense
Amount: Float (positive for income, negative for expenses)Category Definitions
Income Categories:
- Salary: Regular employment income
- Freelance: Contract or gig work
- Investment: Dividends, interest, capital gains
- Business: Self-employment income
- Other: Gifts, refunds, misc
Expense Categories:
- Housing: Rent, mortgage, property tax, home insurance
- Food: Groceries, restaurants, cafes
- Transportation: Gas, car payments, insurance, maintenance, public transit
- Utilities: Electric, water, gas, internet, phone
- Health: Insurance, medications, doctor visits, gym
- Shopping: Clothing, electronics, household items
- Entertainment: Movies, subscriptions, hobbies
- Education: Tuition, books, courses
Analysis Workflows
1. Monthly Review Process
1. Import Data: Extract transactions from bank statements or tracking apps 2. Categorize: Ensure all transactions have correct categories 3. Calculate Totals: Sum income and expenses by category 4. Compare to Budget: Check actuals vs planned spending 5. Identify Anomalies: Flag unusual transactions or categories over budget 6. Generate Insights: Create trends and recommendations
2. Spending Pattern Analysis
Questions to Answer:
- Which categories consume the most money?
- Are there recurring unnecessary expenses?
- How does spending vary by day of week or time of month?
- What percentage of income goes to fixed vs variable expenses?
3. Budget Optimization
Steps: 1. Identify top 3 expense categories 2. Look for reduction opportunities in each 3. Calculate potential savings 4. Set realistic targets 5. Track progress month-over-month
Visualization Best Practices
Chart Types for Financial Data
Pie/Doughnut Charts:
- Best for: Category breakdown of expenses
- Shows: Relative proportion of spending
Bar Charts:
- Best for: Comparing income vs expenses over time
- Shows: Month-over-month trends
Line Charts:
- Best for: Tracking net worth or savings over time
- Shows: Growth trends
Stacked Bar Charts:
- Best for: Showing category breakdown over multiple periods
- Shows: How spending composition changes
Color Conventions
- Green: Income, positive values, on-budget
- Red: Expenses, negative values, over-budget
- Blue: Neutral information
- Yellow/Orange: Warnings, areas needing attention
Recommendation Engine Logic
Triggers for Recommendations
High Spending in Category:
if category_percentage > threshold:
recommend("Consider reducing [category] spending")Low Savings Rate:
if savings_rate < 10:
recommend("Critical: Increase savings immediately")
elif savings_rate < 20:
recommend("Aim for 20% savings rate")Unbalanced Budget:
if needs_percentage > 50:
recommend("Housing or essential costs too high")
if wants_percentage > 30:
recommend("Discretionary spending exceeds guidelines")Income Diversification:
if income_source_count == 1:
recommend("Consider additional income streams")Report Components
Executive Summary
- Total income for period
- Total expenses for period
- Net savings/loss
- Savings rate
- Key insight (1 sentence takeaway)
Detailed Breakdown
- Income by source
- Expenses by category (with percentages)
- Top 5 largest transactions
- Comparison to previous period
Trends & Patterns
- Month-over-month changes
- Category trends
- Spending habits (day of week, time patterns)
Actionable Recommendations
- Specific, measurable actions
- Prioritized by impact
- Easy to implement
Visualizations
- Category spending pie chart
- Income vs expenses bar chart
- Monthly trend line chart
- Budget vs actual comparison
Common Financial Insights
Warning Signs
- Spending more than earning (negative cash flow)
- Savings rate below 5%
- Credit card balances increasing
- Emergency fund depleted
- High percentage in discretionary categories
Positive Indicators
- Consistent month-over-month savings
- Diversified income sources
- Expenses within budget guidelines
- Growing investment contributions
- Low fixed expense ratio
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Financial Report - November 04, 2025</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 20px;
min-height: 100vh;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
.header {
background: white;
padding: 30px;
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0,0,0,0.2);
margin-bottom: 30px;
text-align: center;
}
.header h1 {
color: #333;
font-size: 2.5em;
margin-bottom: 10px;
}
.date-range {
color: #666;
font-size: 1.1em;
}
.stats-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
margin-bottom: 30px;
}
.stat-card {
background: white;
padding: 25px;
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0,0,0,0.2);
}
.stat-card h3 {
color: #666;
font-size: 0.9em;
text-transform: uppercase;
letter-spacing: 1px;
margin-bottom: 10px;
}
.stat-value {
font-size: 2em;
font-weight: bold;
color: #333;
}
.stat-value.positive {
color: #10b981;
}
.stat-value.negative {
color: #ef4444;
}
.chart-container {
background: white;
padding: 30px;
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0,0,0,0.2);
margin-bottom: 30px;
}
.chart-container h2 {
color: #333;
margin-bottom: 20px;
font-size: 1.5em;
}
.chart-wrapper {
position: relative;
height: 300px;
}
.recommendations {
background: white;
padding: 30px;
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0,0,0,0.2);
}
.recommendations h2 {
color: #333;
margin-bottom: 20px;
font-size: 1.5em;
}
.recommendation {
padding: 15px;
margin-bottom: 15px;
border-radius: 10px;
background: #f3f4f6;
border-left: 4px solid #667eea;
}
.recommendation:last-child {
margin-bottom: 0;
}
.footer {
text-align: center;
color: white;
margin-top: 30px;
padding: 20px;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>💰 Financial Report</h1>
<div class="date-range">2025-10-15 to 2025-11-04</div>
</div>
<div class="stats-grid">
<div class="stat-card">
<h3>Total Income</h3>
<div class="stat-value positive">$6,770.00</div>
</div>
<div class="stat-card">
<h3>Total Expenses</h3>
<div class="stat-value negative">$2,033.86</div>
</div>
<div class="stat-card">
<h3>Net Savings</h3>
<div class="stat-value positive">$4,736.14</div>
</div>
<div class="stat-card">
<h3>Savings Rate</h3>
<div class="stat-value positive">70.0%</div>
</div>
</div>
<div class="chart-container">
<h2>📊 Spending by Category</h2>
<div class="chart-wrapper">
<canvas id="categoryChart"></canvas>
</div>
</div>
<div class="chart-container">
<h2>📈 Income vs Expenses</h2>
<div class="chart-wrapper">
<canvas id="comparisonChart"></canvas>
</div>
</div>
<div class="recommendations">
<h2>💡 Recommendations</h2>
<div class="recommendation">✅ Excellent savings rate! You're on track for strong financial health.</div>
<div class="recommendation">✅ Great job diversifying your income streams!</div>
</div>
<div class="footer">
<p>Report Generated: 2025-11-04 10:29:58</p>
</div>
</div>
<script>
// Category Pie Chart
const categoryCtx = document.getElementById('categoryChart').getContext('2d');
new Chart(categoryCtx, {
type: 'doughnut',
data: {
labels: ["Food", "Health", "Housing", "Shopping", "Transportation", "Utilities"],
datasets: [{
data: [237.07, 92.3, 1200.0, 124.99, 225.0, 154.5],
backgroundColor: [
'#667eea', '#764ba2', '#f093fb', '#4facfe',
'#43e97b', '#fa709a', '#fee140', '#30cfd0'
],
borderWidth: 0
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'right'
},
tooltip: {
callbacks: {
label: function(context) {
return context.label + ': $' + context.parsed.toFixed(2);
}
}
}
}
}
});
// Monthly Comparison Bar Chart
const comparisonCtx = document.getElementById('comparisonChart').getContext('2d');
new Chart(comparisonCtx, {
type: 'bar',
data: {
labels: ["2025-10", "2025-11"],
datasets: [
{
label: 'Income',
data: [1520.0, 5250.0],
backgroundColor: '#10b981',
borderRadius: 5
},
{
label: 'Expenses',
data: [474.79, 1559.07],
backgroundColor: '#ef4444',
borderRadius: 5
}
]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'top'
}
},
scales: {
y: {
beginAtZero: true,
ticks: {
callback: function(value) {
return '$' + value.toLocaleString();
}
}
}
}
}
});
</script>
</body>
</html>
#!/usr/bin/env python3
"""
Comprehensive financial analysis tool for processing transaction data,
generating insights, and creating visualizations.
"""
import pandas as pd
import json
from datetime import datetime
from typing import Dict, List, Tuple
import sys
def load_transactions(file_path: str) -> pd.DataFrame:
"""Load transaction data from CSV or JSON file."""
if file_path.endswith('.csv'):
df = pd.read_csv(file_path)
elif file_path.endswith('.json'):
df = pd.read_json(file_path)
else:
raise ValueError("Unsupported file format. Use CSV or JSON.")
# Convert date column to datetime
df['Date'] = pd.to_datetime(df['Date'])
return df
def calculate_summary_stats(df: pd.DataFrame) -> Dict:
"""Calculate summary statistics from transaction data."""
total_income = df[df['Type'] == 'Income']['Amount'].sum()
total_expenses = abs(df[df['Type'] == 'Expense']['Amount'].sum())
net_savings = total_income - total_expenses
# Category breakdown for expenses
expense_by_category = df[df['Type'] == 'Expense'].groupby('Income')['Amount'].sum().abs().to_dict()
# Income breakdown
income_by_source = df[df['Type'] == 'Income'].groupby('Description')['Amount'].sum().to_dict()
return {
'total_income': float(total_income),
'total_expenses': float(total_expenses),
'net_savings': float(net_savings),
'savings_rate': float((net_savings / total_income * 100) if total_income > 0 else 0),
'expense_by_category': expense_by_category,
'income_by_source': income_by_source,
'transaction_count': len(df),
'date_range': {
'start': df['Date'].min().strftime('%Y-%m-%d'),
'end': df['Date'].max().strftime('%Y-%m-%d')
}
}
def analyze_spending_trends(df: pd.DataFrame) -> Dict:
"""Analyze spending patterns and trends."""
expenses = df[df['Type'] == 'Expense'].copy()
# Daily spending average
date_range = (expenses['Date'].max() - expenses['Date'].min()).days + 1
daily_avg = abs(expenses['Amount'].sum()) / date_range if date_range > 0 else 0
# Top expenses
top_expenses = expenses.nlargest(5, 'Amount', keep='all')[['Date', 'Description', 'Amount']].to_dict('records')
for expense in top_expenses:
expense['Date'] = expense['Date'].strftime('%Y-%m-%d')
expense['Amount'] = abs(float(expense['Amount']))
# Category percentages
category_totals = expenses.groupby('Income')['Amount'].sum().abs()
category_percentages = (category_totals / category_totals.sum() * 100).to_dict()
return {
'daily_average_spending': float(daily_avg),
'top_expenses': top_expenses,
'category_percentages': {k: float(v) for k, v in category_percentages.items()}
}
def generate_budget_recommendations(summary: Dict, trends: Dict) -> List[str]:
"""Generate personalized budget recommendations based on spending patterns."""
recommendations = []
# Savings rate recommendations
savings_rate = summary['savings_rate']
if savings_rate < 10:
recommendations.append("⚠️ Your savings rate is below 10%. Consider reducing discretionary spending.")
elif savings_rate < 20:
recommendations.append("💡 Good start! Try to increase your savings rate to 20% for better financial security.")
else:
recommendations.append("✅ Excellent savings rate! You're on track for strong financial health.")
# Category-specific recommendations
expense_categories = summary['expense_by_category']
total_expenses = summary['total_expenses']
for category, amount in expense_categories.items():
percentage = (amount / total_expenses * 100) if total_expenses > 0 else 0
if category == 'Food' and percentage > 15:
recommendations.append(f"🍽️ Food spending is {percentage:.1f}% of expenses. Consider meal planning to reduce costs.")
elif category == 'Shopping' and percentage > 10:
recommendations.append(f"🛍️ Shopping represents {percentage:.1f}% of expenses. Review for unnecessary purchases.")
elif category == 'Transportation' and percentage > 15:
recommendations.append(f"🚗 Transportation costs are {percentage:.1f}% of expenses. Explore carpooling or public transit options.")
# Income diversification
income_sources = len(summary['income_by_source'])
if income_sources == 1:
recommendations.append("💼 Consider diversifying income sources for financial stability.")
elif income_sources > 2:
recommendations.append("✅ Great job diversifying your income streams!")
return recommendations
def create_visualization_data(df: pd.DataFrame) -> Dict:
"""Prepare data structure for visualization."""
expenses = df[df['Type'] == 'Expense'].copy()
income = df[df['Type'] == 'Income'].copy()
# Category spending data
category_data = expenses.groupby('Income')['Amount'].sum().abs().to_dict()
# Daily spending trend
expenses['Date_Only'] = expenses['Date'].dt.date
daily_spending = expenses.groupby('Date_Only')['Amount'].sum().abs()
daily_trend = [{'date': str(date), 'amount': float(amount)} for date, amount in daily_spending.items()]
# Income vs Expenses over time
expenses['YearMonth'] = expenses['Date'].dt.to_period('M').astype(str)
income['YearMonth'] = income['Date'].dt.to_period('M').astype(str)
monthly_expenses = expenses.groupby('YearMonth')['Amount'].sum().abs()
monthly_income = income.groupby('YearMonth')['Amount'].sum()
monthly_comparison = []
all_months = sorted(set(monthly_expenses.index) | set(monthly_income.index))
for month in all_months:
monthly_comparison.append({
'month': month,
'income': float(monthly_income.get(month, 0)),
'expenses': float(monthly_expenses.get(month, 0))
})
return {
'category_spending': category_data,
'daily_trend': daily_trend,
'monthly_comparison': monthly_comparison
}
def main():
if len(sys.argv) < 2:
print("Usage: python analyze_finances.py <transaction_file.csv>")
sys.exit(1)
file_path = sys.argv[1]
# Load data
df = load_transactions(file_path)
# Generate analysis
summary = calculate_summary_stats(df)
trends = analyze_spending_trends(df)
recommendations = generate_budget_recommendations(summary, trends)
viz_data = create_visualization_data(df)
# Compile full report
report = {
'summary': summary,
'trends': trends,
'recommendations': recommendations,
'visualization_data': viz_data
}
# Output as JSON
print(json.dumps(report, indent=2))
if __name__ == "__main__":
main()
#!/usr/bin/env python3
"""
Extract financial transaction data from PDF files and convert to CSV format.
"""
import sys
import csv
import re
from datetime import datetime
def extract_tables_from_pdf(pdf_path: str) -> list:
"""Extract table data from PDF using pdfplumber."""
try:
import pdfplumber
except ImportError:
print("Error: pdfplumber not installed. Install with: pip install pdfplumber --break-system-packages")
sys.exit(1)
all_transactions = []
with pdfplumber.open(pdf_path) as pdf:
for page in pdf.pages:
tables = page.extract_tables()
for table in tables:
if table:
# First row is usually headers
headers = table[0] if table else []
# Process data rows
for row in table[1:]:
if row and len(row) >= 5:
# Skip empty rows or header rows
if not row[0] or 'Date' in str(row[0]):
continue
try:
# Parse the row: [Date, Description, Income/Category, Type, Amount]
date_str = str(row[0]).strip()
description = str(row[1]).strip()
category = str(row[2]).strip()
trans_type = str(row[3]).strip()
amount_str = str(row[4]).strip().replace(',', '')
# Parse date
date = datetime.strptime(date_str, '%b %d, %Y').strftime('%Y-%m-%d')
# Parse amount
amount = float(amount_str)
all_transactions.append({
'Date': date,
'Description': description,
'Income': category,
'Type': trans_type,
'Amount': amount
})
except (ValueError, IndexError) as e:
continue
return all_transactions
def save_to_csv(transactions: list, output_path: str):
"""Save transactions to CSV file."""
if not transactions:
print("No transactions found to save.")
return
fieldnames = ['Date', 'Description', 'Income', 'Type', 'Amount']
with open(output_path, 'w', newline='') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(transactions)
print(f"Extracted {len(transactions)} transactions to {output_path}")
def main():
if len(sys.argv) < 3:
print("Usage: python extract_pdf_data.py <input.pdf> <output.csv>")
sys.exit(1)
pdf_path = sys.argv[1]
csv_path = sys.argv[2]
print(f"Extracting data from {pdf_path}...")
transactions = extract_tables_from_pdf(pdf_path)
print("Saving to CSV...")
save_to_csv(transactions, csv_path)
if __name__ == "__main__":
main()
#!/usr/bin/env python3
"""
Generate interactive HTML financial reports with charts and visualizations.
"""
import json
import sys
from datetime import datetime
HTML_TEMPLATE = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Financial Report - {date}</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<style>
* {{
margin: 0;
padding: 0;
box-sizing: border-box;
}}
body {{
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 20px;
min-height: 100vh;
}}
.container {{
max-width: 1200px;
margin: 0 auto;
}}
.header {{
background: white;
padding: 30px;
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0,0,0,0.2);
margin-bottom: 30px;
text-align: center;
}}
.header h1 {{
color: #333;
font-size: 2.5em;
margin-bottom: 10px;
}}
.date-range {{
color: #666;
font-size: 1.1em;
}}
.stats-grid {{
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
margin-bottom: 30px;
}}
.stat-card {{
background: white;
padding: 25px;
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0,0,0,0.2);
}}
.stat-card h3 {{
color: #666;
font-size: 0.9em;
text-transform: uppercase;
letter-spacing: 1px;
margin-bottom: 10px;
}}
.stat-value {{
font-size: 2em;
font-weight: bold;
color: #333;
}}
.stat-value.positive {{
color: #10b981;
}}
.stat-value.negative {{
color: #ef4444;
}}
.chart-container {{
background: white;
padding: 30px;
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0,0,0,0.2);
margin-bottom: 30px;
}}
.chart-container h2 {{
color: #333;
margin-bottom: 20px;
font-size: 1.5em;
}}
.chart-wrapper {{
position: relative;
height: 300px;
}}
.recommendations {{
background: white;
padding: 30px;
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0,0,0,0.2);
}}
.recommendations h2 {{
color: #333;
margin-bottom: 20px;
font-size: 1.5em;
}}
.recommendation {{
padding: 15px;
margin-bottom: 15px;
border-radius: 10px;
background: #f3f4f6;
border-left: 4px solid #667eea;
}}
.recommendation:last-child {{
margin-bottom: 0;
}}
.footer {{
text-align: center;
color: white;
margin-top: 30px;
padding: 20px;
}}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>💰 Financial Report</h1>
<div class="date-range">{date_range}</div>
</div>
<div class="stats-grid">
<div class="stat-card">
<h3>Total Income</h3>
<div class="stat-value positive">${total_income:,.2f}</div>
</div>
<div class="stat-card">
<h3>Total Expenses</h3>
<div class="stat-value negative">${total_expenses:,.2f}</div>
</div>
<div class="stat-card">
<h3>Net Savings</h3>
<div class="stat-value {savings_class}">${net_savings:,.2f}</div>
</div>
<div class="stat-card">
<h3>Savings Rate</h3>
<div class="stat-value {savings_rate_class}">{savings_rate:.1f}%</div>
</div>
</div>
<div class="chart-container">
<h2>📊 Spending by Category</h2>
<div class="chart-wrapper">
<canvas id="categoryChart"></canvas>
</div>
</div>
<div class="chart-container">
<h2>📈 Income vs Expenses</h2>
<div class="chart-wrapper">
<canvas id="comparisonChart"></canvas>
</div>
</div>
<div class="recommendations">
<h2>💡 Recommendations</h2>
{recommendations_html}
</div>
<div class="footer">
<p>Report Generated: {generation_date}</p>
</div>
</div>
<script>
// Category Pie Chart
const categoryCtx = document.getElementById('categoryChart').getContext('2d');
new Chart(categoryCtx, {{
type: 'doughnut',
data: {{
labels: {category_labels},
datasets: [{{
data: {category_values},
backgroundColor: [
'#667eea', '#764ba2', '#f093fb', '#4facfe',
'#43e97b', '#fa709a', '#fee140', '#30cfd0'
],
borderWidth: 0
}}]
}},
options: {{
responsive: true,
maintainAspectRatio: false,
plugins: {{
legend: {{
position: 'right'
}},
tooltip: {{
callbacks: {{
label: function(context) {{
return context.label + ': $' + context.parsed.toFixed(2);
}}
}}
}}
}}
}}
}});
// Monthly Comparison Bar Chart
const comparisonCtx = document.getElementById('comparisonChart').getContext('2d');
new Chart(comparisonCtx, {{
type: 'bar',
data: {{
labels: {monthly_labels},
datasets: [
{{
label: 'Income',
data: {monthly_income},
backgroundColor: '#10b981',
borderRadius: 5
}},
{{
label: 'Expenses',
data: {monthly_expenses},
backgroundColor: '#ef4444',
borderRadius: 5
}}
]
}},
options: {{
responsive: true,
maintainAspectRatio: false,
plugins: {{
legend: {{
position: 'top'
}}
}},
scales: {{
y: {{
beginAtZero: true,
ticks: {{
callback: function(value) {{
return '$' + value.toLocaleString();
}}
}}
}}
}}
}}
}});
</script>
</body>
</html>
"""
def generate_html_report(analysis_data: dict, output_file: str):
"""Generate HTML report from analysis data."""
summary = analysis_data['summary']
recommendations = analysis_data['recommendations']
viz_data = analysis_data['visualization_data']
# Format recommendations
recommendations_html = '\n'.join([
f'<div class="recommendation">{rec}</div>'
for rec in recommendations
])
# Prepare chart data
category_labels = list(viz_data['category_spending'].keys())
category_values = list(viz_data['category_spending'].values())
monthly_labels = [item['month'] for item in viz_data['monthly_comparison']]
monthly_income = [item['income'] for item in viz_data['monthly_comparison']]
monthly_expenses = [item['expenses'] for item in viz_data['monthly_comparison']]
# Determine savings class
net_savings = summary['net_savings']
savings_rate = summary['savings_rate']
savings_class = 'positive' if net_savings > 0 else 'negative'
savings_rate_class = 'positive' if savings_rate >= 20 else ('negative' if savings_rate < 10 else '')
# Format HTML
html = HTML_TEMPLATE.format(
date=datetime.now().strftime('%B %d, %Y'),
date_range=f"{summary['date_range']['start']} to {summary['date_range']['end']}",
total_income=summary['total_income'],
total_expenses=summary['total_expenses'],
net_savings=net_savings,
savings_rate=savings_rate,
savings_class=savings_class,
savings_rate_class=savings_rate_class,
recommendations_html=recommendations_html,
generation_date=datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
category_labels=json.dumps(category_labels),
category_values=json.dumps(category_values),
monthly_labels=json.dumps(monthly_labels),
monthly_income=json.dumps(monthly_income),
monthly_expenses=json.dumps(monthly_expenses)
)
with open(output_file, 'w') as f:
f.write(html)
print(f"Report generated: {output_file}")
def main():
if len(sys.argv) < 3:
print("Usage: python generate_report.py <analysis_data.json> <output.html>")
sys.exit(1)
input_file = sys.argv[1]
output_file = sys.argv[2]
with open(input_file, 'r') as f:
analysis_data = json.load(f)
generate_html_report(analysis_data, output_file)
if __name__ == "__main__":
main()
Date,Description,Income,Type,Amount
2025-11-01,Salary Deposit,Income,Income,4500
2025-11-01,Rent Payment,Housing,Expense,-1200
2025-11-02,Grocery Shopping,Food,Expense,-156.32
2025-11-02,Electric Bill,Utilities,Expense,-89.5
2025-11-03,Gas Station,Transportation,Expense,-45
2025-11-03,Freelance Project,Income,Income,750
2025-11-04,Restaurant Dinner,Food,Expense,-68.25
2025-10-28,Internet Bill,Utilities,Expense,-65
2025-10-27,Online Shopping,Shopping,Expense,-124.99
2025-10-25,Investment Dividend,Income,Income,320
2025-10-24,Gym Membership,Health,Expense,-50
2025-10-22,Coffee Shop,Food,Expense,-12.5
2025-10-20,Car Insurance,Transportation,Expense,-180
2025-10-18,Consulting Income,Income,Income,1200
2025-10-15,Pharmacy,Health,Expense,-42.3
Related skills
How it compares
Use finance-manager for quick agent summaries from logs; use dedicated accounting software when compliance and audit trails are required.
FAQ
What is finance-manager?
Comprehensive personal finance management system for analyzing transaction data, generating insights, creating visualizations, and providing actionable financial recommendations. U
When should I use finance-manager?
Comprehensive personal finance management system for analyzing transaction data, generating insights, creating visualizations, and providing actionable financial recommendations. U
Is finance-manager safe to install?
Review the Security Audits panel on this page before installing in production.