beans-ledger 1.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
beans/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """beans — professional-grade double-entry accounting for personal finance."""
2
+
3
+ __version__ = "1.0.1"
beans/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from beans.cli import main
4
+
5
+ sys.exit(main())
beans/analysis.py ADDED
@@ -0,0 +1,158 @@
1
+ """Financial analysis: the ratios an analyst would compute for a company,
2
+ adapted to a household — savings rate, liquidity runway, leverage,
3
+ debt-to-income, and expense composition."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from datetime import date
8
+
9
+ from beans import loans
10
+ from beans.ledger import Ledger
11
+ from beans.models import AccountType
12
+ from beans.render import Table, bold, money
13
+ from beans.utils import months_in_range
14
+
15
+
16
+ def analyze(led: Ledger, start: date | None, end: date, label: str) -> dict:
17
+ flows = led.flows(start, end)
18
+ accounts = {a.id: a for a in led.accounts(include_closed=True)}
19
+
20
+ flow_totals = led.type_totals(flows)
21
+ income = flow_totals[AccountType.INCOME]
22
+ expenses = flow_totals[AccountType.EXPENSE]
23
+ net = income - expenses
24
+
25
+ raw = led.balances(as_of=end)
26
+ position = led.position(raw=raw)
27
+ assets = position["assets"]
28
+ liabilities = position["liabilities"]
29
+ cash = position["cash"]
30
+
31
+ # Working-capital view: current assets (by liquidity tag) against current
32
+ # liabilities (loan-aware split, else tag). The quick ratio's numerator is
33
+ # *current* cash — a cash account tagged non-current is excluded so quick
34
+ # assets stay a subset of current assets.
35
+ current_assets = sum(
36
+ raw.get(a.id, 0) * AccountType.ASSET.natural_sign
37
+ for a in accounts.values()
38
+ if a.type is AccountType.ASSET and a.is_current
39
+ )
40
+ current_cash = sum(
41
+ raw.get(a.id, 0) * AccountType.ASSET.natural_sign
42
+ for a in accounts.values()
43
+ if a.type is AccountType.ASSET and a.is_cash and a.is_current
44
+ )
45
+ liab_split = loans.classified_liability_split(led, end, raw)
46
+ current_liabilities = sum(cur for cur, _non in liab_split.values())
47
+ noncurrent_liabilities = sum(non for _cur, non in liab_split.values())
48
+
49
+ months = months_in_range(start, end) if start else None
50
+ monthly_expenses = expenses / months if months else None
51
+ monthly_income = income / months if months else None
52
+
53
+ top_expenses = sorted(
54
+ (
55
+ (accounts[k].name, v * AccountType.EXPENSE.natural_sign)
56
+ for k, v in flows.items()
57
+ if k in accounts and accounts[k].type is AccountType.EXPENSE and v
58
+ ),
59
+ key=lambda item: -item[1],
60
+ )[:5]
61
+
62
+ return {
63
+ "report": "analysis",
64
+ "period": label,
65
+ "start": start,
66
+ "end": end,
67
+ "income": income,
68
+ "expenses": expenses,
69
+ "net_income": net,
70
+ "savings_rate_pct": round(100 * net / income, 1) if income else None,
71
+ "total_assets": assets,
72
+ "total_liabilities": liabilities,
73
+ "net_worth": assets - liabilities,
74
+ "cash": cash,
75
+ "current_assets": current_assets,
76
+ "current_liabilities": current_liabilities,
77
+ "noncurrent_liabilities": noncurrent_liabilities,
78
+ "working_capital": current_assets - current_liabilities,
79
+ "current_ratio": (
80
+ round(current_assets / current_liabilities, 2)
81
+ if current_liabilities else None
82
+ ),
83
+ "quick_ratio": (
84
+ round(current_cash / current_liabilities, 2)
85
+ if current_liabilities else None
86
+ ),
87
+ "liquidity_months": (
88
+ round(cash / monthly_expenses, 1) if monthly_expenses else None
89
+ ),
90
+ "debt_to_assets_pct": (
91
+ round(100 * liabilities / assets, 1) if assets else None
92
+ ),
93
+ "debt_to_annual_income_pct": (
94
+ round(100 * liabilities / (monthly_income * 12), 1)
95
+ if monthly_income else None
96
+ ),
97
+ "top_expenses": [
98
+ {"account": name, "amount": amount,
99
+ "pct_of_income": round(100 * amount / income, 1) if income else None}
100
+ for name, amount in top_expenses
101
+ ],
102
+ }
103
+
104
+
105
+ def render_analysis(data: dict, decimals: int, symbol: str) -> str:
106
+ lines = [bold("FINANCIAL ANALYSIS"),
107
+ f"For the period: {data['period']}", ""]
108
+
109
+ def pct(value) -> str:
110
+ return f"{value:.1f}%" if value is not None else "n/a"
111
+
112
+ table = Table(align="lr")
113
+ table.add(bold("Performance"), "")
114
+ table.add(" Income", money(data["income"], decimals, symbol))
115
+ table.add(" Expenses", money(data["expenses"], decimals, symbol))
116
+ table.add(" Net Income (savings)", money(data["net_income"], decimals,
117
+ symbol))
118
+ table.add(" Savings Rate", pct(data["savings_rate_pct"]))
119
+ table.add("", "")
120
+ table.add(bold("Position"), "")
121
+ table.add(" Total Assets", money(data["total_assets"], decimals, symbol))
122
+ table.add(" Total Liabilities",
123
+ money(data["total_liabilities"], decimals, symbol))
124
+ table.add(" Net Worth", money(data["net_worth"], decimals, symbol))
125
+ table.add(" Cash & Equivalents", money(data["cash"], decimals, symbol))
126
+ table.add("", "")
127
+ table.add(bold("Working Capital"), "")
128
+ table.add(" Current Assets",
129
+ money(data["current_assets"], decimals, symbol))
130
+ table.add(" Current Liabilities",
131
+ money(data["current_liabilities"], decimals, symbol))
132
+ table.add(" Working Capital",
133
+ money(data["working_capital"], decimals, symbol))
134
+ table.add("", "")
135
+ table.add(bold("Ratios"), "")
136
+
137
+ def ratio(value) -> str:
138
+ return f"{value:.2f}" if value is not None else "n/a"
139
+
140
+ table.add(" Current Ratio", ratio(data["current_ratio"]))
141
+ table.add(" Quick Ratio", ratio(data["quick_ratio"]))
142
+ months = data["liquidity_months"]
143
+ table.add(" Liquidity Runway",
144
+ f"{months:.1f} months of expenses" if months is not None
145
+ else "n/a")
146
+ table.add(" Debt / Assets", pct(data["debt_to_assets_pct"]))
147
+ table.add(" Debt / Annual Income",
148
+ pct(data["debt_to_annual_income_pct"]))
149
+ lines.append(table.render())
150
+
151
+ if data["top_expenses"]:
152
+ lines += ["", bold("Top expense categories")]
153
+ top = Table(headers=["Account", "Amount", "% of Income"], align="lrr")
154
+ for row in data["top_expenses"]:
155
+ top.add(row["account"], money(row["amount"], decimals),
156
+ pct(row["pct_of_income"]))
157
+ lines.append(top.render())
158
+ return "\n".join(lines)
beans/budget.py ADDED
@@ -0,0 +1,101 @@
1
+ """Budget vs. actual reporting.
2
+
3
+ Budgets are stored per income/expense account with a cadence (weekly,
4
+ monthly, quarterly, yearly). Reports normalize each budget to the length
5
+ of the requested period, so a $600/month grocery budget shows as $1,800
6
+ for a quarter and is pro-rated for partial periods.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from datetime import date
12
+
13
+ from beans.ledger import BUDGET_PERIOD_MONTHS, Ledger
14
+ from beans.models import AccountType
15
+ from beans.render import Table, bold, green, money, red
16
+ from beans.utils import months_in_range
17
+
18
+
19
+ def budget_report(led: Ledger, start: date, end: date, label: str) -> dict:
20
+ months = months_in_range(start, end)
21
+ flows = led.flows(start, end)
22
+ rows = []
23
+ for account, amount, period in led.budgets():
24
+ monthly = amount / BUDGET_PERIOD_MONTHS[period]
25
+ budgeted = round(monthly * months)
26
+ actual = flows.get(account.id, 0) * account.type.natural_sign
27
+ rows.append({
28
+ "account": account.name,
29
+ "type": account.type.value,
30
+ "period": period,
31
+ "budget": budgeted,
32
+ "actual": actual,
33
+ # For expenses, positive remaining means money left to spend;
34
+ # for income, positive remaining means a shortfall vs. target.
35
+ "remaining": budgeted - actual,
36
+ "pct_used": (100 * actual / budgeted) if budgeted else None,
37
+ })
38
+ expense_rows = [r for r in rows if r["type"] == "expense"]
39
+ income_rows = [r for r in rows if r["type"] == "income"]
40
+ return {
41
+ "report": "budget",
42
+ "period": label,
43
+ "start": start,
44
+ "end": end,
45
+ "months": round(months, 2),
46
+ "rows": rows,
47
+ "total_expense_budget": sum(r["budget"] for r in expense_rows),
48
+ "total_expense_actual": sum(r["actual"] for r in expense_rows),
49
+ "total_income_budget": sum(r["budget"] for r in income_rows),
50
+ "total_income_actual": sum(r["actual"] for r in income_rows),
51
+ }
52
+
53
+
54
+ def render_budget_report(data: dict, decimals: int, symbol: str) -> str:
55
+ lines = [bold("BUDGET REPORT"), f"For the period: {data['period']}", ""]
56
+ if not data["rows"]:
57
+ lines.append("No budgets set. Add one with: "
58
+ "beans budget set <account> <amount> --period monthly")
59
+ return "\n".join(lines)
60
+
61
+ table = Table(headers=["Account", "Budget", "Actual", "Remaining",
62
+ "Used"], align="lrrrr")
63
+ for kind, rows in (("expense", [r for r in data["rows"]
64
+ if r["type"] == "expense"]),
65
+ ("income", [r for r in data["rows"]
66
+ if r["type"] == "income"])):
67
+ if not rows:
68
+ continue
69
+ table.add(bold("Expenses" if kind == "expense" else "Income"),
70
+ "", "", "", "")
71
+ for r in rows:
72
+ pct = f"{r['pct_used']:.0f}%" if r["pct_used"] is not None else ""
73
+ if kind == "expense" and r["pct_used"] is not None:
74
+ pct = red(pct) if r["pct_used"] > 100 else green(pct)
75
+ table.add(" " + r["account"],
76
+ money(r["budget"], decimals),
77
+ money(r["actual"], decimals),
78
+ money(r["remaining"], decimals),
79
+ pct)
80
+ table.rule()
81
+ prefix = "expense" if kind == "expense" else "income"
82
+ budget = data[f"total_{prefix}_budget"]
83
+ actual = data[f"total_{prefix}_actual"]
84
+ pct = f"{100 * actual / budget:.0f}%" if budget else ""
85
+ table.add(bold("Total"),
86
+ money(budget, decimals, symbol),
87
+ money(actual, decimals, symbol),
88
+ money(budget - actual, decimals, symbol),
89
+ pct)
90
+ table.add("", "", "", "", "")
91
+ lines.append(table.render())
92
+ return "\n".join(lines)
93
+
94
+
95
+ def budget_accounts(led: Ledger) -> dict[int, int]:
96
+ """Map of account id -> normalized monthly budget in minor units."""
97
+ return {
98
+ account.id: round(amount / BUDGET_PERIOD_MONTHS[period])
99
+ for account, amount, period in led.budgets()
100
+ if account.type in (AccountType.INCOME, AccountType.EXPENSE)
101
+ }