-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathbeancount_envelope.py
369 lines (326 loc) · 13.6 KB
/
beancount_envelope.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# Debug
from __future__ import annotations
import collections
import datetime
import logging
import re
import pandas as pd
from beancount.core import account_types
from beancount.core import amount
from beancount.core import convert
from beancount.core import data
from beancount.core import inventory
from beancount.core import prices
from beancount.core.data import Custom
from beancount.core.number import Decimal
from beancount.parser import options
from beancount.query import query
from dateutil.relativedelta import relativedelta
class BeancountEnvelope:
def __init__(self, entries, options_map, currency):
self.entries = entries
self.options_map = options_map
self.currency = currency
self.negative_rollover = False
self.months_ahead = 0
if self.currency:
self.etype = "envelope" + self.currency
else:
self.etype = "envelope"
(
self.start_date,
self.budget_accounts,
self.mappings,
self.income_accounts,
self.months_ahead,
) = self._find_envelop_settings()
if not self.currency:
self.currency = self._find_currency(options_map)
decimal_precison = "0.00"
self.Q = Decimal(decimal_precison)
# Compute start of period
# TODO get start date from journal
today = datetime.date.today()
self.date_start = datetime.datetime.strptime(
self.start_date, "%Y-%m"
).date()
# TODO should be able to assert errors
# Compute end of period
self.date_end = datetime.date(
today.year, today.month, today.day
) + relativedelta(months=+self.months_ahead)
self.price_map = prices.build_price_map(entries)
self.acctypes = options.get_account_types(options_map)
def _find_currency(self, options_map):
default_currency = "USD"
opt_currency = options_map.get("operating_currency")
currency = opt_currency[0] if opt_currency else default_currency
if len(currency) == 3:
return currency
logging.warning(
f"invalid operating currency: {currency},"
+ "defaulting to {default_currency}"
)
return default_currency
def _find_envelop_settings(self):
start_date = None
budget_accounts = []
mappings = []
income_accounts = []
months_ahead = 0
for e in self.entries:
if isinstance(e, Custom) and e.type == self.etype:
if e.values[0].value == "start date":
start_date = e.values[1].value
if e.values[0].value == "budget account":
budget_accounts.append(re.compile(e.values[1].value))
if e.values[0].value == "mapping":
map_set = (
re.compile(e.values[1].value),
e.values[2].value,
)
mappings.append(map_set)
if e.values[0].value == "income account":
income_accounts.append(re.compile(e.values[1].value))
if e.values[0].value == "currency":
self.currency = e.values[1].value
if e.values[0].value == "negative rollover":
if e.values[1].value == "allow":
self.negative_rollover = True
if e.values[0].value == "months ahead":
months_ahead = int(e.values[1].value)
return (
start_date,
budget_accounts,
mappings,
income_accounts,
months_ahead,
)
def envelope_tables(self):
months = []
date_current = self.date_start
while date_current < self.date_end:
months.append(
f"{date_current.year}-{str(date_current.month).zfill(2)}"
)
month = date_current.month - 1 + 1
year = date_current.year + month // 12
month = month % 12 + 1
date_current = datetime.date(year, month, 1)
# Create Income DataFrame
column_index = pd.MultiIndex.from_product([months], names=["Month"])
self.income_df = pd.DataFrame(columns=months)
# Create Envelopes DataFrame
column_index = pd.MultiIndex.from_product(
[months, ["budgeted", "activity", "available"]],
names=["Month", "col"],
)
self.envelope_df = pd.DataFrame(columns=column_index)
self.envelope_df.index.name = "Envelopes"
self._calculate_budget_activity()
self._calc_budget_budgeted()
# Calculate Starting Balance Income
starting_balance = Decimal(0.0)
query_str = (
f"select account, convert(sum(position),'{self.currency}')"
+ f" from close on {months[0]}-01 group by 1 order by 1;"
)
rows = query.run_query(
self.entries, self.options_map, query_str, numberify=True
)
for row in rows[1]:
if any(regexp.match(row[0]) for regexp in self.budget_accounts):
if row[1] is not None:
starting_balance += row[1]
self.income_df[months[0]]["Avail Income"] += starting_balance
self.envelope_df.fillna(Decimal(0.00), inplace=True)
# Set available
for index, row in self.envelope_df.iterrows():
for index2, month in enumerate(months):
if index2 == 0:
self.envelope_df[month, "available"][index] = (
row[month, "budgeted"] + row[month, "activity"]
)
else:
prev_available = self.envelope_df[
months[index2 - 1], "available"
][index]
if prev_available > 0 or self.negative_rollover:
self.envelope_df[month, "available"][index] = (
prev_available
+ row[month, "budgeted"]
+ row[month, "activity"]
)
else:
self.envelope_df[month, "available"][index] = (
row[month, "budgeted"] + row[month, "activity"]
)
# Set overspent
for index, month in enumerate(months):
if index == 0:
self.income_df.loc["Overspent", month] = Decimal(0.00)
else:
overspent = Decimal(0.00)
for index2, row in self.envelope_df.iterrows():
if row[months[index - 1], "available"] < Decimal(0.00):
overspent += Decimal(
row[months[index - 1], "available"]
)
self.income_df.loc["Overspent", month] = overspent
# Set Budgeted for month
for month in months:
self.income_df.loc["Budgeted", month] = Decimal(
-1 * self.envelope_df[month, "budgeted"].sum()
)
# Adjust Avail Income
for index, month in enumerate(months):
if index == 0:
continue
else:
prev_month = months[index - 1]
self.income_df.loc["Avail Income", month] = (
self.income_df.loc["Avail Income", month]
+ self.income_df.loc["Avail Income", prev_month]
+ self.income_df.loc["Overspent", prev_month]
+ self.income_df.loc["Budgeted", prev_month]
)
# Set Budgeted in the future
for index, month in enumerate(months):
sum_total = self.income_df[month].sum()
if (index == len(months) - 1) or sum_total < 0:
self.income_df.loc["Budgeted Future", month] = Decimal(0.00)
else:
next_month = months[index + 1]
opp_budgeted_next_month = (
self.income_df.loc["Budgeted", next_month] * -1
)
if opp_budgeted_next_month < sum_total:
self.income_df.loc["Budgeted Future", month] = Decimal(
-1 * opp_budgeted_next_month
)
else:
self.income_df.loc["Budgeted Future", month] = Decimal(
-1 * sum_total
)
# Set to be budgeted
for index, month in enumerate(months):
self.income_df.loc["To Be Budgeted", month] = Decimal(
self.income_df[month].sum()
)
return self.income_df, self.envelope_df, self.currency
def _calculate_budget_activity(self):
# Accumulate expenses for the period
balances = collections.defaultdict(
lambda: collections.defaultdict(inventory.Inventory)
)
all_months = set()
for entry in data.filter_txns(self.entries):
# Check entry in date range
if entry.date < self.date_start or entry.date > self.date_end:
continue
month = (entry.date.year, entry.date.month)
# TODO domwe handle no transaction in a month?
all_months.add(month)
# TODO
contains_budget_accounts = False
for posting in entry.postings:
if any(
regexp.match(posting.account)
for regexp in self.budget_accounts
):
contains_budget_accounts = True
break
if not contains_budget_accounts:
continue
for posting in entry.postings:
account = posting.account
for regexp, target_account in self.mappings:
if regexp.match(account):
account = target_account
break
account_type = account_types.get_account_type(account)
if posting.units.currency != self.currency:
orig = posting.units.number
if posting.price is not None:
converted = posting.price.number * orig
posting = data.Posting(
posting.account,
amount.Amount(converted, self.currency),
posting.cost,
None,
posting.flag,
posting.meta,
)
else:
continue
if account_type == self.acctypes.income or (
any(
regexp.match(account)
for regexp in self.income_accounts
)
):
account = "Income"
elif any(
regexp.match(posting.account)
for regexp in self.budget_accounts
):
continue
# TODO WARn of any assets / liabilities left
# TODO
balances[account][month].add_position(posting)
# Reduce the final balances to numbers
sbalances = collections.defaultdict(dict)
for account, months in sorted(balances.items()):
for month, balance in sorted(months.items()):
year, mth = month
date = datetime.date(year, mth, 1)
balance = balance.reduce(
convert.get_value, self.price_map, date
)
balance = balance.reduce(
convert.convert_position,
self.currency,
self.price_map,
date,
)
try:
pos = balance.get_only_position()
except AssertionError:
print(balance)
raise
total = pos.units.number if pos and pos.units else None
sbalances[account][month] = total
# Pivot the table
header_months = sorted(all_months)
# header = ["account"]+["{}-{:02d}".format(*m) for m in header_months]
self.income_df.loc["Avail Income", :] = Decimal(0.00)
for account in sorted(sbalances.keys()):
for month in header_months:
total = sbalances[account].get(month, None)
temp = total.quantize(self.Q) if total else 0.00
# swap sign to be more human readable
temp *= -1
month_str = f"{str(month[0])}-{str(month[1]).zfill(2)}"
if account == "Income":
self.income_df.loc["Avail Income", month_str] = Decimal(
temp
)
else:
self.envelope_df.loc[
account, (month_str, "budgeted")
] = Decimal(0.00)
self.envelope_df.loc[
account, (month_str, "activity")
] = Decimal(temp)
self.envelope_df.loc[
account, (month_str, "available")
] = Decimal(0.00)
def _calc_budget_budgeted(self):
# rows = {}
for e in self.entries:
if isinstance(e, Custom) and e.type == self.etype:
if e.values[0].value == "allocate":
month = f"{e.date.year}-{e.date.month:02}"
self.envelope_df.loc[
e.values[1].value, (month, "budgeted")
] = Decimal(e.values[2].value)