id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
3,066
from collections import defaultdict from collections import OrderedDict from beancount.core.data import Transaction from beancount.core.data import Open from beancount.core.data import Close from beancount.core.data import Commodity from beancount.core import account class Transaction(NamedTuple): """ A transaction! This is the main type of object that we manipulate, and the entire reason this whole project exists in the first place, because representing these types of structures with a spreadsheet is difficult. Attributes: meta: See above. date: See above. flag: A single-character string or None. This user-specified string represents some custom/user-defined state of the transaction. You can use this for various purposes. Otherwise common, pre-defined flags are defined under beancount.core.flags, to flags transactions that are automatically generated. payee: A free-form string that identifies the payee, or None, if absent. narration: A free-form string that provides a description for the transaction. All transactions have at least a narration string, this is never None. tags: A set of tag strings (without the '#'), or EMPTY_SET. links: A set of link strings (without the '^'), or EMPTY_SET. postings: A list of Posting instances, the legs of this transaction. See the doc under Posting above. """ meta: Meta date: datetime.date flag: Flag payee: Optional[str] narration: str tags: Set links: Set postings: List[Posting] The provided code snippet includes necessary dependencies for implementing the `get_all_tags` function. Write a Python function `def get_all_tags(entries)` to solve the following problem: Return a list of all the tags seen in the given entries. Args: entries: A list of directive instances. Returns: A set of tag strings. Here is the function: def get_all_tags(entries): """Return a list of all the tags seen in the given entries. Args: entries: A list of directive instances. Returns: A set of tag strings. """ all_tags = set() for entry in entries: if not isinstance(entry, Transaction): continue if entry.tags: all_tags.update(entry.tags) return sorted(all_tags)
Return a list of all the tags seen in the given entries. Args: entries: A list of directive instances. Returns: A set of tag strings.
3,067
from collections import defaultdict from collections import OrderedDict from beancount.core.data import Transaction from beancount.core.data import Open from beancount.core.data import Close from beancount.core.data import Commodity from beancount.core import account class Transaction(NamedTuple): """ A transaction! This is the main type of object that we manipulate, and the entire reason this whole project exists in the first place, because representing these types of structures with a spreadsheet is difficult. Attributes: meta: See above. date: See above. flag: A single-character string or None. This user-specified string represents some custom/user-defined state of the transaction. You can use this for various purposes. Otherwise common, pre-defined flags are defined under beancount.core.flags, to flags transactions that are automatically generated. payee: A free-form string that identifies the payee, or None, if absent. narration: A free-form string that provides a description for the transaction. All transactions have at least a narration string, this is never None. tags: A set of tag strings (without the '#'), or EMPTY_SET. links: A set of link strings (without the '^'), or EMPTY_SET. postings: A list of Posting instances, the legs of this transaction. See the doc under Posting above. """ meta: Meta date: datetime.date flag: Flag payee: Optional[str] narration: str tags: Set links: Set postings: List[Posting] The provided code snippet includes necessary dependencies for implementing the `get_all_payees` function. Write a Python function `def get_all_payees(entries)` to solve the following problem: Return a list of all the unique payees seen in the given entries. Args: entries: A list of directive instances. Returns: A set of payee strings. Here is the function: def get_all_payees(entries): """Return a list of all the unique payees seen in the given entries. Args: entries: A list of directive instances. Returns: A set of payee strings. """ all_payees = set() for entry in entries: if not isinstance(entry, Transaction): continue all_payees.add(entry.payee) all_payees.discard(None) return sorted(all_payees)
Return a list of all the unique payees seen in the given entries. Args: entries: A list of directive instances. Returns: A set of payee strings.
3,068
from collections import defaultdict from collections import OrderedDict from beancount.core.data import Transaction from beancount.core.data import Open from beancount.core.data import Close from beancount.core.data import Commodity from beancount.core import account class Transaction(NamedTuple): """ A transaction! This is the main type of object that we manipulate, and the entire reason this whole project exists in the first place, because representing these types of structures with a spreadsheet is difficult. Attributes: meta: See above. date: See above. flag: A single-character string or None. This user-specified string represents some custom/user-defined state of the transaction. You can use this for various purposes. Otherwise common, pre-defined flags are defined under beancount.core.flags, to flags transactions that are automatically generated. payee: A free-form string that identifies the payee, or None, if absent. narration: A free-form string that provides a description for the transaction. All transactions have at least a narration string, this is never None. tags: A set of tag strings (without the '#'), or EMPTY_SET. links: A set of link strings (without the '^'), or EMPTY_SET. postings: A list of Posting instances, the legs of this transaction. See the doc under Posting above. """ meta: Meta date: datetime.date flag: Flag payee: Optional[str] narration: str tags: Set links: Set postings: List[Posting] The provided code snippet includes necessary dependencies for implementing the `get_all_links` function. Write a Python function `def get_all_links(entries)` to solve the following problem: Return a list of all the links seen in the given entries. Args: entries: A list of directive instances. Returns: A set of links strings. Here is the function: def get_all_links(entries): """Return a list of all the links seen in the given entries. Args: entries: A list of directive instances. Returns: A set of links strings. """ all_links = set() for entry in entries: if not isinstance(entry, Transaction): continue if entry.links: all_links.update(entry.links) return sorted(all_links)
Return a list of all the links seen in the given entries. Args: entries: A list of directive instances. Returns: A set of links strings.
3,069
from collections import defaultdict from collections import OrderedDict from beancount.core.data import Transaction from beancount.core.data import Open from beancount.core.data import Close from beancount.core.data import Commodity from beancount.core import account The provided code snippet includes necessary dependencies for implementing the `get_leveln_parent_accounts` function. Write a Python function `def get_leveln_parent_accounts(account_names, level, nrepeats=0)` to solve the following problem: Return a list of all the unique leaf names at level N in an account hierarchy. Args: account_names: A list of account names (strings) level: The level to cross-cut. 0 is for root accounts. nrepeats: A minimum number of times a leaf is required to be present in the the list of unique account names in order to be returned by this function. Returns: A list of leaf node names. Here is the function: def get_leveln_parent_accounts(account_names, level, nrepeats=0): """Return a list of all the unique leaf names at level N in an account hierarchy. Args: account_names: A list of account names (strings) level: The level to cross-cut. 0 is for root accounts. nrepeats: A minimum number of times a leaf is required to be present in the the list of unique account names in order to be returned by this function. Returns: A list of leaf node names. """ leveldict = defaultdict(int) for account_name in set(account_names): components = account.split(account_name) if level < len(components): leveldict[components[level]] += 1 levels = {level_ for level_, count in leveldict.items() if count > nrepeats} return sorted(levels)
Return a list of all the unique leaf names at level N in an account hierarchy. Args: account_names: A list of account names (strings) level: The level to cross-cut. 0 is for root accounts. nrepeats: A minimum number of times a leaf is required to be present in the the list of unique account names in order to be returned by this function. Returns: A list of leaf node names.
3,070
from collections import defaultdict from collections import OrderedDict from beancount.core.data import Transaction from beancount.core.data import Open from beancount.core.data import Close from beancount.core.data import Commodity from beancount.core import account The provided code snippet includes necessary dependencies for implementing the `get_dict_accounts` function. Write a Python function `def get_dict_accounts(account_names)` to solve the following problem: Return a nested dict of all the unique leaf names. account names are labelled with LABEL=True Args: account_names: An iterable of account names (strings) Returns: A nested OrderedDict of account leafs Here is the function: def get_dict_accounts(account_names): """Return a nested dict of all the unique leaf names. account names are labelled with LABEL=True Args: account_names: An iterable of account names (strings) Returns: A nested OrderedDict of account leafs """ leveldict = OrderedDict() for account_name in account_names: nested_dict = leveldict for component in account.split(account_name): nested_dict = nested_dict.setdefault(component, OrderedDict()) nested_dict[get_dict_accounts.ACCOUNT_LABEL] = True return leveldict
Return a nested dict of all the unique leaf names. account names are labelled with LABEL=True Args: account_names: An iterable of account names (strings) Returns: A nested OrderedDict of account leafs
3,071
from collections import defaultdict from collections import OrderedDict from beancount.core.data import Transaction from beancount.core.data import Open from beancount.core.data import Close from beancount.core.data import Commodity from beancount.core import account The provided code snippet includes necessary dependencies for implementing the `get_min_max_dates` function. Write a Python function `def get_min_max_dates(entries, types=None)` to solve the following problem: Return the minimum and maximum dates in the list of entries. Args: entries: A list of directive instances. types: An optional tuple of types to restrict the entries to. Returns: A pair of datetime.date dates, the minimum and maximum dates seen in the directives. Here is the function: def get_min_max_dates(entries, types=None): """Return the minimum and maximum dates in the list of entries. Args: entries: A list of directive instances. types: An optional tuple of types to restrict the entries to. Returns: A pair of datetime.date dates, the minimum and maximum dates seen in the directives. """ date_first = date_last = None for entry in entries: if types and not isinstance(entry, types): continue date_first = entry.date break for entry in reversed(entries): if types and not isinstance(entry, types): continue date_last = entry.date break return (date_first, date_last)
Return the minimum and maximum dates in the list of entries. Args: entries: A list of directive instances. types: An optional tuple of types to restrict the entries to. Returns: A pair of datetime.date dates, the minimum and maximum dates seen in the directives.
3,072
from collections import defaultdict from collections import OrderedDict from beancount.core.data import Transaction from beancount.core.data import Open from beancount.core.data import Close from beancount.core.data import Commodity from beancount.core import account The provided code snippet includes necessary dependencies for implementing the `get_active_years` function. Write a Python function `def get_active_years(entries)` to solve the following problem: Yield all the years that have at least one entry in them. Args: entries: A list of directive instances. Yields: Unique dates see in the list of directives. Here is the function: def get_active_years(entries): """Yield all the years that have at least one entry in them. Args: entries: A list of directive instances. Yields: Unique dates see in the list of directives. """ seen = set() prev_year = None for entry in entries: year = entry.date.year if year != prev_year: prev_year = year assert year not in seen seen.add(year) yield year
Yield all the years that have at least one entry in them. Args: entries: A list of directive instances. Yields: Unique dates see in the list of directives.
3,073
from collections import defaultdict from collections import OrderedDict from beancount.core.data import Transaction from beancount.core.data import Open from beancount.core.data import Close from beancount.core.data import Commodity from beancount.core import account The provided code snippet includes necessary dependencies for implementing the `get_values_meta` function. Write a Python function `def get_values_meta(name_to_entries_map, *meta_keys, default=None)` to solve the following problem: Get a map of the metadata from a map of entries values. Given a dict of some key to a directive instance (or None), return a mapping of the key to the metadata extracted from each directive, or a default value. This can be used to gather a particular piece of metadata from an accounts map or a commodities map. Args: name_to_entries_map: A dict of something to an entry or None. meta_keys: A list of strings, the keys to fetch from the metadata. default: The default value to use if the metadata is not available or if the value/entry is None. Returns: A mapping of the keys of name_to_entries_map to the values of the 'meta_keys' metadata. If there are multiple 'meta_keys', each value is a tuple of them. On the other hand, if there is only a single one, the value itself is returned. Here is the function: def get_values_meta(name_to_entries_map, *meta_keys, default=None): """Get a map of the metadata from a map of entries values. Given a dict of some key to a directive instance (or None), return a mapping of the key to the metadata extracted from each directive, or a default value. This can be used to gather a particular piece of metadata from an accounts map or a commodities map. Args: name_to_entries_map: A dict of something to an entry or None. meta_keys: A list of strings, the keys to fetch from the metadata. default: The default value to use if the metadata is not available or if the value/entry is None. Returns: A mapping of the keys of name_to_entries_map to the values of the 'meta_keys' metadata. If there are multiple 'meta_keys', each value is a tuple of them. On the other hand, if there is only a single one, the value itself is returned. """ value_map = {} for key, entry in name_to_entries_map.items(): value_list = [] for meta_key in meta_keys: value_list.append(entry.meta.get(meta_key, default) if entry is not None else default) value_map[key] = (value_list[0] if len(meta_keys) == 1 else tuple(value_list)) return value_map
Get a map of the metadata from a map of entries values. Given a dict of some key to a directive instance (or None), return a mapping of the key to the metadata extracted from each directive, or a default value. This can be used to gather a particular piece of metadata from an accounts map or a commodities map. Args: name_to_entries_map: A dict of something to an entry or None. meta_keys: A list of strings, the keys to fetch from the metadata. default: The default value to use if the metadata is not available or if the value/entry is None. Returns: A mapping of the keys of name_to_entries_map to the values of the 'meta_keys' metadata. If there are multiple 'meta_keys', each value is a tuple of them. On the other hand, if there is only a single one, the value itself is returned.
3,074
import collections from collections.abc import Iterable from decimal import Decimal import enum import re from beancount.core.number import ZERO from beancount.core.number import same_sign from beancount.core.amount import Amount from beancount.core.position import Cost from beancount.core.position import Position from beancount.core.position import from_string as position_from_string from beancount.core import convert from beancount.core.display_context import DEFAULT_FORMATTER ZERO = Decimal() The provided code snippet includes necessary dependencies for implementing the `check_invariants` function. Write a Python function `def check_invariants(inv)` to solve the following problem: Check the invariants of the Inventory. Args: inventory: An instance of Inventory. Returns: True if the invariants are respected. Here is the function: def check_invariants(inv): """Check the invariants of the Inventory. Args: inventory: An instance of Inventory. Returns: True if the invariants are respected. """ # Check that all the keys are unique. lots = set((pos.units.currency, pos.cost) for pos in inv) assert len(lots) == len(inv), "Invalid inventory: {}".format(inv) # Check that none of the amounts is zero. for pos in inv: assert pos.units.number != ZERO, "Invalid position size: {}".format(pos)
Check the invariants of the Inventory. Args: inventory: An instance of Inventory. Returns: True if the invariants are respected.
3,075
import re from decimal import Decimal from typing import List, Optional The provided code snippet includes necessary dependencies for implementing the `same_sign` function. Write a Python function `def same_sign(number1, number2)` to solve the following problem: Return true if both numbers have the same sign. Args: number1: An instance of Decimal. number2: An instance of Decimal. Returns: A boolean. Here is the function: def same_sign(number1, number2): """Return true if both numbers have the same sign. Args: number1: An instance of Decimal. number2: An instance of Decimal. Returns: A boolean. """ return (number1 >= 0) == (number2 >= 0)
Return true if both numbers have the same sign. Args: number1: An instance of Decimal. number2: An instance of Decimal. Returns: A boolean.
3,076
import re from decimal import Decimal from typing import List, Optional def auto_quantize(number: Decimal, threshold: float) -> Decimal: """Automatically quantize the number at a given threshold. For example, with a threshold of 0.01, this will convert: 20.899999618530273 20.9 20.290000000000000000000000000000 20.29 110.90 110.9 11.0600004196167 11.06 10.539999961853027 10.54 134.3300018310547 134.33 253.920200000000000000000000000000 253.9202 """ exponent = auto_quantized_exponent(number, threshold) if exponent != number.as_tuple().exponent: quant = TEN ** exponent qnumber = number.quantize(quant).normalize() return qnumber else: return number def num_fractional_digits(number: Decimal) -> int: """Return the number of fractional digits.""" return -number.as_tuple().exponent The provided code snippet includes necessary dependencies for implementing the `infer_quantum_from_list` function. Write a Python function `def infer_quantum_from_list(numbers: List[Decimal], threshold: float=0.01) -> Optional[Decimal]` to solve the following problem: Given a list of numbers from floats, infer the common quantization. For a series of numbers provided as floats, e.g., prices from a price source, we'd like to infer what the right quantization that should be used to avoid rounding errors above some threshold. from the numbers. This simple algorithm auto-quantizes all the numbers and quantizes all of them at the maximum precision that would result in rounding under the threshold. Args: prices: A list of float or Decimal prices to infer from. If floats are provided, conversion is done naively. threshold: A fraction, the maximum error to tolerate before stopping the search. Returns: A decimal object to use with decimal.Decimal.quantize(). Here is the function: def infer_quantum_from_list(numbers: List[Decimal], threshold: float=0.01) -> Optional[Decimal]: """Given a list of numbers from floats, infer the common quantization. For a series of numbers provided as floats, e.g., prices from a price source, we'd like to infer what the right quantization that should be used to avoid rounding errors above some threshold. from the numbers. This simple algorithm auto-quantizes all the numbers and quantizes all of them at the maximum precision that would result in rounding under the threshold. Args: prices: A list of float or Decimal prices to infer from. If floats are provided, conversion is done naively. threshold: A fraction, the maximum error to tolerate before stopping the search. Returns: A decimal object to use with decimal.Decimal.quantize(). """ # Auto quantize all the numbers. qnumbers = [auto_quantize(num, threshold) for num in numbers] exponent = max(num_fractional_digits(n) for n in qnumbers) return -exponent
Given a list of numbers from floats, infer the common quantization. For a series of numbers provided as floats, e.g., prices from a price source, we'd like to infer what the right quantization that should be used to avoid rounding errors above some threshold. from the numbers. This simple algorithm auto-quantizes all the numbers and quantizes all of them at the maximum precision that would result in rounding under the threshold. Args: prices: A list of float or Decimal prices to infer from. If floats are provided, conversion is done naively. threshold: A fraction, the maximum error to tolerate before stopping the search. Returns: A decimal object to use with decimal.Decimal.quantize().
3,077
import collections from typing import Optional, Set from beancount.core.number import ONE from beancount.core.number import ZERO from beancount.core.data import Price from beancount.core.data import Currency from beancount.core import data from beancount.utils import misc_utils from beancount.utils import bisect_key class PriceMap(dict): """A price map dictionary. The keys include both the set of forward (base, quote) pairs and their inverse. In order to determine which are the forward pairs, access the 'forward_pairs' attribute Attributes: forward_pairs: A list of (base, quote) keys for the forward pairs. """ __slots__ = ('forward_pairs',) def get_price(price_map, base_quote, date=None): """Return the price as of the given date. If the date is unspecified, return the latest price. Args: price_map: A price map, which is a dict of (base, quote) -> list of (date, number) tuples, as created by build_price_map. base_quote: A pair of strings, the base currency to lookup, and the quote currency to lookup, which expresses which units the base currency is denominated in. This may also just be a string, with a '/' separator. date: A datetime.date instance, the date at which we want the conversion rate. Returns: A pair of (datetime.date, Decimal) instance. If no price information could be found, return (None, None). """ if date is None: return get_latest_price(price_map, base_quote) base_quote = normalize_base_quote(base_quote) # Handle the degenerate case of a currency priced into its own. base, quote = base_quote if quote is None or base == quote: return (None, ONE) try: price_list = _lookup_price_and_inverse(price_map, base_quote) index = bisect_key.bisect_right_with_key(price_list, date, key=lambda x: x[0]) if index == 0: return None, None else: return price_list[index-1] except KeyError: return None, None ZERO = Decimal() ONE = Decimal('1') Currency = str The provided code snippet includes necessary dependencies for implementing the `project` function. Write a Python function `def project(orig_price_map: PriceMap, from_currency: Currency, to_currency: Currency, base_currencies: Optional[Set[Currency]] = None) -> PriceMap` to solve the following problem: Project all prices with a quote currency to another quote currency. Say you have a price for HOOL in USD and you'd like to convert HOOL to CAD. If there aren't any (HOOL, CAD) price pairs in the database it will remain unconverted. Projecting from USD to CAD will compute combined rates and insert corresponding prices over all base currencies (like HOOL). In this example, each of the (HOOL, USD) prices would see an inserted (HOOL, CAD) price inserted at the same date. It is common to make these projections when reducing inventories in a ledger that states multiple operating currency pairs, when for example, one wants to compute total value of a set of accounts in one of those currencies. Please note that: - Even if the target pair has existing entries, projection will still be applied. For example, is there exist some (HOOL, CAD) prices, the projection in the example above will still insert some new price points to it. - However, projected prices colliding existing ones at the same date will not override them. - Projection will fail to insert a new price if the conversion between to and from currencies has no existing prices (e.g. before its first price entry). - Perhaps most importantly, we only insert price points at dates where the base commodity has a price point. In other words, if we have prices for dates A and C and the rate changes between these dates at date B, we don't synthesize a new price at date B. A more accurate method to get projected prices that takes into account varying rates is to do multiple lookups. We'll eventually add a method to query it via a specified list of intermediate pairs. {c1bd24f8d4b7} Args: orig_price_map: An existing price map. from_currency: The quote currency with existing project points (e.g., USD). to_currency: The quote currency to insert price points for (e.g., CAD). base_currencies: An optional set of commodities to restrict the projections to (e.g., {HOOL}). Returns: A new price map, with the extra projected prices. The original price map is kept intact. Here is the function: def project(orig_price_map: PriceMap, from_currency: Currency, to_currency: Currency, base_currencies: Optional[Set[Currency]] = None) -> PriceMap: """Project all prices with a quote currency to another quote currency. Say you have a price for HOOL in USD and you'd like to convert HOOL to CAD. If there aren't any (HOOL, CAD) price pairs in the database it will remain unconverted. Projecting from USD to CAD will compute combined rates and insert corresponding prices over all base currencies (like HOOL). In this example, each of the (HOOL, USD) prices would see an inserted (HOOL, CAD) price inserted at the same date. It is common to make these projections when reducing inventories in a ledger that states multiple operating currency pairs, when for example, one wants to compute total value of a set of accounts in one of those currencies. Please note that: - Even if the target pair has existing entries, projection will still be applied. For example, is there exist some (HOOL, CAD) prices, the projection in the example above will still insert some new price points to it. - However, projected prices colliding existing ones at the same date will not override them. - Projection will fail to insert a new price if the conversion between to and from currencies has no existing prices (e.g. before its first price entry). - Perhaps most importantly, we only insert price points at dates where the base commodity has a price point. In other words, if we have prices for dates A and C and the rate changes between these dates at date B, we don't synthesize a new price at date B. A more accurate method to get projected prices that takes into account varying rates is to do multiple lookups. We'll eventually add a method to query it via a specified list of intermediate pairs. {c1bd24f8d4b7} Args: orig_price_map: An existing price map. from_currency: The quote currency with existing project points (e.g., USD). to_currency: The quote currency to insert price points for (e.g., CAD). base_currencies: An optional set of commodities to restrict the projections to (e.g., {HOOL}). Returns: A new price map, with the extra projected prices. The original price map is kept intact. """ # If nothing is requested, return the original map. if from_currency == to_currency: return orig_price_map # Avoid mutating the input map. price_map = {key: list(value) for key, value in orig_price_map.items()} # Process the entire database (it's not indexed by quote currency). currency_pair = (from_currency, to_currency) for base_quote, prices in list(price_map.items()): # Filter just the currencies to convert. base, quote = base_quote if quote != from_currency: continue # Skip currencies not requested if a constraint has been provided. # {4bb702d82c8a} if base_currencies and base not in base_currencies: continue # Create a mapping of existing prices so we can avoid date collisions. existing_prices = ({date for date, _ in price_map[(base, to_currency)]} if (base, to_currency) in price_map else set()) # Project over each of the prices. new_projected = [] for date, price in prices: rate_date, rate = get_price(price_map, currency_pair, date) if rate is None: # There is no conversion rate at this time; skip projection. # {b2b23353275d}. continue if rate_date in existing_prices: # Skip collisions in date. {97a5703ac517} continue # Append the new rate. new_price = price * rate new_projected.append((date, new_price)) # Make sure the resulting lists are sorted. if new_projected: projected = price_map.setdefault((base, to_currency), []) projected.extend(new_projected) projected.sort() inverted = price_map.setdefault((to_currency, base), []) inverted.extend((date, ZERO if rate == ZERO else ONE/rate) for date, rate in new_projected) inverted.sort() return price_map
Project all prices with a quote currency to another quote currency. Say you have a price for HOOL in USD and you'd like to convert HOOL to CAD. If there aren't any (HOOL, CAD) price pairs in the database it will remain unconverted. Projecting from USD to CAD will compute combined rates and insert corresponding prices over all base currencies (like HOOL). In this example, each of the (HOOL, USD) prices would see an inserted (HOOL, CAD) price inserted at the same date. It is common to make these projections when reducing inventories in a ledger that states multiple operating currency pairs, when for example, one wants to compute total value of a set of accounts in one of those currencies. Please note that: - Even if the target pair has existing entries, projection will still be applied. For example, is there exist some (HOOL, CAD) prices, the projection in the example above will still insert some new price points to it. - However, projected prices colliding existing ones at the same date will not override them. - Projection will fail to insert a new price if the conversion between to and from currencies has no existing prices (e.g. before its first price entry). - Perhaps most importantly, we only insert price points at dates where the base commodity has a price point. In other words, if we have prices for dates A and C and the rate changes between these dates at date B, we don't synthesize a new price at date B. A more accurate method to get projected prices that takes into account varying rates is to do multiple lookups. We'll eventually add a method to query it via a specified list of intermediate pairs. {c1bd24f8d4b7} Args: orig_price_map: An existing price map. from_currency: The quote currency with existing project points (e.g., USD). to_currency: The quote currency to insert price points for (e.g., CAD). base_currencies: An optional set of commodities to restrict the projections to (e.g., {HOOL}). Returns: A new price map, with the extra projected prices. The original price map is kept intact.
3,078
import collections from typing import Optional, Set from beancount.core.number import ONE from beancount.core.number import ZERO from beancount.core.data import Price from beancount.core.data import Currency from beancount.core import data from beancount.utils import misc_utils from beancount.utils import bisect_key def normalize_base_quote(base_quote): """Convert a slash-separated string to a pair of strings. Args: base_quote: A pair of strings, the base currency to lookup, and the quote currency to lookup, which expresses which units the base currency is denominated in. This may also just be a string, with a '/' separator. Returns: A pair of strings. """ if isinstance(base_quote, str): base_quote_norm = tuple(base_quote.split('/')) assert len(base_quote_norm) == 2, base_quote base_quote = base_quote_norm assert isinstance(base_quote, tuple), base_quote return base_quote def _lookup_price_and_inverse(price_map, base_quote): """Lookup the (base, quote) tuple in the price map and its inverse. If not found, raise an appropriate exception. Note: this is meant to be an INTERNAL helper function, use the get_* functions to obtain values from a price_map object. Args: price_map: A price map, which is a dict of (base, quote) -> list of (date, number) tuples, as created by build_price_map. base_quote: A pair of strings, (base, quote) currencies. No normalization is done. Returns: A list of price-dates, if successful. Raises: KeyError: If the base_quote and its inverse both weren't able to be looked up. """ try: return price_map[base_quote] except KeyError as exc: base, quote = base_quote prices = price_map.get((quote, base), None) if prices: return prices else: raise The provided code snippet includes necessary dependencies for implementing the `get_all_prices` function. Write a Python function `def get_all_prices(price_map, base_quote)` to solve the following problem: Return a sorted list of all (date, number) price pairs. Args: price_map: A price map, which is a dict of (base, quote) -> list of (date, number) tuples, as created by build_price_map. base_quote: A pair of strings, the base currency to lookup, and the quote currency to lookup, which expresses which units the base currency is denominated in. This may also just be a string, with a '/' separator. Returns: A list of (date, Decimal) pairs, sorted by date. Raises: KeyError: If the base/quote could not be found. Here is the function: def get_all_prices(price_map, base_quote): """Return a sorted list of all (date, number) price pairs. Args: price_map: A price map, which is a dict of (base, quote) -> list of (date, number) tuples, as created by build_price_map. base_quote: A pair of strings, the base currency to lookup, and the quote currency to lookup, which expresses which units the base currency is denominated in. This may also just be a string, with a '/' separator. Returns: A list of (date, Decimal) pairs, sorted by date. Raises: KeyError: If the base/quote could not be found. """ base_quote = normalize_base_quote(base_quote) return _lookup_price_and_inverse(price_map, base_quote)
Return a sorted list of all (date, number) price pairs. Args: price_map: A price map, which is a dict of (base, quote) -> list of (date, number) tuples, as created by build_price_map. base_quote: A pair of strings, the base currency to lookup, and the quote currency to lookup, which expresses which units the base currency is denominated in. This may also just be a string, with a '/' separator. Returns: A list of (date, Decimal) pairs, sorted by date. Raises: KeyError: If the base/quote could not be found.
3,079
import collections import hashlib from beancount.core.data import Price from beancount.core import data def hash_entries(entries, exclude_meta=False): """Compute unique hashes of each of the entries and return a map of them. This is used for comparisons between sets of entries. Args: entries: A list of directives. exclude_meta: If set, exclude the metadata from the hash. Use this for unit tests comparing entries coming from different sources as the filename and lineno will be distinct. However, when you're using the hashes to uniquely identify transactions, you want to include the filenames and line numbers (the default). Returns: A dict of hash-value to entry (for all entries) and a list of errors. Errors are created when duplicate entries are found. """ entry_hash_dict = {} errors = [] num_legal_duplicates = 0 for entry in entries: hash_ = hash_entry(entry, exclude_meta) if hash_ in entry_hash_dict: if isinstance(entry, Price): # Note: Allow duplicate Price entries, they should be common # because of the nature of stock markets (if they're closed, the # data source is likely to return an entry for the previously # available date, which may already have been fetched). num_legal_duplicates += 1 else: other_entry = entry_hash_dict[hash_] errors.append( CompareError(entry.meta, "Duplicate entry: {} == {}".format(entry, other_entry), entry)) entry_hash_dict[hash_] = entry if not errors: assert len(entry_hash_dict) + num_legal_duplicates == len(entries), ( len(entry_hash_dict), len(entries), num_legal_duplicates) return entry_hash_dict, errors The provided code snippet includes necessary dependencies for implementing the `includes_entries` function. Write a Python function `def includes_entries(subset_entries, entries)` to solve the following problem: Check if a list of entries is included in another list. Args: subset_entries: The set of entries to look for in 'entries'. entries: The larger list of entries that could include 'subset_entries'. Returns: A boolean and a list of missing entries. Raises: ValueError: If a duplicate entry is found. Here is the function: def includes_entries(subset_entries, entries): """Check if a list of entries is included in another list. Args: subset_entries: The set of entries to look for in 'entries'. entries: The larger list of entries that could include 'subset_entries'. Returns: A boolean and a list of missing entries. Raises: ValueError: If a duplicate entry is found. """ subset_hashes, subset_errors = hash_entries(subset_entries, exclude_meta=True) subset_keys = set(subset_hashes.keys()) hashes, errors = hash_entries(entries, exclude_meta=True) keys = set(hashes.keys()) if subset_errors or errors: error = (subset_errors + errors)[0] raise ValueError(str(error)) includes = subset_keys.issubset(keys) missing = data.sorted([subset_hashes[key] for key in subset_keys - keys]) return (includes, missing)
Check if a list of entries is included in another list. Args: subset_entries: The set of entries to look for in 'entries'. entries: The larger list of entries that could include 'subset_entries'. Returns: A boolean and a list of missing entries. Raises: ValueError: If a duplicate entry is found.
3,080
import collections import hashlib from beancount.core.data import Price from beancount.core import data def hash_entries(entries, exclude_meta=False): """Compute unique hashes of each of the entries and return a map of them. This is used for comparisons between sets of entries. Args: entries: A list of directives. exclude_meta: If set, exclude the metadata from the hash. Use this for unit tests comparing entries coming from different sources as the filename and lineno will be distinct. However, when you're using the hashes to uniquely identify transactions, you want to include the filenames and line numbers (the default). Returns: A dict of hash-value to entry (for all entries) and a list of errors. Errors are created when duplicate entries are found. """ entry_hash_dict = {} errors = [] num_legal_duplicates = 0 for entry in entries: hash_ = hash_entry(entry, exclude_meta) if hash_ in entry_hash_dict: if isinstance(entry, Price): # Note: Allow duplicate Price entries, they should be common # because of the nature of stock markets (if they're closed, the # data source is likely to return an entry for the previously # available date, which may already have been fetched). num_legal_duplicates += 1 else: other_entry = entry_hash_dict[hash_] errors.append( CompareError(entry.meta, "Duplicate entry: {} == {}".format(entry, other_entry), entry)) entry_hash_dict[hash_] = entry if not errors: assert len(entry_hash_dict) + num_legal_duplicates == len(entries), ( len(entry_hash_dict), len(entries), num_legal_duplicates) return entry_hash_dict, errors The provided code snippet includes necessary dependencies for implementing the `excludes_entries` function. Write a Python function `def excludes_entries(subset_entries, entries)` to solve the following problem: Check that a list of entries does not appear in another list. Args: subset_entries: The set of entries to look for in 'entries'. entries: The larger list of entries that should not include 'subset_entries'. Returns: A boolean and a list of entries that are not supposed to appear. Raises: ValueError: If a duplicate entry is found. Here is the function: def excludes_entries(subset_entries, entries): """Check that a list of entries does not appear in another list. Args: subset_entries: The set of entries to look for in 'entries'. entries: The larger list of entries that should not include 'subset_entries'. Returns: A boolean and a list of entries that are not supposed to appear. Raises: ValueError: If a duplicate entry is found. """ subset_hashes, subset_errors = hash_entries(subset_entries, exclude_meta=True) subset_keys = set(subset_hashes.keys()) hashes, errors = hash_entries(entries, exclude_meta=True) keys = set(hashes.keys()) if subset_errors or errors: error = (subset_errors + errors)[0] raise ValueError(str(error)) intersection = keys.intersection(subset_keys) excludes = not bool(intersection) extra = data.sorted([subset_hashes[key] for key in intersection]) return (excludes, extra)
Check that a list of entries does not appear in another list. Args: subset_entries: The set of entries to look for in 'entries'. entries: The larger list of entries that should not include 'subset_entries'. Returns: A boolean and a list of entries that are not supposed to appear. Raises: ValueError: If a duplicate entry is found.
3,081
from typing import NamedTuple, Tuple, List, Set, Any, Dict from decimal import Decimal import csv import datetime import logging import re import click from beancount.core.number import ONE from beancount.core.number import D from beancount.core import data from beancount.core import account from beancount.core import account_types from beancount.core import getters from beancount.ops import summarize from beancount.core import prices from beancount.parser import options from beancount import loader Table = NamedTuple('Table', [('header', Header), ('rows', Rows)]) def get_metamap_table(metamap: Dict[str, data.Directive], attributes: List[str], getter) -> Table: """Produce a Table of per-commodity attributes.""" header = attributes attrlist = attributes[1:] rows = [] for key, value in metamap.items(): row = [key] for attr in attrlist: row.append(getter(value, attr)) rows.append(row) return Table(attributes, sorted(rows)) def main(filename, currency, ignore_options, dry_run, insert_date, output, output_commodities, output_accounts, output_prices, output_rates, output_postings): # Load the file contents. entries, errors, options_map = loader.load_file(filename) # Initialize main output currency. main_currency = currency or options_map['operating_currency'][0] logging.info("Operating currency: %s", main_currency) # Get the map of commodities to their meta tags. commodities_table = get_commodities_table( entries, ['export', 'assetcls', 'strategy', 'issuer']) if output_commodities is not None: write_table(commodities_table, output_commodities) # Get a table of the commodity names. # # Note: We're fetching the table separately in order to avoid changes to the # spreadsheet upstream, and want to tack on the values as new columns on the # right. names_table = get_commodities_table(entries, ['name']) # Get the map of accounts to their meta tags. accounts_table, accounts_map = get_accounts_table( entries, ['tax', 'liquid']) if output_accounts is not None: write_table(accounts_table, output_accounts) # Enumerate the list of assets. postings_table = get_postings_table(entries, options_map, accounts_map) if output_postings is not None: write_table(postings_table, output_postings) # Get the list of prices. prices_table = get_prices_table(entries, main_currency) if output_prices is not None: write_table(prices_table, output_prices) # Get the list of exchange rates. index = postings_table.header.index('cost_currency') currencies = set(row[index] for row in postings_table.rows) rates_table = get_rates_table(entries, currencies, main_currency) if output_rates is not None: write_table(rates_table, output_rates) # Join all the tables. joined_table = join(postings_table, (('currency',), commodities_table), (('account',), accounts_table), (('currency', 'cost_currency'), prices_table), (('cost_currency',), rates_table), (('currency',), names_table)) # Reorder columns. # We do this in order to avoid having to change the spreadsheet when we add new columns. headers = list(joined_table.header) headers.remove('issuer') headers.append('issuer') final_table = reorder_columns(joined_table, headers) # Filter table removing rows to ignore (rows not to export). index = final_table.header.index('export') rows = [row for row in final_table.rows if row[index] is None or row[index].lower() != 'ignore'] # Filter out options if requested. if ignore_options: index = final_table.header.index('currency') is_option = re.compile(r"[A-Z]+_\d{6,}[CP]\d+", re.I).match rows = [row for row in rows if row[index] is None or not is_option(row[index])] table = Table(final_table.header, rows) if output is not None: if insert_date: table[0][0] += ' ({:%Y-%m-%d %H:%M})'.format(datetime.datetime.now()) write_table(table, output) The provided code snippet includes necessary dependencies for implementing the `get_commodities_table` function. Write a Python function `def get_commodities_table(entries: data.Entries, attributes: List[str]) -> Table` to solve the following problem: Produce a Table of per-commodity attributes. Here is the function: def get_commodities_table(entries: data.Entries, attributes: List[str]) -> Table: """Produce a Table of per-commodity attributes.""" commodities = getters.get_commodity_directives(entries) header = ['currency'] + attributes getter = lambda entry, key: entry.meta.get(key, None) table = get_metamap_table(commodities, header, getter) return table
Produce a Table of per-commodity attributes.
3,082
from typing import NamedTuple, Tuple, List, Set, Any, Dict from decimal import Decimal import csv import datetime import logging import re import click from beancount.core.number import ONE from beancount.core.number import D from beancount.core import data from beancount.core import account from beancount.core import account_types from beancount.core import getters from beancount.ops import summarize from beancount.core import prices from beancount.parser import options from beancount import loader Table = NamedTuple('Table', [('header', Header), ('rows', Rows)]) def get_metamap_table(metamap: Dict[str, data.Directive], attributes: List[str], getter) -> Table: """Produce a Table of per-commodity attributes.""" header = attributes attrlist = attributes[1:] rows = [] for key, value in metamap.items(): row = [key] for attr in attrlist: row.append(getter(value, attr)) rows.append(row) return Table(attributes, sorted(rows)) def main(filename, currency, ignore_options, dry_run, insert_date, output, output_commodities, output_accounts, output_prices, output_rates, output_postings): # Load the file contents. entries, errors, options_map = loader.load_file(filename) # Initialize main output currency. main_currency = currency or options_map['operating_currency'][0] logging.info("Operating currency: %s", main_currency) # Get the map of commodities to their meta tags. commodities_table = get_commodities_table( entries, ['export', 'assetcls', 'strategy', 'issuer']) if output_commodities is not None: write_table(commodities_table, output_commodities) # Get a table of the commodity names. # # Note: We're fetching the table separately in order to avoid changes to the # spreadsheet upstream, and want to tack on the values as new columns on the # right. names_table = get_commodities_table(entries, ['name']) # Get the map of accounts to their meta tags. accounts_table, accounts_map = get_accounts_table( entries, ['tax', 'liquid']) if output_accounts is not None: write_table(accounts_table, output_accounts) # Enumerate the list of assets. postings_table = get_postings_table(entries, options_map, accounts_map) if output_postings is not None: write_table(postings_table, output_postings) # Get the list of prices. prices_table = get_prices_table(entries, main_currency) if output_prices is not None: write_table(prices_table, output_prices) # Get the list of exchange rates. index = postings_table.header.index('cost_currency') currencies = set(row[index] for row in postings_table.rows) rates_table = get_rates_table(entries, currencies, main_currency) if output_rates is not None: write_table(rates_table, output_rates) # Join all the tables. joined_table = join(postings_table, (('currency',), commodities_table), (('account',), accounts_table), (('currency', 'cost_currency'), prices_table), (('cost_currency',), rates_table), (('currency',), names_table)) # Reorder columns. # We do this in order to avoid having to change the spreadsheet when we add new columns. headers = list(joined_table.header) headers.remove('issuer') headers.append('issuer') final_table = reorder_columns(joined_table, headers) # Filter table removing rows to ignore (rows not to export). index = final_table.header.index('export') rows = [row for row in final_table.rows if row[index] is None or row[index].lower() != 'ignore'] # Filter out options if requested. if ignore_options: index = final_table.header.index('currency') is_option = re.compile(r"[A-Z]+_\d{6,}[CP]\d+", re.I).match rows = [row for row in rows if row[index] is None or not is_option(row[index])] table = Table(final_table.header, rows) if output is not None: if insert_date: table[0][0] += ' ({:%Y-%m-%d %H:%M})'.format(datetime.datetime.now()) write_table(table, output) The provided code snippet includes necessary dependencies for implementing the `get_accounts_table` function. Write a Python function `def get_accounts_table(entries: data.Entries, attributes: List[str]) -> Table` to solve the following problem: Produce a Table of per-account attributes. Here is the function: def get_accounts_table(entries: data.Entries, attributes: List[str]) -> Table: """Produce a Table of per-account attributes.""" oc_map = getters.get_account_open_close(entries) accounts_map = {account: dopen for account, (dopen, _) in oc_map.items()} header = ['account'] + attributes defaults = {'tax': 'taxable', 'liquid': False} def getter(entry, key): """Lookup the value working up the accounts tree.""" value = entry.meta.get(key, None) if value is not None: return value account_name = account.parent(entry.account) if not account_name: return defaults.get(key, None) parent_entry = accounts_map.get(account_name, None) if not parent_entry: return defaults.get(key, None) return getter(parent_entry, key) return get_metamap_table(accounts_map, header, getter), accounts_map
Produce a Table of per-account attributes.
3,083
from typing import NamedTuple, Tuple, List, Set, Any, Dict from decimal import Decimal import csv import datetime import logging import re import click from beancount.core.number import ONE from beancount.core.number import D from beancount.core import data from beancount.core import account from beancount.core import account_types from beancount.core import getters from beancount.ops import summarize from beancount.core import prices from beancount.parser import options from beancount import loader Table = NamedTuple('Table', [('header', Header), ('rows', Rows)]) def abbreviate_account(acc: str, accounts_map: Dict[str, data.Open]): """Compute an abbreviated version of the account name.""" # Get the root of the account by inspecting the "root: TRUE" attribute up # the accounts tree. racc = acc while racc: racc = account.parent(racc) dopen = accounts_map.get(racc, None) if dopen and dopen.meta.get('root', False): acc = racc break # Remove the account type. acc = account.sans_root(acc) # Remove the two-letter country code if there is one. if re.match(r'[A-Z][A-Z]', acc): acc = account.sans_root(acc) return acc def main(filename, currency, ignore_options, dry_run, insert_date, output, output_commodities, output_accounts, output_prices, output_rates, output_postings): # Load the file contents. entries, errors, options_map = loader.load_file(filename) # Initialize main output currency. main_currency = currency or options_map['operating_currency'][0] logging.info("Operating currency: %s", main_currency) # Get the map of commodities to their meta tags. commodities_table = get_commodities_table( entries, ['export', 'assetcls', 'strategy', 'issuer']) if output_commodities is not None: write_table(commodities_table, output_commodities) # Get a table of the commodity names. # # Note: We're fetching the table separately in order to avoid changes to the # spreadsheet upstream, and want to tack on the values as new columns on the # right. names_table = get_commodities_table(entries, ['name']) # Get the map of accounts to their meta tags. accounts_table, accounts_map = get_accounts_table( entries, ['tax', 'liquid']) if output_accounts is not None: write_table(accounts_table, output_accounts) # Enumerate the list of assets. postings_table = get_postings_table(entries, options_map, accounts_map) if output_postings is not None: write_table(postings_table, output_postings) # Get the list of prices. prices_table = get_prices_table(entries, main_currency) if output_prices is not None: write_table(prices_table, output_prices) # Get the list of exchange rates. index = postings_table.header.index('cost_currency') currencies = set(row[index] for row in postings_table.rows) rates_table = get_rates_table(entries, currencies, main_currency) if output_rates is not None: write_table(rates_table, output_rates) # Join all the tables. joined_table = join(postings_table, (('currency',), commodities_table), (('account',), accounts_table), (('currency', 'cost_currency'), prices_table), (('cost_currency',), rates_table), (('currency',), names_table)) # Reorder columns. # We do this in order to avoid having to change the spreadsheet when we add new columns. headers = list(joined_table.header) headers.remove('issuer') headers.append('issuer') final_table = reorder_columns(joined_table, headers) # Filter table removing rows to ignore (rows not to export). index = final_table.header.index('export') rows = [row for row in final_table.rows if row[index] is None or row[index].lower() != 'ignore'] # Filter out options if requested. if ignore_options: index = final_table.header.index('currency') is_option = re.compile(r"[A-Z]+_\d{6,}[CP]\d+", re.I).match rows = [row for row in rows if row[index] is None or not is_option(row[index])] table = Table(final_table.header, rows) if output is not None: if insert_date: table[0][0] += ' ({:%Y-%m-%d %H:%M})'.format(datetime.datetime.now()) write_table(table, output) ONE = Decimal('1') def D(strord=None): """Convert a string into a Decimal object. This is used in parsing amounts from files in the importers. This is the main function you should use to build all numbers the system manipulates (never use floating-point in an accounting system). Commas are stripped and ignored, as they are assumed to be thousands separators (the French comma separator as decimal is not supported). This function just returns the argument if it is already a Decimal object, for convenience. Args: strord: A string or Decimal instance. Returns: A Decimal instance. """ try: # Note: try a map lookup and optimize performance here. if strord is None or strord == '': return Decimal() elif isinstance(strord, str): return Decimal(_CLEAN_NUMBER_RE.sub('', strord)) elif isinstance(strord, Decimal): return strord elif isinstance(strord, (int, float)): return Decimal(strord) else: assert strord is None, "Invalid value to convert: {}".format(strord) except Exception as exc: raise ValueError("Impossible to create Decimal instance from {!s}: {}".format( strord, exc)) from exc def summarize(entries, date, account_opening): """Summarize all entries before a date by replacing then with summarization entries. This function replaces the transactions up to (and not including) the given date with a opening balance transactions, one for each account. It returns new entries, all of the transactions before the given date having been replaced by a few summarization entries, one for each account. Notes: - Open entries are preserved for active accounts. - The last relevant price entry for each (base, quote) pair is preserved. - All other entries before the cutoff date are culled. Args: entries: A list of directives. date: A datetime.date instance, the cutoff date before which to summarize. account_opening: A string, the name of the source account to book summarization entries against. Returns: The function returns a list of new entries and the integer index at which the entries on or after the cutoff date begin. """ # Compute balances at date. balances, index = balance_by_account(entries, date) # We need to insert the entries with a date previous to subsequent checks, # to maintain ensure the open directives show up before any transaction. summarize_date = date - datetime.timedelta(days=1) # Create summarization / opening balance entries. summarizing_entries = create_entries_from_balances( balances, summarize_date, account_opening, True, data.new_metadata('<summarize>', 0), flags.FLAG_SUMMARIZE, "Opening balance for '{account}' (Summarization)") # Insert the last price entry for each commodity from before the date. price_entries = prices.get_last_price_entries(entries, date) # Gather the list of active open entries at date. open_entries = get_open_entries(entries, date) # Compute entries before the date and preserve the entries after the date. before_entries = sorted(open_entries + price_entries + summarizing_entries, key=data.entry_sortkey) after_entries = entries[index:] # Return a new list of entries and the index that points after the entries # were inserted. return (before_entries + after_entries), len(before_entries) The provided code snippet includes necessary dependencies for implementing the `get_postings_table` function. Write a Python function `def get_postings_table(entries: data.Entries, options_map: Dict, accounts_map: Dict[str, data.Open], threshold: Decimal = D('0.01')) -> Table` to solve the following problem: Enumerate all the postings. Here is the function: def get_postings_table(entries: data.Entries, options_map: Dict, accounts_map: Dict[str, data.Open], threshold: Decimal = D('0.01')) -> Table: """Enumerate all the postings.""" header = ['account', 'account_abbrev', 'number', 'currency', 'cost_number', 'cost_currency', 'cost_date'] balances, _ = summarize.balance_by_account(entries, compress_unbooked=True) acctypes = options.get_account_types(options_map) rows = [] for acc, balance in sorted(balances.items()): # Keep only the balance sheet accounts. acctype = account_types.get_account_type(acc) if not acctype in (acctypes.assets, acctypes.liabilities): continue # Create a posting for each of the positions. for pos in balance: acc_abbrev = abbreviate_account(acc, accounts_map) row = [acc, acc_abbrev, pos.units.number, pos.units.currency, pos.cost.number if pos.cost else ONE, pos.cost.currency if pos.cost else pos.units.currency, pos.cost.date if pos.cost else None] rows.append(row) return Table(header, rows)
Enumerate all the postings.
3,084
from typing import NamedTuple, Tuple, List, Set, Any, Dict from decimal import Decimal import csv import datetime import logging import re import click from beancount.core.number import ONE from beancount.core.number import D from beancount.core import data from beancount.core import account from beancount.core import account_types from beancount.core import getters from beancount.ops import summarize from beancount.core import prices from beancount.parser import options from beancount import loader Table = NamedTuple('Table', [('header', Header), ('rows', Rows)]) PRICE_Q = D('0.0000001') def main(filename, currency, ignore_options, dry_run, insert_date, output, output_commodities, output_accounts, output_prices, output_rates, output_postings): # Load the file contents. entries, errors, options_map = loader.load_file(filename) # Initialize main output currency. main_currency = currency or options_map['operating_currency'][0] logging.info("Operating currency: %s", main_currency) # Get the map of commodities to their meta tags. commodities_table = get_commodities_table( entries, ['export', 'assetcls', 'strategy', 'issuer']) if output_commodities is not None: write_table(commodities_table, output_commodities) # Get a table of the commodity names. # # Note: We're fetching the table separately in order to avoid changes to the # spreadsheet upstream, and want to tack on the values as new columns on the # right. names_table = get_commodities_table(entries, ['name']) # Get the map of accounts to their meta tags. accounts_table, accounts_map = get_accounts_table( entries, ['tax', 'liquid']) if output_accounts is not None: write_table(accounts_table, output_accounts) # Enumerate the list of assets. postings_table = get_postings_table(entries, options_map, accounts_map) if output_postings is not None: write_table(postings_table, output_postings) # Get the list of prices. prices_table = get_prices_table(entries, main_currency) if output_prices is not None: write_table(prices_table, output_prices) # Get the list of exchange rates. index = postings_table.header.index('cost_currency') currencies = set(row[index] for row in postings_table.rows) rates_table = get_rates_table(entries, currencies, main_currency) if output_rates is not None: write_table(rates_table, output_rates) # Join all the tables. joined_table = join(postings_table, (('currency',), commodities_table), (('account',), accounts_table), (('currency', 'cost_currency'), prices_table), (('cost_currency',), rates_table), (('currency',), names_table)) # Reorder columns. # We do this in order to avoid having to change the spreadsheet when we add new columns. headers = list(joined_table.header) headers.remove('issuer') headers.append('issuer') final_table = reorder_columns(joined_table, headers) # Filter table removing rows to ignore (rows not to export). index = final_table.header.index('export') rows = [row for row in final_table.rows if row[index] is None or row[index].lower() != 'ignore'] # Filter out options if requested. if ignore_options: index = final_table.header.index('currency') is_option = re.compile(r"[A-Z]+_\d{6,}[CP]\d+", re.I).match rows = [row for row in rows if row[index] is None or not is_option(row[index])] table = Table(final_table.header, rows) if output is not None: if insert_date: table[0][0] += ' ({:%Y-%m-%d %H:%M})'.format(datetime.datetime.now()) write_table(table, output) The provided code snippet includes necessary dependencies for implementing the `get_prices_table` function. Write a Python function `def get_prices_table(entries: data.Entries, main_currency: str) -> Table` to solve the following problem: Enumerate all the prices seen. Here is the function: def get_prices_table(entries: data.Entries, main_currency: str) -> Table: """Enumerate all the prices seen.""" price_map = prices.build_price_map(entries) header = ['currency', 'cost_currency', 'price_file'] rows = [] for base_quote in price_map.keys(): _, price = prices.get_latest_price(price_map, base_quote) if price is None: continue base, quote = base_quote rows.append([base, quote, price.quantize(PRICE_Q)]) return Table(header, rows)
Enumerate all the prices seen.
3,085
from typing import NamedTuple, Tuple, List, Set, Any, Dict from decimal import Decimal import csv import datetime import logging import re import click from beancount.core.number import ONE from beancount.core.number import D from beancount.core import data from beancount.core import account from beancount.core import account_types from beancount.core import getters from beancount.ops import summarize from beancount.core import prices from beancount.parser import options from beancount import loader Table = NamedTuple('Table', [('header', Header), ('rows', Rows)]) PRICE_Q = D('0.0000001') def main(filename, currency, ignore_options, dry_run, insert_date, output, output_commodities, output_accounts, output_prices, output_rates, output_postings): # Load the file contents. entries, errors, options_map = loader.load_file(filename) # Initialize main output currency. main_currency = currency or options_map['operating_currency'][0] logging.info("Operating currency: %s", main_currency) # Get the map of commodities to their meta tags. commodities_table = get_commodities_table( entries, ['export', 'assetcls', 'strategy', 'issuer']) if output_commodities is not None: write_table(commodities_table, output_commodities) # Get a table of the commodity names. # # Note: We're fetching the table separately in order to avoid changes to the # spreadsheet upstream, and want to tack on the values as new columns on the # right. names_table = get_commodities_table(entries, ['name']) # Get the map of accounts to their meta tags. accounts_table, accounts_map = get_accounts_table( entries, ['tax', 'liquid']) if output_accounts is not None: write_table(accounts_table, output_accounts) # Enumerate the list of assets. postings_table = get_postings_table(entries, options_map, accounts_map) if output_postings is not None: write_table(postings_table, output_postings) # Get the list of prices. prices_table = get_prices_table(entries, main_currency) if output_prices is not None: write_table(prices_table, output_prices) # Get the list of exchange rates. index = postings_table.header.index('cost_currency') currencies = set(row[index] for row in postings_table.rows) rates_table = get_rates_table(entries, currencies, main_currency) if output_rates is not None: write_table(rates_table, output_rates) # Join all the tables. joined_table = join(postings_table, (('currency',), commodities_table), (('account',), accounts_table), (('currency', 'cost_currency'), prices_table), (('cost_currency',), rates_table), (('currency',), names_table)) # Reorder columns. # We do this in order to avoid having to change the spreadsheet when we add new columns. headers = list(joined_table.header) headers.remove('issuer') headers.append('issuer') final_table = reorder_columns(joined_table, headers) # Filter table removing rows to ignore (rows not to export). index = final_table.header.index('export') rows = [row for row in final_table.rows if row[index] is None or row[index].lower() != 'ignore'] # Filter out options if requested. if ignore_options: index = final_table.header.index('currency') is_option = re.compile(r"[A-Z]+_\d{6,}[CP]\d+", re.I).match rows = [row for row in rows if row[index] is None or not is_option(row[index])] table = Table(final_table.header, rows) if output is not None: if insert_date: table[0][0] += ' ({:%Y-%m-%d %H:%M})'.format(datetime.datetime.now()) write_table(table, output) The provided code snippet includes necessary dependencies for implementing the `get_rates_table` function. Write a Python function `def get_rates_table(entries: data.Entries, currencies: Set[str], main_currency: str) -> Table` to solve the following problem: Enumerate all the exchange rates. Here is the function: def get_rates_table(entries: data.Entries, currencies: Set[str], main_currency: str) -> Table: """Enumerate all the exchange rates.""" price_map = prices.build_price_map(entries) header = ['cost_currency', 'rate_file'] rows = [] for currency in currencies: _, rate = prices.get_latest_price(price_map, (currency, main_currency)) if rate is None: continue rows.append([currency, rate.quantize(PRICE_Q)]) return Table(header, rows)
Enumerate all the exchange rates.
3,086
from typing import NamedTuple, Tuple, List, Set, Any, Dict from decimal import Decimal import csv import datetime import logging import re import click from beancount.core.number import ONE from beancount.core.number import D from beancount.core import data from beancount.core import account from beancount.core import account_types from beancount.core import getters from beancount.ops import summarize from beancount.core import prices from beancount.parser import options from beancount import loader Table = NamedTuple('Table', [('header', Header), ('rows', Rows)]) def main(filename, currency, ignore_options, dry_run, insert_date, output, output_commodities, output_accounts, output_prices, output_rates, output_postings): # Load the file contents. entries, errors, options_map = loader.load_file(filename) # Initialize main output currency. main_currency = currency or options_map['operating_currency'][0] logging.info("Operating currency: %s", main_currency) # Get the map of commodities to their meta tags. commodities_table = get_commodities_table( entries, ['export', 'assetcls', 'strategy', 'issuer']) if output_commodities is not None: write_table(commodities_table, output_commodities) # Get a table of the commodity names. # # Note: We're fetching the table separately in order to avoid changes to the # spreadsheet upstream, and want to tack on the values as new columns on the # right. names_table = get_commodities_table(entries, ['name']) # Get the map of accounts to their meta tags. accounts_table, accounts_map = get_accounts_table( entries, ['tax', 'liquid']) if output_accounts is not None: write_table(accounts_table, output_accounts) # Enumerate the list of assets. postings_table = get_postings_table(entries, options_map, accounts_map) if output_postings is not None: write_table(postings_table, output_postings) # Get the list of prices. prices_table = get_prices_table(entries, main_currency) if output_prices is not None: write_table(prices_table, output_prices) # Get the list of exchange rates. index = postings_table.header.index('cost_currency') currencies = set(row[index] for row in postings_table.rows) rates_table = get_rates_table(entries, currencies, main_currency) if output_rates is not None: write_table(rates_table, output_rates) # Join all the tables. joined_table = join(postings_table, (('currency',), commodities_table), (('account',), accounts_table), (('currency', 'cost_currency'), prices_table), (('cost_currency',), rates_table), (('currency',), names_table)) # Reorder columns. # We do this in order to avoid having to change the spreadsheet when we add new columns. headers = list(joined_table.header) headers.remove('issuer') headers.append('issuer') final_table = reorder_columns(joined_table, headers) # Filter table removing rows to ignore (rows not to export). index = final_table.header.index('export') rows = [row for row in final_table.rows if row[index] is None or row[index].lower() != 'ignore'] # Filter out options if requested. if ignore_options: index = final_table.header.index('currency') is_option = re.compile(r"[A-Z]+_\d{6,}[CP]\d+", re.I).match rows = [row for row in rows if row[index] is None or not is_option(row[index])] table = Table(final_table.header, rows) if output is not None: if insert_date: table[0][0] += ' ({:%Y-%m-%d %H:%M})'.format(datetime.datetime.now()) write_table(table, output) The provided code snippet includes necessary dependencies for implementing the `join` function. Write a Python function `def join(main_table: Table, *col_tables: Tuple[Tuple[Tuple[str], Table]]) -> Table` to solve the following problem: Join a table with a number of other tables. col_tables is a tuple of (column, table) pairs. Here is the function: def join(main_table: Table, *col_tables: Tuple[Tuple[Tuple[str], Table]]) -> Table: """Join a table with a number of other tables. col_tables is a tuple of (column, table) pairs.""" new_header = list(main_table.header) for cols, col_table in col_tables: header = list(col_table.header) for col in cols: assert col in main_table.header header.remove(col) new_header.extend(header) col_maps = [] for cols, col_table in col_tables: indexes_main = [main_table.header.index(col) for col in cols] indexes_col = [col_table.header.index(col) for col in cols] #indexes_notcol = sorted(set(range(len(col_table.header))) - set(indexes_col)) col_map = {} for row in col_table.rows: key = tuple(row[index] for index in indexes_col) col_map[key] = row assert len(col_map) == len(col_table.rows), cols col_maps.append((indexes_main, indexes_col, col_map)) rows = [] for row in main_table.rows: row = list(row) empty_row = [None] * (len(col_table.header) - len(indexes_col)) for indexes_main, indexes_col, col_map in col_maps: key = tuple(row[index] for index in indexes_main) other_row = col_map.get(key, None) if other_row is not None: other_row = list(other_row) for index in reversed(indexes_col): del other_row[index] else: other_row = empty_row row.extend(other_row) rows.append(row) return Table(new_header, rows)
Join a table with a number of other tables. col_tables is a tuple of (column, table) pairs.
3,087
from typing import NamedTuple, Tuple, List, Set, Any, Dict from decimal import Decimal import csv import datetime import logging import re import click from beancount.core.number import ONE from beancount.core.number import D from beancount.core import data from beancount.core import account from beancount.core import account_types from beancount.core import getters from beancount.ops import summarize from beancount.core import prices from beancount.parser import options from beancount import loader Table = NamedTuple('Table', [('header', Header), ('rows', Rows)]) def main(filename, currency, ignore_options, dry_run, insert_date, output, output_commodities, output_accounts, output_prices, output_rates, output_postings): # Load the file contents. entries, errors, options_map = loader.load_file(filename) # Initialize main output currency. main_currency = currency or options_map['operating_currency'][0] logging.info("Operating currency: %s", main_currency) # Get the map of commodities to their meta tags. commodities_table = get_commodities_table( entries, ['export', 'assetcls', 'strategy', 'issuer']) if output_commodities is not None: write_table(commodities_table, output_commodities) # Get a table of the commodity names. # # Note: We're fetching the table separately in order to avoid changes to the # spreadsheet upstream, and want to tack on the values as new columns on the # right. names_table = get_commodities_table(entries, ['name']) # Get the map of accounts to their meta tags. accounts_table, accounts_map = get_accounts_table( entries, ['tax', 'liquid']) if output_accounts is not None: write_table(accounts_table, output_accounts) # Enumerate the list of assets. postings_table = get_postings_table(entries, options_map, accounts_map) if output_postings is not None: write_table(postings_table, output_postings) # Get the list of prices. prices_table = get_prices_table(entries, main_currency) if output_prices is not None: write_table(prices_table, output_prices) # Get the list of exchange rates. index = postings_table.header.index('cost_currency') currencies = set(row[index] for row in postings_table.rows) rates_table = get_rates_table(entries, currencies, main_currency) if output_rates is not None: write_table(rates_table, output_rates) # Join all the tables. joined_table = join(postings_table, (('currency',), commodities_table), (('account',), accounts_table), (('currency', 'cost_currency'), prices_table), (('cost_currency',), rates_table), (('currency',), names_table)) # Reorder columns. # We do this in order to avoid having to change the spreadsheet when we add new columns. headers = list(joined_table.header) headers.remove('issuer') headers.append('issuer') final_table = reorder_columns(joined_table, headers) # Filter table removing rows to ignore (rows not to export). index = final_table.header.index('export') rows = [row for row in final_table.rows if row[index] is None or row[index].lower() != 'ignore'] # Filter out options if requested. if ignore_options: index = final_table.header.index('currency') is_option = re.compile(r"[A-Z]+_\d{6,}[CP]\d+", re.I).match rows = [row for row in rows if row[index] is None or not is_option(row[index])] table = Table(final_table.header, rows) if output is not None: if insert_date: table[0][0] += ' ({:%Y-%m-%d %H:%M})'.format(datetime.datetime.now()) write_table(table, output) The provided code snippet includes necessary dependencies for implementing the `reorder_columns` function. Write a Python function `def reorder_columns(table: Table, new_headers: List[str]) -> Table` to solve the following problem: Reorder the columns of a table to a desired new headers. Here is the function: def reorder_columns(table: Table, new_headers: List[str]) -> Table: """Reorder the columns of a table to a desired new headers.""" assert len(table.header) == len(new_headers) indexes = [table.header.index(header) for header in new_headers] rows = [[row[index] for index in indexes] for row in table.rows] return Table(new_headers, rows)
Reorder the columns of a table to a desired new headers.
3,088
from typing import NamedTuple, Tuple, List, Set, Any, Dict from decimal import Decimal import csv import datetime import logging import re import click from beancount.core.number import ONE from beancount.core.number import D from beancount.core import data from beancount.core import account from beancount.core import account_types from beancount.core import getters from beancount.ops import summarize from beancount.core import prices from beancount.parser import options from beancount import loader Table = NamedTuple('Table', [('header', Header), ('rows', Rows)]) def main(filename, currency, ignore_options, dry_run, insert_date, output, output_commodities, output_accounts, output_prices, output_rates, output_postings): # Load the file contents. entries, errors, options_map = loader.load_file(filename) # Initialize main output currency. main_currency = currency or options_map['operating_currency'][0] logging.info("Operating currency: %s", main_currency) # Get the map of commodities to their meta tags. commodities_table = get_commodities_table( entries, ['export', 'assetcls', 'strategy', 'issuer']) if output_commodities is not None: write_table(commodities_table, output_commodities) # Get a table of the commodity names. # # Note: We're fetching the table separately in order to avoid changes to the # spreadsheet upstream, and want to tack on the values as new columns on the # right. names_table = get_commodities_table(entries, ['name']) # Get the map of accounts to their meta tags. accounts_table, accounts_map = get_accounts_table( entries, ['tax', 'liquid']) if output_accounts is not None: write_table(accounts_table, output_accounts) # Enumerate the list of assets. postings_table = get_postings_table(entries, options_map, accounts_map) if output_postings is not None: write_table(postings_table, output_postings) # Get the list of prices. prices_table = get_prices_table(entries, main_currency) if output_prices is not None: write_table(prices_table, output_prices) # Get the list of exchange rates. index = postings_table.header.index('cost_currency') currencies = set(row[index] for row in postings_table.rows) rates_table = get_rates_table(entries, currencies, main_currency) if output_rates is not None: write_table(rates_table, output_rates) # Join all the tables. joined_table = join(postings_table, (('currency',), commodities_table), (('account',), accounts_table), (('currency', 'cost_currency'), prices_table), (('cost_currency',), rates_table), (('currency',), names_table)) # Reorder columns. # We do this in order to avoid having to change the spreadsheet when we add new columns. headers = list(joined_table.header) headers.remove('issuer') headers.append('issuer') final_table = reorder_columns(joined_table, headers) # Filter table removing rows to ignore (rows not to export). index = final_table.header.index('export') rows = [row for row in final_table.rows if row[index] is None or row[index].lower() != 'ignore'] # Filter out options if requested. if ignore_options: index = final_table.header.index('currency') is_option = re.compile(r"[A-Z]+_\d{6,}[CP]\d+", re.I).match rows = [row for row in rows if row[index] is None or not is_option(row[index])] table = Table(final_table.header, rows) if output is not None: if insert_date: table[0][0] += ' ({:%Y-%m-%d %H:%M})'.format(datetime.datetime.now()) write_table(table, output) The provided code snippet includes necessary dependencies for implementing the `write_table` function. Write a Python function `def write_table(table: Table, outfile: str)` to solve the following problem: Write a table to a CSV file. Here is the function: def write_table(table: Table, outfile: str): """Write a table to a CSV file.""" writer = csv.writer(outfile) writer.writerow(table.header) writer.writerows(table.rows)
Write a table to a CSV file.
3,089
import collections from beancount.core import account from beancount.core import amount from beancount.core import inventory from beancount.core import data from beancount.core import position from beancount.core import flags from beancount.core import realization from beancount.utils import misc_utils from beancount.ops import balance PadError = collections.namedtuple('PadError', 'source message entry') The provided code snippet includes necessary dependencies for implementing the `pad` function. Write a Python function `def pad(entries, options_map)` to solve the following problem: Insert transaction entries for to fulfill a subsequent balance check. Synthesize and insert Transaction entries right after Pad entries in order to fulfill checks in the padded accounts. Returns a new list of entries. Note that this doesn't pad across parent-child relationships, it is a very simple kind of pad. (I have found this to be sufficient in practice, and simpler to implement and understand.) Furthermore, this pads for a single currency only, that is, balance checks are specified only for one currency at a time, and pads will only be inserted for those currencies. Args: entries: A list of directives. options_map: A parser options dict. Returns: A new list of directives, with Pad entries inserted, and a list of new errors produced. Here is the function: def pad(entries, options_map): """Insert transaction entries for to fulfill a subsequent balance check. Synthesize and insert Transaction entries right after Pad entries in order to fulfill checks in the padded accounts. Returns a new list of entries. Note that this doesn't pad across parent-child relationships, it is a very simple kind of pad. (I have found this to be sufficient in practice, and simpler to implement and understand.) Furthermore, this pads for a single currency only, that is, balance checks are specified only for one currency at a time, and pads will only be inserted for those currencies. Args: entries: A list of directives. options_map: A parser options dict. Returns: A new list of directives, with Pad entries inserted, and a list of new errors produced. """ pad_errors = [] # Find all the pad entries and group them by account. pads = list(misc_utils.filter_type(entries, data.Pad)) pad_dict = misc_utils.groupby(lambda x: x.account, pads) # Partially realize the postings, so we can iterate them by account. by_account = realization.postings_by_account(entries) # A dict of pad -> list of entries to be inserted. new_entries = {id(pad): [] for pad in pads} # Process each account that has a padding group. for account_, pad_list in sorted(pad_dict.items()): # Last encountered / currency active pad entry. active_pad = None # Gather all the postings for the account and its children. postings = [] is_child = account.parent_matcher(account_) for item_account, item_postings in by_account.items(): if is_child(item_account): postings.extend(item_postings) postings.sort(key=data.posting_sortkey) # A set of currencies already padded so far in this account. padded_lots = set() pad_balance = inventory.Inventory() for entry in postings: assert not isinstance(entry, data.Posting) if isinstance(entry, data.TxnPosting): # This is a transaction; update the running balance for this # account. pad_balance.add_position(entry.posting) elif isinstance(entry, data.Pad): if entry.account == account_: # Mark this newly encountered pad as active and allow all lots # to be padded heretofore. active_pad = entry padded_lots = set() elif isinstance(entry, data.Balance): check_amount = entry.amount # Compare the current balance amount to the expected one from # the check entry. IMPORTANT: You need to understand that this # does not check a single position, but rather checks that the # total amount for a particular currency (which itself is # distinct from the cost). balance_amount = pad_balance.get_currency_units(check_amount.currency) diff_amount = amount.sub(balance_amount, check_amount) # Use the specified tolerance or automatically infer it. tolerance = balance.get_balance_tolerance(entry, options_map) if abs(diff_amount.number) > tolerance: # The check fails; we need to pad. # Pad only if pad entry is active and we haven't already # padded that lot since it was last encountered. if active_pad and (check_amount.currency not in padded_lots): # Note: we decide that it's an error to try to pad # positions at cost; we check here that all the existing # positions with that currency have no cost. positions = [pos for pos in pad_balance.get_positions() if pos.units.currency == check_amount.currency] for position_ in positions: if position_.cost is not None: pad_errors.append( PadError(entry.meta, ("Attempt to pad an entry with cost for " "balance: {}".format(pad_balance)), active_pad)) # Thus our padding lot is without cost by default. diff_position = position.Position.from_amounts( amount.Amount(check_amount.number - balance_amount.number, check_amount.currency)) # Synthesize a new transaction entry for the difference. narration = ('(Padding inserted for Balance of {} for ' 'difference {})').format(check_amount, diff_position) new_entry = data.Transaction( active_pad.meta.copy(), active_pad.date, flags.FLAG_PADDING, None, narration, data.EMPTY_SET, data.EMPTY_SET, []) new_entry.postings.append( data.Posting(active_pad.account, diff_position.units, diff_position.cost, None, None, None)) neg_diff_position = -diff_position new_entry.postings.append( data.Posting(active_pad.source_account, neg_diff_position.units, neg_diff_position.cost, None, None, None)) # Save it for later insertion after the active pad. new_entries[id(active_pad)].append(new_entry) # Fixup the running balance. pos, _ = pad_balance.add_position(diff_position) if pos is not None and pos.is_negative_at_cost(): raise ValueError( "Position held at cost goes negative: {}".format(pos)) # Mark this lot as padded. Further checks should not pad this lot. padded_lots.add(check_amount.currency) # Insert the newly created entries right after the pad entries that created them. padded_entries = [] for entry in entries: padded_entries.append(entry) if isinstance(entry, data.Pad): entry_list = new_entries[id(entry)] if entry_list: padded_entries.extend(entry_list) else: # Generate errors on unused pad entries. pad_errors.append( PadError(entry.meta, "Unused Pad entry", entry)) return padded_entries, pad_errors
Insert transaction entries for to fulfill a subsequent balance check. Synthesize and insert Transaction entries right after Pad entries in order to fulfill checks in the padded accounts. Returns a new list of entries. Note that this doesn't pad across parent-child relationships, it is a very simple kind of pad. (I have found this to be sufficient in practice, and simpler to implement and understand.) Furthermore, this pads for a single currency only, that is, balance checks are specified only for one currency at a time, and pads will only be inserted for those currencies. Args: entries: A list of directives. options_map: A parser options dict. Returns: A new list of directives, with Pad entries inserted, and a list of new errors produced.
3,090
from collections import defaultdict from beancount.core import data The provided code snippet includes necessary dependencies for implementing the `filter_tag` function. Write a Python function `def filter_tag(tag, entries)` to solve the following problem: Yield all the entries which have the given tag. Args: tag: A string, the tag we are interested in. Yields: Every entry in 'entries' that tags to 'tag. Here is the function: def filter_tag(tag, entries): """Yield all the entries which have the given tag. Args: tag: A string, the tag we are interested in. Yields: Every entry in 'entries' that tags to 'tag. """ for entry in entries: if (isinstance(entry, data.Transaction) and entry.tags and tag in entry.tags): yield entry
Yield all the entries which have the given tag. Args: tag: A string, the tag we are interested in. Yields: Every entry in 'entries' that tags to 'tag.
3,091
from collections import defaultdict from beancount.core import data The provided code snippet includes necessary dependencies for implementing the `filter_link` function. Write a Python function `def filter_link(link, entries)` to solve the following problem: Yield all the entries which have the given link. Args: link: A string, the link we are interested in. Yields: Every entry in 'entries' that links to 'link. Here is the function: def filter_link(link, entries): """Yield all the entries which have the given link. Args: link: A string, the link we are interested in. Yields: Every entry in 'entries' that links to 'link. """ for entry in entries: if (isinstance(entry, data.Transaction) and entry.links and link in entry.links): yield entry
Yield all the entries which have the given link. Args: link: A string, the link we are interested in. Yields: Every entry in 'entries' that links to 'link.
3,092
from collections import defaultdict from beancount.core import data The provided code snippet includes necessary dependencies for implementing the `group_entries_by_link` function. Write a Python function `def group_entries_by_link(entries)` to solve the following problem: Group the list of entries by link. Args: entries: A list of directives/transactions to process. Returns: A dict of link-name to list of entries. Here is the function: def group_entries_by_link(entries): """Group the list of entries by link. Args: entries: A list of directives/transactions to process. Returns: A dict of link-name to list of entries. """ link_groups = defaultdict(list) for entry in entries: if not (isinstance(entry, data.Transaction) and entry.links): continue for link in entry.links: link_groups[link].append(entry) return link_groups
Group the list of entries by link. Args: entries: A list of directives/transactions to process. Returns: A dict of link-name to list of entries.
3,093
from collections import defaultdict from beancount.core import data The provided code snippet includes necessary dependencies for implementing the `get_common_accounts` function. Write a Python function `def get_common_accounts(entries)` to solve the following problem: Compute the intersection of the accounts on the given entries. Args: entries: A list of Transaction entries to process. Returns: A set of strings, the names of the common accounts from these entries. Here is the function: def get_common_accounts(entries): """Compute the intersection of the accounts on the given entries. Args: entries: A list of Transaction entries to process. Returns: A set of strings, the names of the common accounts from these entries. """ assert all(isinstance(entry, data.Transaction) for entry in entries) # If there is a single entry, the common accounts to it is all its accounts. # Note that this also works with no entries (yields an empty set). if len(entries) < 2: if entries: intersection = {posting.account for posting in entries[0].postings} else: intersection = set() else: entries_iter = iter(entries) intersection = set(posting.account for posting in next(entries_iter).postings) for entry in entries_iter: accounts = set(posting.account for posting in entry.postings) intersection &= accounts if not intersection: break return intersection
Compute the intersection of the accounts on the given entries. Args: entries: A list of Transaction entries to process. Returns: A set of strings, the names of the common accounts from these entries.
3,094
import collections from beancount.core.number import ONE from beancount.core.number import ZERO from beancount.core.data import Transaction from beancount.core.data import Balance from beancount.core import amount from beancount.core import account from beancount.core import realization from beancount.core import getters BalanceError = collections.namedtuple('BalanceError', 'source message entry') def get_balance_tolerance(balance_entry, options_map): """Get the tolerance amount for a single entry. Args: balance_entry: An instance of data.Balance options_map: An options dict, as per the parser. Returns: A Decimal, the amount of tolerance implied by the directive. """ if balance_entry.tolerance is not None: # Use the balance-specific tolerance override if it is provided. tolerance = balance_entry.tolerance else: expo = balance_entry.amount.number.as_tuple().exponent if expo < 0: # Be generous and always allow twice the multiplier on Balance and # Pad because the user creates these and the rounding of those # balances may often be further off than those used within a single # transaction. tolerance = options_map["inferred_tolerance_multiplier"] * 2 tolerance = ONE.scaleb(expo) * tolerance else: tolerance = ZERO return tolerance class Balance(NamedTuple): """ A "check the balance of this account" directive. This directive asserts that the declared account should have a known number of units of a particular currency at the beginning of its date. This is essentially an assertion, and corresponds to the final "Statement Balance" line of a real-world statement. These assertions act as checkpoints to help ensure that you have entered your transactions correctly. Attributes: meta: See above. date: See above. account: A string, the account whose balance to check at the given date. amount: An Amount, the number of units of the given currency you're expecting 'account' to have at this date. diff_amount: None if the balance check succeeds. This value is set to an Amount instance if the balance fails, the amount of the difference. tolerance: A Decimal object, the amount of tolerance to use in the verification. """ meta: Meta date: datetime.date account: Account amount: Amount tolerance: Optional[Decimal] diff_amount: Optional[Amount] class Transaction(NamedTuple): """ A transaction! This is the main type of object that we manipulate, and the entire reason this whole project exists in the first place, because representing these types of structures with a spreadsheet is difficult. Attributes: meta: See above. date: See above. flag: A single-character string or None. This user-specified string represents some custom/user-defined state of the transaction. You can use this for various purposes. Otherwise common, pre-defined flags are defined under beancount.core.flags, to flags transactions that are automatically generated. payee: A free-form string that identifies the payee, or None, if absent. narration: A free-form string that provides a description for the transaction. All transactions have at least a narration string, this is never None. tags: A set of tag strings (without the '#'), or EMPTY_SET. links: A set of link strings (without the '^'), or EMPTY_SET. postings: A list of Posting instances, the legs of this transaction. See the doc under Posting above. """ meta: Meta date: datetime.date flag: Flag payee: Optional[str] narration: str tags: Set links: Set postings: List[Posting] The provided code snippet includes necessary dependencies for implementing the `check` function. Write a Python function `def check(entries, options_map)` to solve the following problem: Process the balance assertion directives. For each Balance directive, check that their expected balance corresponds to the actual balance computed at that time and replace failing ones by new ones with a flag that indicates failure. Args: entries: A list of directives. options_map: A dict of options, parsed from the input file. Returns: A pair of a list of directives and a list of balance check errors. Here is the function: def check(entries, options_map): """Process the balance assertion directives. For each Balance directive, check that their expected balance corresponds to the actual balance computed at that time and replace failing ones by new ones with a flag that indicates failure. Args: entries: A list of directives. options_map: A dict of options, parsed from the input file. Returns: A pair of a list of directives and a list of balance check errors. """ new_entries = [] check_errors = [] # This is similar to realization, but performed in a different order, and # where we only accumulate inventories for accounts that have balance # assertions in them (this saves on time). Here we process the entries one # by one along with the balance checks. We use a temporary realization in # order to hold the incremental tree of balances, so that we can easily get # the amounts of an account's subaccounts for making checks on parent # accounts. real_root = realization.RealAccount('') # Figure out the set of accounts for which we need to compute a running # inventory balance. asserted_accounts = {entry.account for entry in entries if isinstance(entry, Balance)} # Add all children accounts of an asserted account to be calculated as well, # and pre-create these accounts, and only those (we're just being tight to # make sure). asserted_match_list = [account.parent_matcher(account_) for account_ in asserted_accounts] for account_ in getters.get_accounts(entries): if (account_ in asserted_accounts or any(match(account_) for match in asserted_match_list)): realization.get_or_create(real_root, account_) # Get the Open directives for each account. open_close_map = getters.get_account_open_close(entries) for entry in entries: if isinstance(entry, Transaction): # For each of the postings' accounts, update the balance inventory. for posting in entry.postings: real_account = realization.get(real_root, posting.account) # The account will have been created only if we're meant to track it. if real_account is not None: # Note: Always allow negative lots for the purpose of balancing. # This error should show up somewhere else than here. real_account.balance.add_position(posting) elif isinstance(entry, Balance): # Check that the currency of the balance check is one of the allowed # currencies for that account. expected_amount = entry.amount try: open, _ = open_close_map[entry.account] except KeyError: check_errors.append( BalanceError(entry.meta, "Invalid reference to unknown account '{}'".format( entry.account), entry)) continue if (expected_amount is not None and open and open.currencies and expected_amount.currency not in open.currencies): check_errors.append( BalanceError(entry.meta, "Invalid currency '{}' for Balance directive: ".format( expected_amount.currency), entry)) # Sum up the current balances for this account and its # sub-accounts. We want to support checks for parent accounts # for the total sum of their subaccounts. # # FIXME: Improve the performance further by computing the balance # for the desired currency only. This won't allow us to cache in # this way but may be faster, if we're not asserting all the # currencies. Furthermore, we could probably avoid recomputing the # balance if a subtree of positions hasn't been invalidated by a new # position added to the realization. Do this. real_account = realization.get(real_root, entry.account) assert real_account is not None, "Missing {}".format(entry.account) subtree_balance = realization.compute_balance(real_account, leaf_only=False) # Get only the amount in the desired currency. balance_amount = subtree_balance.get_currency_units(expected_amount.currency) # Check if the amount is within bounds of the expected amount. diff_amount = amount.sub(balance_amount, expected_amount) # Use the specified tolerance or automatically infer it. tolerance = get_balance_tolerance(entry, options_map) if abs(diff_amount.number) > tolerance: check_errors.append( BalanceError(entry.meta, ("Balance failed for '{}': " "expected {} != accumulated {} ({} {})").format( entry.account, expected_amount, balance_amount, abs(diff_amount.number), ('too much' if diff_amount.number > 0 else 'too little')), entry)) # Substitute the entry by a failing entry, with the diff_amount # field set on it. I'm not entirely sure that this is the best # of ideas, maybe leaving the original check intact and insert a # new error entry might be more functional or easier to # understand. entry = entry._replace( meta=entry.meta.copy(), diff_amount=diff_amount) new_entries.append(entry) return new_entries, check_errors
Process the balance assertion directives. For each Balance directive, check that their expected balance corresponds to the actual balance computed at that time and replace failing ones by new ones with a flag that indicates failure. Args: entries: A list of directives. options_map: A dict of options, parsed from the input file. Returns: A pair of a list of directives and a list of balance check errors.
3,095
import collections import datetime import itertools from beancount.core import inventory from beancount.core import data ONEDAY = datetime.timedelta(days=1) The provided code snippet includes necessary dependencies for implementing the `get_commodity_lifetimes` function. Write a Python function `def get_commodity_lifetimes(entries)` to solve the following problem: Given a list of directives, figure out the life of each commodity. Args: entries: A list of directives. Returns: A dict of (currency, cost-currency) commodity strings to lists of (start, end) datetime.date pairs. The dates are inclusive of the day the commodity was seen; the end/last dates are one day _after_ the last date seen. Here is the function: def get_commodity_lifetimes(entries): """Given a list of directives, figure out the life of each commodity. Args: entries: A list of directives. Returns: A dict of (currency, cost-currency) commodity strings to lists of (start, end) datetime.date pairs. The dates are inclusive of the day the commodity was seen; the end/last dates are one day _after_ the last date seen. """ lifetimes = collections.defaultdict(list) # The current set of active commodities. commodities = set() # The current balances across all accounts. balances = collections.defaultdict(inventory.Inventory) for entry in entries: # Process only transaction entries. if not isinstance(entry, data.Transaction): continue # Update the balance of affected accounts and check locally whether that # triggered a change in the set of commodities. commodities_changed = False for posting in entry.postings: balance = balances[posting.account] commodities_before = balance.currency_pairs() balance.add_position(posting) commodities_after = balance.currency_pairs() if commodities_after != commodities_before: commodities_changed = True # If there was a change in one of the affected account's list of # commodities, recompute the total set globally. This should not # occur very frequently. if commodities_changed: new_commodities = set( itertools.chain(*(inv.currency_pairs() for inv in balances.values()))) if new_commodities != commodities: # The new global set of commodities has changed; update our # the dictionary of intervals. for currency in new_commodities - commodities: lifetimes[currency].append((entry.date, None)) for currency in commodities - new_commodities: lifetime = lifetimes[currency] begin_date, end_date = lifetime.pop(-1) assert end_date is None lifetime.append((begin_date, entry.date + ONEDAY)) # Update our current set. commodities = new_commodities return lifetimes
Given a list of directives, figure out the life of each commodity. Args: entries: A list of directives. Returns: A dict of (currency, cost-currency) commodity strings to lists of (start, end) datetime.date pairs. The dates are inclusive of the day the commodity was seen; the end/last dates are one day _after_ the last date seen.
3,096
import collections import datetime import itertools from beancount.core import inventory from beancount.core import data The provided code snippet includes necessary dependencies for implementing the `trim_intervals` function. Write a Python function `def trim_intervals(intervals, trim_start=None, trim_end=None)` to solve the following problem: Trim a list of date pairs to be within a start and end date. Useful in update-style price fetching. Args: intervals: A list of pairs of datetime.date instances trim_start: An inclusive starting date. trim_end: An exclusive starting date. Returns: A list of new intervals (pairs of (date, date)). Here is the function: def trim_intervals(intervals, trim_start=None, trim_end=None): """Trim a list of date pairs to be within a start and end date. Useful in update-style price fetching. Args: intervals: A list of pairs of datetime.date instances trim_start: An inclusive starting date. trim_end: An exclusive starting date. Returns: A list of new intervals (pairs of (date, date)). """ new_intervals = [] iter_intervals = iter(intervals) if(trim_start is not None and trim_end is not None and trim_end < trim_start): raise ValueError('Trim end date is before start date') for date_begin, date_end in iter_intervals: if(trim_start is not None and trim_start > date_begin): date_begin = trim_start if(trim_end is not None): if(date_end is None or trim_end < date_end): date_end = trim_end if(date_end is None or date_begin <= date_end): new_intervals.append((date_begin, date_end)) return new_intervals
Trim a list of date pairs to be within a start and end date. Useful in update-style price fetching. Args: intervals: A list of pairs of datetime.date instances trim_start: An inclusive starting date. trim_end: An exclusive starting date. Returns: A list of new intervals (pairs of (date, date)).
3,097
import collections import datetime import itertools from beancount.core import inventory from beancount.core import data def compress_intervals_days(intervals, num_days): """Compress a list of date pairs to ignore short stretches of unused days. Args: intervals: A list of pairs of datetime.date instances. num_days: An integer, the number of unused days to require for intervals to be distinct, to allow a gap. Returns: A new dict of lifetimes map where some intervals may have been joined. """ ignore_interval = datetime.timedelta(days=num_days) new_intervals = [] iter_intervals = iter(intervals) last_begin, last_end = next(iter_intervals) for date_begin, date_end in iter_intervals: if date_begin - last_end < ignore_interval: # Compress. last_end = date_end continue new_intervals.append((last_begin, last_end)) last_begin, last_end = date_begin, date_end new_intervals.append((last_begin, last_end)) return new_intervals The provided code snippet includes necessary dependencies for implementing the `compress_lifetimes_days` function. Write a Python function `def compress_lifetimes_days(lifetimes_map, num_days)` to solve the following problem: Compress a lifetimes map to ignore short stretches of unused days. Args: lifetimes_map: A dict of currency intervals as returned by get_commodity_lifetimes. num_days: An integer, the number of unused days to ignore. Returns: A new dict of lifetimes map where some intervals may have been joined. Here is the function: def compress_lifetimes_days(lifetimes_map, num_days): """Compress a lifetimes map to ignore short stretches of unused days. Args: lifetimes_map: A dict of currency intervals as returned by get_commodity_lifetimes. num_days: An integer, the number of unused days to ignore. Returns: A new dict of lifetimes map where some intervals may have been joined. """ return {currency_pair: compress_intervals_days(intervals, num_days) for currency_pair, intervals in lifetimes_map.items()}
Compress a lifetimes map to ignore short stretches of unused days. Args: lifetimes_map: A dict of currency intervals as returned by get_commodity_lifetimes. num_days: An integer, the number of unused days to ignore. Returns: A new dict of lifetimes map where some intervals may have been joined.
3,098
import collections import datetime import itertools from beancount.core import inventory from beancount.core import data ONE_WEEK = datetime.timedelta(days=7) The provided code snippet includes necessary dependencies for implementing the `required_weekly_prices` function. Write a Python function `def required_weekly_prices(lifetimes_map, date_last)` to solve the following problem: Enumerate all the commodities and Fridays where the price is required. Given a map of lifetimes for a set of commodities, enumerate all the Fridays for each commodity where it is active. This can be used to connect to a historical price fetcher routine to fill in missing price entries from an existing ledger. Args: lifetimes_map: A dict of currency to active intervals as returned by get_commodity_lifetimes(). date_last: A datetime.date instance, the last date which we're interested in. Returns: Tuples of (date, currency, cost-currency). Here is the function: def required_weekly_prices(lifetimes_map, date_last): """Enumerate all the commodities and Fridays where the price is required. Given a map of lifetimes for a set of commodities, enumerate all the Fridays for each commodity where it is active. This can be used to connect to a historical price fetcher routine to fill in missing price entries from an existing ledger. Args: lifetimes_map: A dict of currency to active intervals as returned by get_commodity_lifetimes(). date_last: A datetime.date instance, the last date which we're interested in. Returns: Tuples of (date, currency, cost-currency). """ results = [] for currency_pair, intervals in lifetimes_map.items(): if currency_pair[1] is None: continue for date_begin, date_end in intervals: # Find first Friday before the minimum date. diff_days = 4 - date_begin.weekday() if diff_days >= 1: diff_days -= 7 date = date_begin + datetime.timedelta(days=diff_days) # Iterate over all Fridays. if date_end is None: date_end = date_last while date < date_end: results.append((date, currency_pair[0], currency_pair[1])) date += ONE_WEEK return sorted(results)
Enumerate all the commodities and Fridays where the price is required. Given a map of lifetimes for a set of commodities, enumerate all the Fridays for each commodity where it is active. This can be used to connect to a historical price fetcher routine to fill in missing price entries from an existing ledger. Args: lifetimes_map: A dict of currency to active intervals as returned by get_commodity_lifetimes(). date_last: A datetime.date instance, the last date which we're interested in. Returns: Tuples of (date, currency, cost-currency).
3,099
import collections import datetime import itertools from beancount.core import inventory from beancount.core import data ONEDAY = datetime.timedelta(days=1) The provided code snippet includes necessary dependencies for implementing the `required_daily_prices` function. Write a Python function `def required_daily_prices(lifetimes_map, date_last, weekdays_only=False)` to solve the following problem: Enumerate all the commodities and days where the price is required. Given a map of lifetimes for a set of commodities, enumerate all the days for each commodity where it is active. This can be used to connect to a historical price fetcher routine to fill in missing price entries from an existing ledger. Args: lifetimes_map: A dict of currency to active intervals as returned by get_commodity_lifetimes(). date_last: A datetime.date instance, the last date which we're interested in. weekdays_only: Option to limit fetching to weekdays only. Returns: Tuples of (date, currency, cost-currency). Here is the function: def required_daily_prices(lifetimes_map, date_last, weekdays_only=False): """Enumerate all the commodities and days where the price is required. Given a map of lifetimes for a set of commodities, enumerate all the days for each commodity where it is active. This can be used to connect to a historical price fetcher routine to fill in missing price entries from an existing ledger. Args: lifetimes_map: A dict of currency to active intervals as returned by get_commodity_lifetimes(). date_last: A datetime.date instance, the last date which we're interested in. weekdays_only: Option to limit fetching to weekdays only. Returns: Tuples of (date, currency, cost-currency). """ results = [] for currency_pair, intervals in lifetimes_map.items(): if currency_pair[1] is None: continue for date_begin, date_end in intervals: # Find first Weekday starting on or before minimum date. date = date_begin if(weekdays_only): diff_days = 4 - date_begin.weekday() if diff_days < 0: date += datetime.timedelta(days=diff_days) # Iterate over all weekdays. if date_end is None: date_end = date_last while date < date_end: results.append((date, currency_pair[0], currency_pair[1])) if weekdays_only and date.weekday() == 4: date += 3 * ONEDAY else: date += ONEDAY return sorted(results)
Enumerate all the commodities and days where the price is required. Given a map of lifetimes for a set of commodities, enumerate all the days for each commodity where it is active. This can be used to connect to a historical price fetcher routine to fill in missing price entries from an existing ledger. Args: lifetimes_map: A dict of currency to active intervals as returned by get_commodity_lifetimes(). date_last: A datetime.date instance, the last date which we're interested in. weekdays_only: Option to limit fetching to weekdays only. Returns: Tuples of (date, currency, cost-currency).
3,100
import re import datetime from os import path from collections import namedtuple from beancount.core import account from beancount.core import data from beancount.core import getters def find_documents(directory, input_filename, accounts_only=None, strict=False): """Find dated document files under the given directory. If a restricting set of accounts is provided in 'accounts_only', only return entries that correspond to one of the given accounts. Args: directory: A string, the name of the root of the directory hierarchy to be searched. input_filename: The name of the file to be used for the Document directives. This is also used to resolve relative directory names. accounts_only: A set of valid accounts strings to search for. strict: A boolean, set to true if you want to generate errors on documents found in accounts not provided in accounts_only. This is only meaningful if accounts_only is specified. Returns: A list of new Document objects that were created from the files found, and a list of new errors generated. """ errors = [] # Compute the documents directory name relative to the beancount input # file itself. if not path.isabs(directory): input_directory = path.dirname(input_filename) directory = path.abspath(path.normpath(path.join(input_directory, directory))) # If the directory does not exist, just generate an error and return. if not path.exists(directory): meta = data.new_metadata(input_filename, 0) error = DocumentError( meta, "Document root '{}' does not exist".format(directory), None) return ([], [error]) # Walk the hierarchy of files. entries = [] for root, account_name, dirs, files in account.walk(directory): # Look for files that have a dated filename. for filename in files: match = re.match(r'(\d\d\d\d)-(\d\d)-(\d\d).(.*)', filename) if not match: continue # If a restricting set of accounts was specified, skip document # directives found in accounts with no corresponding account name. if accounts_only is not None and not account_name in accounts_only: if strict: if any(account_name.startswith(account) for account in accounts_only): errors.append(DocumentError( data.new_metadata(input_filename, 0), "Document '{}' found in child account {}".format( filename, account_name), None)) elif any(account.startswith(account_name) for account in accounts_only): errors.append(DocumentError( data.new_metadata(input_filename, 0), "Document '{}' found in parent account {}".format( filename, account_name), None)) continue # Create a new directive. meta = data.new_metadata(input_filename, 0) try: date = datetime.date(*map(int, match.group(1, 2, 3))) except ValueError as exc: errors.append(DocumentError( data.new_metadata(input_filename, 0), "Invalid date on document file '{}': {}".format( filename, exc), None)) else: entry = data.Document(meta, date, account_name, path.join(root, filename), data.EMPTY_SET, data.EMPTY_SET) entries.append(entry) return (entries, errors) The provided code snippet includes necessary dependencies for implementing the `process_documents` function. Write a Python function `def process_documents(entries, options_map)` to solve the following problem: Check files for document directives and create documents directives automatically. Args: entries: A list of all directives parsed from the file. options_map: An options dict, as is output by the parser. We're using its 'filename' option to figure out relative path to search for documents. Returns: A pair of list of all entries (including new ones), and errors generated during the process of creating document directives. Here is the function: def process_documents(entries, options_map): """Check files for document directives and create documents directives automatically. Args: entries: A list of all directives parsed from the file. options_map: An options dict, as is output by the parser. We're using its 'filename' option to figure out relative path to search for documents. Returns: A pair of list of all entries (including new ones), and errors generated during the process of creating document directives. """ filename = options_map["filename"] # Detect filenames that should convert into entries. autodoc_entries = [] autodoc_errors = [] document_dirs = options_map['documents'] if document_dirs: # Restrict to the list of valid accounts only. accounts = getters.get_accounts(entries) # Accumulate all the entries. for directory in map(path.normpath, document_dirs): new_entries, new_errors = find_documents(directory, filename, accounts) autodoc_entries.extend(new_entries) autodoc_errors.extend(new_errors) # Merge the two lists of entries and errors. Keep the entries sorted. entries.extend(autodoc_entries) entries.sort(key=data.entry_sortkey) return (entries, autodoc_errors)
Check files for document directives and create documents directives automatically. Args: entries: A list of all directives parsed from the file. options_map: An options dict, as is output by the parser. We're using its 'filename' option to figure out relative path to search for documents. Returns: A pair of list of all entries (including new ones), and errors generated during the process of creating document directives.
3,101
import re import datetime from os import path from collections import namedtuple from beancount.core import account from beancount.core import data from beancount.core import getters DocumentError = namedtuple('DocumentError', 'source message entry') The provided code snippet includes necessary dependencies for implementing the `verify_document_files_exist` function. Write a Python function `def verify_document_files_exist(entries, unused_options_map)` to solve the following problem: Verify that the document entries point to existing files. Args: entries: a list of directives whose documents need to be validated. unused_options_map: A parser options dict. We're not using it. Returns: The same list of entries, and a list of new errors, if any were encountered. Here is the function: def verify_document_files_exist(entries, unused_options_map): """Verify that the document entries point to existing files. Args: entries: a list of directives whose documents need to be validated. unused_options_map: A parser options dict. We're not using it. Returns: The same list of entries, and a list of new errors, if any were encountered. """ errors = [] for entry in entries: if not isinstance(entry, data.Document): continue if not path.exists(entry.filename): errors.append( DocumentError(entry.meta, 'File does not exist: "{}"'.format(entry.filename), entry)) return entries, errors
Verify that the document entries point to existing files. Args: entries: a list of directives whose documents need to be validated. unused_options_map: A parser options dict. We're not using it. Returns: The same list of entries, and a list of new errors, if any were encountered.
3,102
from beancount.core import data from beancount.ops import summarize The provided code snippet includes necessary dependencies for implementing the `find_currencies_at_cost` function. Write a Python function `def find_currencies_at_cost(entries, date=None)` to solve the following problem: Return all currencies that were held at cost at some point. This returns all of them, even if not on the books at a particular point in time. This code does not look at account balances. Args: entries: A list of directives. date: A datetime.date instance. Returns: A list of (base, quote) currencies. Here is the function: def find_currencies_at_cost(entries, date=None): """Return all currencies that were held at cost at some point. This returns all of them, even if not on the books at a particular point in time. This code does not look at account balances. Args: entries: A list of directives. date: A datetime.date instance. Returns: A list of (base, quote) currencies. """ currencies = set() for entry in entries: if not isinstance(entry, data.Transaction): continue if date and entry.date >= date: break for posting in entry.postings: if posting.cost is not None and posting.cost.number is not None: currencies.add((posting.units.currency, posting.cost.currency)) return currencies
Return all currencies that were held at cost at some point. This returns all of them, even if not on the books at a particular point in time. This code does not look at account balances. Args: entries: A list of directives. date: A datetime.date instance. Returns: A list of (base, quote) currencies.
3,103
from beancount.core import data from beancount.ops import summarize def find_currencies_converted(entries, date=None): """Return currencies from price conversions. This function looks at all price conversions that occurred until some date and produces a list of them. Note: This does not include Price directives, only postings with price conversions. Args: entries: A list of directives. date: A datetime.date instance. Returns: A list of (base, quote) currencies. """ currencies = set() for entry in entries: if not isinstance(entry, data.Transaction): continue if date and entry.date >= date: break for posting in entry.postings: price = posting.price if posting.cost is not None or price is None: continue currencies.add((posting.units.currency, price.currency)) return currencies def find_currencies_priced(entries, date=None): """Return currencies seen in Price directives. Args: entries: A list of directives. date: A datetime.date instance. Returns: A list of (base, quote) currencies. """ currencies = set() for entry in entries: if not isinstance(entry, data.Price): continue if date and entry.date >= date: break currencies.add((entry.currency, entry.amount.currency)) return currencies def summarize(entries, date, account_opening): """Summarize all entries before a date by replacing then with summarization entries. This function replaces the transactions up to (and not including) the given date with a opening balance transactions, one for each account. It returns new entries, all of the transactions before the given date having been replaced by a few summarization entries, one for each account. Notes: - Open entries are preserved for active accounts. - The last relevant price entry for each (base, quote) pair is preserved. - All other entries before the cutoff date are culled. Args: entries: A list of directives. date: A datetime.date instance, the cutoff date before which to summarize. account_opening: A string, the name of the source account to book summarization entries against. Returns: The function returns a list of new entries and the integer index at which the entries on or after the cutoff date begin. """ # Compute balances at date. balances, index = balance_by_account(entries, date) # We need to insert the entries with a date previous to subsequent checks, # to maintain ensure the open directives show up before any transaction. summarize_date = date - datetime.timedelta(days=1) # Create summarization / opening balance entries. summarizing_entries = create_entries_from_balances( balances, summarize_date, account_opening, True, data.new_metadata('<summarize>', 0), flags.FLAG_SUMMARIZE, "Opening balance for '{account}' (Summarization)") # Insert the last price entry for each commodity from before the date. price_entries = prices.get_last_price_entries(entries, date) # Gather the list of active open entries at date. open_entries = get_open_entries(entries, date) # Compute entries before the date and preserve the entries after the date. before_entries = sorted(open_entries + price_entries + summarizing_entries, key=data.entry_sortkey) after_entries = entries[index:] # Return a new list of entries and the index that points after the entries # were inserted. return (before_entries + after_entries), len(before_entries) The provided code snippet includes necessary dependencies for implementing the `find_balance_currencies` function. Write a Python function `def find_balance_currencies(entries, date=None)` to solve the following problem: Return currencies relevant for the given date. This computes the account balances as of the date, and returns the union of: a) The currencies held at cost, and b) Currency pairs from previous conversions, but only for currencies with non-zero balances. This is intended to produce the list of currencies whose prices are relevant at a particular date, based on previous history. Args: entries: A list of directives. date: A datetime.date instance. Returns: A set of (base, quote) currencies. Here is the function: def find_balance_currencies(entries, date=None): """Return currencies relevant for the given date. This computes the account balances as of the date, and returns the union of: a) The currencies held at cost, and b) Currency pairs from previous conversions, but only for currencies with non-zero balances. This is intended to produce the list of currencies whose prices are relevant at a particular date, based on previous history. Args: entries: A list of directives. date: A datetime.date instance. Returns: A set of (base, quote) currencies. """ # Compute the balances. currencies = set() currencies_on_books = set() balances, _ = summarize.balance_by_account(entries, date) for _, balance in balances.items(): for pos in balance: if pos.cost is not None: # Add currencies held at cost. currencies.add((pos.units.currency, pos.cost.currency)) else: # Add regular currencies. currencies_on_books.add(pos.units.currency) # Create currency pairs from the currencies which are on account balances. # In order to figure out the quote currencies, we use the list of price # conversions until this date. converted = (find_currencies_converted(entries, date) | find_currencies_priced(entries, date)) for cbase in currencies_on_books: for base_quote in converted: base, quote = base_quote if base == cbase: currencies.add(base_quote) return currencies
Return currencies relevant for the given date. This computes the account balances as of the date, and returns the union of: a) The currencies held at cost, and b) Currency pairs from previous conversions, but only for currencies with non-zero balances. This is intended to produce the list of currencies whose prices are relevant at a particular date, based on previous history. Args: entries: A list of directives. date: A datetime.date instance. Returns: A set of (base, quote) currencies.
3,104
import datetime import collections from beancount.core.number import ZERO from beancount.core.data import Transaction from beancount.core.data import Open from beancount.core.data import Close from beancount.core.account_types import is_income_statement_account from beancount.core import amount from beancount.core import inventory from beancount.core import data from beancount.core import flags from beancount.core import getters from beancount.core import interpolate from beancount.core import convert from beancount.core import prices from beancount.utils import bisect_key from beancount.parser import options def open(entries, date, account_types, conversion_currency, account_earnings, account_opening, account_conversions): """Summarize entries before a date and transfer income/expenses to equity. This method essentially prepares a list of directives to contain only transactions that occur after a particular date. It truncates the past. To do so, it will 1. Insert conversion transactions at the given open date, then 2. Insert transactions at that date to move accumulated balances from before that date from the income and expenses accounts to an equity account, and finally 3. It removes all the transactions previous to the date and replaces them by opening balances entries to bring the balances to the same amount. The result is a list of entries for which the income and expense accounts are beginning with a balance of zero, and all other accounts begin with a transaction that brings their balance to the expected amount. All the past has been summarized at that point. An index is returned to the first transaction past the balance opening transactions, so you can keep just those in order to render a balance sheet for only the opening balances. Args: entries: A list of directive tuples. date: A datetime.date instance, the date at which to do this. account_types: An instance of AccountTypes. conversion_currency: A string, the transfer currency to use for zero prices on the conversion entry. account_earnings: A string, the name of the account to transfer previous earnings from the income statement accounts to the balance sheet. account_opening: A string, the name of the account in equity to transfer previous balances from, in order to initialize account balances at the beginning of the period. This is typically called an opening balances account. account_conversions: A string, the name of the equity account to book currency conversions against. Returns: A new list of entries is returned, and the index that points to the first original transaction after the beginning date of the period. This index can be used to generate the opening balances report, which is a balance sheet fed with only the summarized entries. """ # Insert conversion entries. entries = conversions(entries, account_conversions, conversion_currency, date) # Transfer income and expenses before the period to equity. entries, _ = clear(entries, date, account_types, account_earnings) # Summarize all the previous balances, after transferring the income and # expense balances, so all entries for those accounts before the begin date # should now disappear. entries, index = summarize(entries, date, account_opening) return entries, index The provided code snippet includes necessary dependencies for implementing the `open_opt` function. Write a Python function `def open_opt(entries, date, options_map)` to solve the following problem: Convenience function to open() using an options map. Here is the function: def open_opt(entries, date, options_map): """Convenience function to open() using an options map. """ account_types = options.get_account_types(options_map) previous_accounts = options.get_previous_accounts(options_map) conversion_currency = options_map['conversion_currency'] return open(entries, date, account_types, conversion_currency, *previous_accounts)
Convenience function to open() using an options map.
3,105
import datetime import collections from beancount.core.number import ZERO from beancount.core.data import Transaction from beancount.core.data import Open from beancount.core.data import Close from beancount.core.account_types import is_income_statement_account from beancount.core import amount from beancount.core import inventory from beancount.core import data from beancount.core import flags from beancount.core import getters from beancount.core import interpolate from beancount.core import convert from beancount.core import prices from beancount.utils import bisect_key from beancount.parser import options def close(entries, date, conversion_currency, account_conversions): """Truncate entries that occur after a particular date and ensure balance. This method essentially removes entries after a date. It truncates the future. To do so, it will 1. Remove all entries which occur after 'date', if given. 2. Insert conversion transactions at the end of the list of entries to ensure that the total balance of all postings sums up to empty. The result is a list of entries with a total balance of zero, with possibly non-zero balances for the income/expense accounts. To produce a final balance sheet, use transfer() to move the net income to the equity accounts. Args: entries: A list of directive tuples. date: A datetime.date instance, one day beyond the end of the period. This date can be optionally left to None in order to close at the end of the list of entries. conversion_currency: A string, the transfer currency to use for zero prices on the conversion entry. account_conversions: A string, the name of the equity account to book currency conversions against. Returns: A new list of entries is returned, and the index that points to one beyond the last original transaction that was provided. Further entries may have been inserted to normalize conversions and ensure the total balance sums to zero. """ # Truncate the entries after the date, if a date has been provided. if date is not None: entries = truncate(entries, date) # Keep an index to the truncated list of entries (before conversions). index = len(entries) # Insert a conversions entry to ensure the total balance of all accounts is # flush zero. entries = conversions(entries, account_conversions, conversion_currency, date) return entries, index The provided code snippet includes necessary dependencies for implementing the `close_opt` function. Write a Python function `def close_opt(entries, date, options_map)` to solve the following problem: Convenience function to close() using an options map. Here is the function: def close_opt(entries, date, options_map): """Convenience function to close() using an options map. """ conversion_currency = options_map['conversion_currency'] current_accounts = options.get_current_accounts(options_map) return close(entries, date, conversion_currency, current_accounts[1])
Convenience function to close() using an options map.
3,106
import datetime import collections from beancount.core.number import ZERO from beancount.core.data import Transaction from beancount.core.data import Open from beancount.core.data import Close from beancount.core.account_types import is_income_statement_account from beancount.core import amount from beancount.core import inventory from beancount.core import data from beancount.core import flags from beancount.core import getters from beancount.core import interpolate from beancount.core import convert from beancount.core import prices from beancount.utils import bisect_key from beancount.parser import options def clear(entries, date, account_types, account_earnings): """Transfer income and expenses balances at the given date to the equity accounts. This method insert entries to zero out balances on income and expenses accounts by transferring them to an equity account. Args: entries: A list of directive tuples. date: A datetime.date instance, one day beyond the end of the period. This date can be optionally left to None in order to close at the end of the list of entries. account_types: An instance of AccountTypes. account_earnings: A string, the name of the account to transfer previous earnings from the income statement accounts to the balance sheet. Returns: A new list of entries is returned, and the index that points to one before the last original transaction before the transfers. """ index = len(entries) # Transfer income and expenses before the period to equity. income_statement_account_pred = ( lambda account: is_income_statement_account(account, account_types)) new_entries = transfer_balances(entries, date, income_statement_account_pred, account_earnings) return new_entries, index The provided code snippet includes necessary dependencies for implementing the `clear_opt` function. Write a Python function `def clear_opt(entries, date, options_map)` to solve the following problem: Convenience function to clear() using an options map. Here is the function: def clear_opt(entries, date, options_map): """Convenience function to clear() using an options map. """ account_types = options.get_account_types(options_map) current_accounts = options.get_current_accounts(options_map) return clear(entries, date, account_types, current_accounts[0])
Convenience function to clear() using an options map.
3,107
import datetime import collections from beancount.core.number import ZERO from beancount.core.data import Transaction from beancount.core.data import Open from beancount.core.data import Close from beancount.core.account_types import is_income_statement_account from beancount.core import amount from beancount.core import inventory from beancount.core import data from beancount.core import flags from beancount.core import getters from beancount.core import interpolate from beancount.core import convert from beancount.core import prices from beancount.utils import bisect_key from beancount.parser import options def clamp(entries, begin_date, end_date, account_types, conversion_currency, account_earnings, account_opening, account_conversions): """Filter entries to include only those during a specified time period. Firstly, this method will transfer all balances for the income and expense accounts occurring before the given period begin date to the 'account_earnings' account (earnings before the period, or "retained earnings") and summarize all of the transactions before that date against the 'account_opening' account (usually "opening balances"). The resulting income and expense accounts should have no transactions (since their balances have been transferred out and summarization of zero balances should not add any transactions). Secondly, all the entries after the period end date will be truncated and a conversion entry will be added for the resulting transactions that reflect changes occurring between the beginning and end of the exercise period. The resulting balance of all account should be empty. Args: entries: A list of directive tuples. begin_date: A datetime.date instance, the beginning of the period. end_date: A datetime.date instance, one day beyond the end of the period. account_types: An instance of AccountTypes. conversion_currency: A string, the transfer currency to use for zero prices on the conversion entry. account_earnings: A string, the name of the account to transfer previous earnings from the income statement accounts to the balance sheet. account_opening: A string, the name of the account in equity to transfer previous balances from, in order to initialize account balances at the beginning of the period. This is typically called an opening balances account. account_conversions: A string, the name of the equity account to book currency conversions against. Returns: A new list of entries is returned, and the index that points to the first original transaction after the beginning date of the period. This index can be used to generate the opening balances report, which is a balance sheet fed with only the summarized entries. """ # Transfer income and expenses before the period to equity. income_statement_account_pred = ( lambda account: is_income_statement_account(account, account_types)) entries = transfer_balances(entries, begin_date, income_statement_account_pred, account_earnings) # Summarize all the previous balances, after transferring the income and # expense balances, so all entries for those accounts before the begin date # should now disappear. entries, index = summarize(entries, begin_date, account_opening) # Truncate the entries after this. entries = truncate(entries, end_date) # Insert conversion entries. entries = conversions(entries, account_conversions, conversion_currency, end_date) return entries, index The provided code snippet includes necessary dependencies for implementing the `clamp_opt` function. Write a Python function `def clamp_opt(entries, begin_date, end_date, options_map)` to solve the following problem: Clamp by getting all the parameters from an options map. See clamp() for details. Args: entries: See clamp(). begin_date: See clamp(). end_date: See clamp(). options_map: A parser's option_map. Returns: Same as clamp(). Here is the function: def clamp_opt(entries, begin_date, end_date, options_map): """Clamp by getting all the parameters from an options map. See clamp() for details. Args: entries: See clamp(). begin_date: See clamp(). end_date: See clamp(). options_map: A parser's option_map. Returns: Same as clamp(). """ account_types = options.get_account_types(options_map) previous_earnings, previous_balances, _ = options.get_previous_accounts(options_map) _, current_conversions = options.get_current_accounts(options_map) conversion_currency = options_map['conversion_currency'] return clamp(entries, begin_date, end_date, account_types, conversion_currency, previous_earnings, previous_balances, current_conversions)
Clamp by getting all the parameters from an options map. See clamp() for details. Args: entries: See clamp(). begin_date: See clamp(). end_date: See clamp(). options_map: A parser's option_map. Returns: Same as clamp().
3,108
import datetime import collections from beancount.core.number import ZERO from beancount.core.data import Transaction from beancount.core.data import Open from beancount.core.data import Close from beancount.core.account_types import is_income_statement_account from beancount.core import amount from beancount.core import inventory from beancount.core import data from beancount.core import flags from beancount.core import getters from beancount.core import interpolate from beancount.core import convert from beancount.core import prices from beancount.utils import bisect_key from beancount.parser import options def cap(entries, account_types, conversion_currency, account_earnings, account_conversions): """Transfer net income to equity and insert a final conversion entry. This is used to move and nullify balances from the income and expense accounts to an equity account in order to draw up a balance sheet with a balance of precisely zero. Args: entries: A list of directives. account_types: An instance of AccountTypes. conversion_currency: A string, the transfer currency to use for zero prices on the conversion entry. account_earnings: A string, the name of the equity account to transfer final balances of the income and expense accounts to. account_conversions: A string, the name of the equity account to use as the source for currency conversions. Returns: A modified list of entries, with the income and expense accounts transferred. """ # Transfer the balances of income and expense accounts as earnings / net # income. income_statement_account_pred = ( lambda account: is_income_statement_account(account, account_types)) entries = transfer_balances(entries, None, income_statement_account_pred, account_earnings) # Insert final conversion entries. entries = conversions(entries, account_conversions, conversion_currency, None) return entries The provided code snippet includes necessary dependencies for implementing the `cap_opt` function. Write a Python function `def cap_opt(entries, options_map)` to solve the following problem: Close by getting all the parameters from an options map. See cap() for details. Args: entries: See cap(). options_map: A parser's option_map. Returns: Same as close(). Here is the function: def cap_opt(entries, options_map): """Close by getting all the parameters from an options map. See cap() for details. Args: entries: See cap(). options_map: A parser's option_map. Returns: Same as close(). """ account_types = options.get_account_types(options_map) current_accounts = options.get_current_accounts(options_map) conversion_currency = options_map['conversion_currency'] return cap(entries, account_types, conversion_currency, *current_accounts)
Close by getting all the parameters from an options map. See cap() for details. Args: entries: See cap(). options_map: A parser's option_map. Returns: Same as close().
3,109
import collections from decimal import Decimal from beancount.core.amount import Amount from beancount.core import data def merge(entries, prototype_txn): """Merge the postings of a list of Transactions into a single one. Merge postings the given entries into a single entry with the Transaction attributes of the prototype. Return the new entry. The combined list of postings are merged if everything about the postings is the same except the number. Args: entries: A list of directives. prototype_txn: A Transaction which is used to create the compressed Transaction instance. Its list of postings is ignored. Returns: A new Transaction instance which contains all the postings from the input entries merged together. """ # Aggregate the postings together. This is a mapping of numberless postings # to their number of units. postings_map = collections.defaultdict(Decimal) for entry in data.filter_txns(entries): for posting in entry.postings: # We strip the number off the posting to act as an aggregation key. key = data.Posting(posting.account, Amount(None, posting.units.currency), posting.cost, posting.price, posting.flag, None) postings_map[key] += posting.units.number # Create a new transaction with the aggregated postings. new_entry = data.Transaction(prototype_txn.meta, prototype_txn.date, prototype_txn.flag, prototype_txn.payee, prototype_txn.narration, data.EMPTY_SET, data.EMPTY_SET, []) # Sort for at least some stability of output. sorted_items = sorted(postings_map.items(), key=lambda item: (item[0].account, item[0].units.currency, item[1])) # Issue the merged postings. for posting, number in sorted_items: units = Amount(number, posting.units.currency) new_entry.postings.append( data.Posting(posting.account, units, posting.cost, posting.price, posting.flag, posting.meta)) return new_entry The provided code snippet includes necessary dependencies for implementing the `compress` function. Write a Python function `def compress(entries, predicate)` to solve the following problem: Compress multiple transactions into single transactions. Replace consecutive sequences of Transaction entries that fulfill the given predicate by a single entry at the date of the last matching entry. 'predicate' is the function that determines if an entry should be compressed. This can be used to simply a list of transactions that are similar and occur frequently. As an example, in a retail FOREX trading account, differential interest of very small amounts is paid every day; it is not relevant to look at the full detail of this interest unless there are other transactions. You can use this to compress it into single entries between other types of transactions. Args: entries: A list of directives. predicate: A callable which accepts an entry and return true if the entry is intended to be compressed. Returns: A list of directives, with compressible transactions replaced by a summary equivalent. Here is the function: def compress(entries, predicate): """Compress multiple transactions into single transactions. Replace consecutive sequences of Transaction entries that fulfill the given predicate by a single entry at the date of the last matching entry. 'predicate' is the function that determines if an entry should be compressed. This can be used to simply a list of transactions that are similar and occur frequently. As an example, in a retail FOREX trading account, differential interest of very small amounts is paid every day; it is not relevant to look at the full detail of this interest unless there are other transactions. You can use this to compress it into single entries between other types of transactions. Args: entries: A list of directives. predicate: A callable which accepts an entry and return true if the entry is intended to be compressed. Returns: A list of directives, with compressible transactions replaced by a summary equivalent. """ new_entries = [] pending = [] for entry in entries: if isinstance(entry, data.Transaction) and predicate(entry): # Save for compressing later. pending.append(entry) else: # Compress and output all the pending entries. if pending: new_entries.append(merge(pending, pending[-1])) pending.clear() # Output the differing entry. new_entries.append(entry) if pending: new_entries.append(merge(pending, pending[-1])) return new_entries
Compress multiple transactions into single transactions. Replace consecutive sequences of Transaction entries that fulfill the given predicate by a single entry at the date of the last matching entry. 'predicate' is the function that determines if an entry should be compressed. This can be used to simply a list of transactions that are similar and occur frequently. As an example, in a retail FOREX trading account, differential interest of very small amounts is paid every day; it is not relevant to look at the full detail of this interest unless there are other transactions. You can use this to compress it into single entries between other types of transactions. Args: entries: A list of directives. predicate: A callable which accepts an entry and return true if the entry is intended to be compressed. Returns: A list of directives, with compressible transactions replaced by a summary equivalent.
3,110
from os import path import collections from beancount.core.data import Open from beancount.core.data import Balance from beancount.core.data import Close from beancount.core.data import Transaction from beancount.core.data import Document from beancount.core.data import Note from beancount.core import data from beancount.core import getters from beancount.core import interpolate from beancount.utils import misc_utils ValidationError = collections.namedtuple('ValidationError', 'source message entry') class Open(NamedTuple): """ An "open account" directive. Attributes: meta: See above. date: See above. account: A string, the name of the account that is being opened. currencies: A list of strings, currencies that are allowed in this account. May be None, in which case it means that there are no restrictions on which currencies may be stored in this account. booking: A Booking enum, the booking method to use to disambiguate postings to this account (when zero or more than one postings match the specification), or None if not specified. In practice, this attribute will be should be left unspecified (None) in the vast majority of cases. See Booking below for a selection of valid methods. """ meta: Meta date: datetime.date account: Account currencies: List[Currency] booking: Optional[Booking] class Close(NamedTuple): """ A "close account" directive. Attributes: meta: See above. date: See above. account: A string, the name of the account that is being closed. """ meta: Meta date: datetime.date account: Account The provided code snippet includes necessary dependencies for implementing the `validate_open_close` function. Write a Python function `def validate_open_close(entries, unused_options_map)` to solve the following problem: Check constraints on open and close directives themselves. This method checks two kinds of constraints: 1. An open or a close directive may only show up once for each account. If a duplicate is detected, an error is generated. 2. Close directives may only appear if an open directive has been seen previously (chronologically). 3. The date of close directives must be strictly greater than their corresponding open directive. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found. Here is the function: def validate_open_close(entries, unused_options_map): """Check constraints on open and close directives themselves. This method checks two kinds of constraints: 1. An open or a close directive may only show up once for each account. If a duplicate is detected, an error is generated. 2. Close directives may only appear if an open directive has been seen previously (chronologically). 3. The date of close directives must be strictly greater than their corresponding open directive. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found. """ errors = [] open_map = {} close_map = {} for entry in entries: if isinstance(entry, Open): if entry.account in open_map: errors.append( ValidationError( entry.meta, "Duplicate open directive for {}".format(entry.account), entry)) else: open_map[entry.account] = entry elif isinstance(entry, Close): if entry.account in close_map: errors.append( ValidationError( entry.meta, "Duplicate close directive for {}".format(entry.account), entry)) else: try: open_entry = open_map[entry.account] if entry.date < open_entry.date: errors.append( ValidationError( entry.meta, "Internal error: closing date for {} " "appears before opening date".format(entry.account), entry)) except KeyError: errors.append( ValidationError( entry.meta, "Unopened account {} is being closed".format(entry.account), entry)) close_map[entry.account] = entry return errors
Check constraints on open and close directives themselves. This method checks two kinds of constraints: 1. An open or a close directive may only show up once for each account. If a duplicate is detected, an error is generated. 2. Close directives may only appear if an open directive has been seen previously (chronologically). 3. The date of close directives must be strictly greater than their corresponding open directive. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found.
3,111
from os import path import collections from beancount.core.data import Open from beancount.core.data import Balance from beancount.core.data import Close from beancount.core.data import Transaction from beancount.core.data import Document from beancount.core.data import Note from beancount.core import data from beancount.core import getters from beancount.core import interpolate from beancount.utils import misc_utils ValidationError = collections.namedtuple('ValidationError', 'source message entry') class Balance(NamedTuple): """ A "check the balance of this account" directive. This directive asserts that the declared account should have a known number of units of a particular currency at the beginning of its date. This is essentially an assertion, and corresponds to the final "Statement Balance" line of a real-world statement. These assertions act as checkpoints to help ensure that you have entered your transactions correctly. Attributes: meta: See above. date: See above. account: A string, the account whose balance to check at the given date. amount: An Amount, the number of units of the given currency you're expecting 'account' to have at this date. diff_amount: None if the balance check succeeds. This value is set to an Amount instance if the balance fails, the amount of the difference. tolerance: A Decimal object, the amount of tolerance to use in the verification. """ meta: Meta date: datetime.date account: Account amount: Amount tolerance: Optional[Decimal] diff_amount: Optional[Amount] The provided code snippet includes necessary dependencies for implementing the `validate_duplicate_balances` function. Write a Python function `def validate_duplicate_balances(entries, unused_options_map)` to solve the following problem: Check that balance entries occur only once per day. Because we do not support time, and the declaration order of entries is meant to be kept irrelevant, two balance entries with different amounts should not occur in the file. We do allow two identical balance assertions, however, because this may occur during import. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found. Here is the function: def validate_duplicate_balances(entries, unused_options_map): """Check that balance entries occur only once per day. Because we do not support time, and the declaration order of entries is meant to be kept irrelevant, two balance entries with different amounts should not occur in the file. We do allow two identical balance assertions, however, because this may occur during import. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found. """ errors = [] # Mapping of (account, currency, date) to Balance entry. balance_entries = {} for entry in entries: if not isinstance(entry, data.Balance): continue key = (entry.account, entry.amount.currency, entry.date) try: previous_entry = balance_entries[key] if entry.amount != previous_entry.amount: errors.append( ValidationError( entry.meta, "Duplicate balance assertion with different amounts", entry)) except KeyError: balance_entries[key] = entry return errors
Check that balance entries occur only once per day. Because we do not support time, and the declaration order of entries is meant to be kept irrelevant, two balance entries with different amounts should not occur in the file. We do allow two identical balance assertions, however, because this may occur during import. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found.
3,112
from os import path import collections from beancount.core.data import Open from beancount.core.data import Balance from beancount.core.data import Close from beancount.core.data import Transaction from beancount.core.data import Document from beancount.core.data import Note from beancount.core import data from beancount.core import getters from beancount.core import interpolate from beancount.utils import misc_utils ValidationError = collections.namedtuple('ValidationError', 'source message entry') The provided code snippet includes necessary dependencies for implementing the `validate_duplicate_commodities` function. Write a Python function `def validate_duplicate_commodities(entries, unused_options_map)` to solve the following problem: Check that commodity entries are unique for each commodity. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found. Here is the function: def validate_duplicate_commodities(entries, unused_options_map): """Check that commodity entries are unique for each commodity. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found. """ errors = [] # Mapping of (account, currency, date) to Balance entry. commodity_entries = {} for entry in entries: if not isinstance(entry, data.Commodity): continue key = entry.currency try: previous_entry = commodity_entries[key] if previous_entry: errors.append( ValidationError( entry.meta, "Duplicate commodity directives for '{}'".format(key), entry)) except KeyError: commodity_entries[key] = entry return errors
Check that commodity entries are unique for each commodity. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found.
3,113
from os import path import collections from beancount.core.data import Open from beancount.core.data import Balance from beancount.core.data import Close from beancount.core.data import Transaction from beancount.core.data import Document from beancount.core.data import Note from beancount.core import data from beancount.core import getters from beancount.core import interpolate from beancount.utils import misc_utils ValidationError = collections.namedtuple('ValidationError', 'source message entry') ALLOW_AFTER_CLOSE = (Balance, Document, Note) class Open(NamedTuple): """ An "open account" directive. Attributes: meta: See above. date: See above. account: A string, the name of the account that is being opened. currencies: A list of strings, currencies that are allowed in this account. May be None, in which case it means that there are no restrictions on which currencies may be stored in this account. booking: A Booking enum, the booking method to use to disambiguate postings to this account (when zero or more than one postings match the specification), or None if not specified. In practice, this attribute will be should be left unspecified (None) in the vast majority of cases. See Booking below for a selection of valid methods. """ meta: Meta date: datetime.date account: Account currencies: List[Currency] booking: Optional[Booking] class Close(NamedTuple): """ A "close account" directive. Attributes: meta: See above. date: See above. account: A string, the name of the account that is being closed. """ meta: Meta date: datetime.date account: Account The provided code snippet includes necessary dependencies for implementing the `validate_active_accounts` function. Write a Python function `def validate_active_accounts(entries, unused_options_map)` to solve the following problem: Check that all references to accounts occurs on active accounts. We basically check that references to accounts from all directives other than Open and Close occur at dates the open-close interval of that account. This should be good for all of the directive types where we can extract an account name. Note that this is more strict a check than comparing the dates: we actually check that no references to account are made on the same day before the open directive appears for that account. This is a nice property to have, and is supported by our custom sorting routine that will sort open entries before transaction entries, given the same date. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found. Here is the function: def validate_active_accounts(entries, unused_options_map): """Check that all references to accounts occurs on active accounts. We basically check that references to accounts from all directives other than Open and Close occur at dates the open-close interval of that account. This should be good for all of the directive types where we can extract an account name. Note that this is more strict a check than comparing the dates: we actually check that no references to account are made on the same day before the open directive appears for that account. This is a nice property to have, and is supported by our custom sorting routine that will sort open entries before transaction entries, given the same date. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found. """ error_pairs = [] active_set = set() opened_accounts = set() for entry in entries: if isinstance(entry, data.Open): active_set.add(entry.account) opened_accounts.add(entry.account) elif isinstance(entry, data.Close): active_set.discard(entry.account) else: for account in getters.get_entry_accounts(entry): if account not in active_set: # Allow document and note directives that occur after an # account is closed. if (isinstance(entry, ALLOW_AFTER_CLOSE) and account in opened_accounts): continue # Register an error to be logged later, with an appropriate # message. error_pairs.append((account, entry)) # Refine the error message to disambiguate between the case of an account # that has never been seen and one that was simply not active at the time. errors = [] for account, entry in error_pairs: if account in opened_accounts: message = "Invalid reference to inactive account '{}'".format(account) else: message = "Invalid reference to unknown account '{}'".format(account) errors.append(ValidationError(entry.meta, message, entry)) return errors
Check that all references to accounts occurs on active accounts. We basically check that references to accounts from all directives other than Open and Close occur at dates the open-close interval of that account. This should be good for all of the directive types where we can extract an account name. Note that this is more strict a check than comparing the dates: we actually check that no references to account are made on the same day before the open directive appears for that account. This is a nice property to have, and is supported by our custom sorting routine that will sort open entries before transaction entries, given the same date. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found.
3,114
from os import path import collections from beancount.core.data import Open from beancount.core.data import Balance from beancount.core.data import Close from beancount.core.data import Transaction from beancount.core.data import Document from beancount.core.data import Note from beancount.core import data from beancount.core import getters from beancount.core import interpolate from beancount.utils import misc_utils ValidationError = collections.namedtuple('ValidationError', 'source message entry') class Open(NamedTuple): """ An "open account" directive. Attributes: meta: See above. date: See above. account: A string, the name of the account that is being opened. currencies: A list of strings, currencies that are allowed in this account. May be None, in which case it means that there are no restrictions on which currencies may be stored in this account. booking: A Booking enum, the booking method to use to disambiguate postings to this account (when zero or more than one postings match the specification), or None if not specified. In practice, this attribute will be should be left unspecified (None) in the vast majority of cases. See Booking below for a selection of valid methods. """ meta: Meta date: datetime.date account: Account currencies: List[Currency] booking: Optional[Booking] class Transaction(NamedTuple): """ A transaction! This is the main type of object that we manipulate, and the entire reason this whole project exists in the first place, because representing these types of structures with a spreadsheet is difficult. Attributes: meta: See above. date: See above. flag: A single-character string or None. This user-specified string represents some custom/user-defined state of the transaction. You can use this for various purposes. Otherwise common, pre-defined flags are defined under beancount.core.flags, to flags transactions that are automatically generated. payee: A free-form string that identifies the payee, or None, if absent. narration: A free-form string that provides a description for the transaction. All transactions have at least a narration string, this is never None. tags: A set of tag strings (without the '#'), or EMPTY_SET. links: A set of link strings (without the '^'), or EMPTY_SET. postings: A list of Posting instances, the legs of this transaction. See the doc under Posting above. """ meta: Meta date: datetime.date flag: Flag payee: Optional[str] narration: str tags: Set links: Set postings: List[Posting] The provided code snippet includes necessary dependencies for implementing the `validate_currency_constraints` function. Write a Python function `def validate_currency_constraints(entries, options_map)` to solve the following problem: Check the currency constraints from account open declarations. Open directives admit an optional list of currencies that specify the only types of commodities that the running inventory for this account may contain. This function checks that all postings are only made in those commodities. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found. Here is the function: def validate_currency_constraints(entries, options_map): """Check the currency constraints from account open declarations. Open directives admit an optional list of currencies that specify the only types of commodities that the running inventory for this account may contain. This function checks that all postings are only made in those commodities. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found. """ # Get all the open entries with currency constraints. open_map = {entry.account: entry for entry in entries if isinstance(entry, Open) and entry.currencies} errors = [] for entry in entries: if not isinstance(entry, Transaction): continue for posting in entry.postings: # Look up the corresponding account's valid currencies; skip the # check if there are none specified. try: open_entry = open_map[posting.account] valid_currencies = open_entry.currencies if not valid_currencies: continue except KeyError: continue # Perform the check. if posting.units.currency not in valid_currencies: errors.append( ValidationError( entry.meta, "Invalid currency {} for account '{}'".format( posting.units.currency, posting.account), entry)) return errors
Check the currency constraints from account open declarations. Open directives admit an optional list of currencies that specify the only types of commodities that the running inventory for this account may contain. This function checks that all postings are only made in those commodities. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found.
3,115
from os import path import collections from beancount.core.data import Open from beancount.core.data import Balance from beancount.core.data import Close from beancount.core.data import Transaction from beancount.core.data import Document from beancount.core.data import Note from beancount.core import data from beancount.core import getters from beancount.core import interpolate from beancount.utils import misc_utils ValidationError = collections.namedtuple('ValidationError', 'source message entry') class Document(NamedTuple): """ A document file declaration directive. This directive is used to attach a statement to an account, at a particular date. A typical usage would be to render PDF files or scans of your bank statements into the account's journal. While you can explicitly create those directives in the input syntax, it is much more convenient to provide Beancount with a root directory to search for filenames in a hierarchy mirroring the chart of accounts, filenames which should match the following dated format: "YYYY-MM-DD.*". See options for detail. Beancount will automatically create these documents directives based on the file hierarchy, and you can get them by parsing the list of entries. Attributes: meta: See above. date: See above. account: A string, the account which the statement or document is associated with. filename: The absolute filename of the document file. tags: A set of tag strings (without the '#'), or None, if an empty set. links: A set of link strings (without the '^'), or None, if an empty set. """ meta: Meta date: datetime.date account: Account filename: str tags: Optional[Set] links: Optional[Set] The provided code snippet includes necessary dependencies for implementing the `validate_documents_paths` function. Write a Python function `def validate_documents_paths(entries, options_map)` to solve the following problem: Check that all filenames in resolved Document entries are absolute filenames. The processing of document entries is assumed to result in absolute paths. Relative paths are resolved at the parsing stage and at point we want to make sure we don't have to do any further processing on them. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found. Here is the function: def validate_documents_paths(entries, options_map): """Check that all filenames in resolved Document entries are absolute filenames. The processing of document entries is assumed to result in absolute paths. Relative paths are resolved at the parsing stage and at point we want to make sure we don't have to do any further processing on them. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found. """ return [ValidationError(entry.meta, "Invalid relative path for entry", entry) for entry in entries if (isinstance(entry, Document) and not path.isabs(entry.filename))]
Check that all filenames in resolved Document entries are absolute filenames. The processing of document entries is assumed to result in absolute paths. Relative paths are resolved at the parsing stage and at point we want to make sure we don't have to do any further processing on them. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found.
3,116
from os import path import collections from beancount.core.data import Open from beancount.core.data import Balance from beancount.core.data import Close from beancount.core.data import Transaction from beancount.core.data import Document from beancount.core.data import Note from beancount.core import data from beancount.core import getters from beancount.core import interpolate from beancount.utils import misc_utils ValidationError = collections.namedtuple('ValidationError', 'source message entry') The provided code snippet includes necessary dependencies for implementing the `validate_data_types` function. Write a Python function `def validate_data_types(entries, options_map)` to solve the following problem: Check that all the data types of the attributes of entries are as expected. Users are provided with a means to filter the list of entries. They're able to write code that manipulates those tuple objects without any type constraints. With discipline, this mostly works, but I know better: check, just to make sure. This routine checks all the data types and assumptions on entries. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found. Here is the function: def validate_data_types(entries, options_map): """Check that all the data types of the attributes of entries are as expected. Users are provided with a means to filter the list of entries. They're able to write code that manipulates those tuple objects without any type constraints. With discipline, this mostly works, but I know better: check, just to make sure. This routine checks all the data types and assumptions on entries. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found. """ errors = [] for entry in entries: try: data.sanity_check_types( entry, options_map["allow_deprecated_none_for_tags_and_links"]) except AssertionError as exc: errors.append( ValidationError(entry.meta, "Invalid data types: {}".format(exc), entry)) return errors
Check that all the data types of the attributes of entries are as expected. Users are provided with a means to filter the list of entries. They're able to write code that manipulates those tuple objects without any type constraints. With discipline, this mostly works, but I know better: check, just to make sure. This routine checks all the data types and assumptions on entries. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found.
3,117
from os import path import collections from beancount.core.data import Open from beancount.core.data import Balance from beancount.core.data import Close from beancount.core.data import Transaction from beancount.core.data import Document from beancount.core.data import Note from beancount.core import data from beancount.core import getters from beancount.core import interpolate from beancount.utils import misc_utils ValidationError = collections.namedtuple('ValidationError', 'source message entry') class Transaction(NamedTuple): """ A transaction! This is the main type of object that we manipulate, and the entire reason this whole project exists in the first place, because representing these types of structures with a spreadsheet is difficult. Attributes: meta: See above. date: See above. flag: A single-character string or None. This user-specified string represents some custom/user-defined state of the transaction. You can use this for various purposes. Otherwise common, pre-defined flags are defined under beancount.core.flags, to flags transactions that are automatically generated. payee: A free-form string that identifies the payee, or None, if absent. narration: A free-form string that provides a description for the transaction. All transactions have at least a narration string, this is never None. tags: A set of tag strings (without the '#'), or EMPTY_SET. links: A set of link strings (without the '^'), or EMPTY_SET. postings: A list of Posting instances, the legs of this transaction. See the doc under Posting above. """ meta: Meta date: datetime.date flag: Flag payee: Optional[str] narration: str tags: Set links: Set postings: List[Posting] The provided code snippet includes necessary dependencies for implementing the `validate_check_transaction_balances` function. Write a Python function `def validate_check_transaction_balances(entries, options_map)` to solve the following problem: Check again that all transaction postings balance, as users may have transformed transactions. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found. Here is the function: def validate_check_transaction_balances(entries, options_map): """Check again that all transaction postings balance, as users may have transformed transactions. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found. """ # Note: this is a bit slow; we could limit our checks to the original # transactions by using the hash function in the loader. errors = [] for entry in entries: if isinstance(entry, Transaction): # IMPORTANT: This validation is _crucial_ and cannot be skipped. # This is where we actually detect and warn on unbalancing # transactions. This _must_ come after the user routines, because # unbalancing input is legal, as those types of transactions may be # "fixed up" by a user-plugin. In other words, we want to allow # users to input unbalancing transactions as long as the final # transactions objects that appear on the stream (after processing # the plugins) are balanced. See {9e6c14b51a59}. # # Detect complete sets of postings that have residual balance; residual = interpolate.compute_residual(entry.postings) tolerances = interpolate.infer_tolerances(entry.postings, options_map) if not residual.is_small(tolerances): errors.append( ValidationError(entry.meta, "Transaction does not balance: {}".format(residual), entry)) return errors
Check again that all transaction postings balance, as users may have transformed transactions. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found.
3,118
import datetime import re import beancount from beancount.parser import _parser The provided code snippet includes necessary dependencies for implementing the `compute_version_string` function. Write a Python function `def compute_version_string(version, changeset, timestamp)` to solve the following problem: Compute a version string from the changeset and timestamp baked in the parser. Args: version: A string, the version number. changeset: A string, a version control string identifying the commit of the version. timestamp: An integer, the UNIX epoch timestamp of the changeset. Returns: A human-readable string for the version. Here is the function: def compute_version_string(version, changeset, timestamp): """Compute a version string from the changeset and timestamp baked in the parser. Args: version: A string, the version number. changeset: A string, a version control string identifying the commit of the version. timestamp: An integer, the UNIX epoch timestamp of the changeset. Returns: A human-readable string for the version. """ # Shorten changeset. if changeset: if re.match('hg:', changeset): changeset = changeset[:15] elif re.match('git:', changeset): changeset = changeset[:12] # Convert timestamp to a date. date = None if timestamp > 0: date = datetime.datetime.utcfromtimestamp(timestamp).date() version = 'Beancount {}'.format(version) if changeset or date: version = '{} ({})'.format( version, '; '.join(map(str, filter(None, [changeset, date])))) return version
Compute a version string from the changeset and timestamp baked in the parser. Args: version: A string, the version number. changeset: A string, a version control string identifying the commit of the version. timestamp: An integer, the UNIX epoch timestamp of the changeset. Returns: A human-readable string for the version.
3,119
import collections import contextlib import io from beancount.core.data import new_metadata from beancount.parser import _parser def lex_iter(file, builder=None): """An iterator that yields all the tokens in the given file. Args: file: A string, the filename to run the lexer on, or a file object. builder: A builder of your choice. If not specified, a LexBuilder is used and discarded (along with its errors). Yields: All the tokens in the input file as ``(token, lineno, text, value)`` tuples where ``token`` is a string representing the token kind, ``lineno`` is the line number in the input file where the token was matched, ``mathed`` is a bytes object containing the exact text matched, and ``value`` is the semantic value of the token or None. """ with contextlib.ExitStack() as ctx: # It would be more appropriate here to check for io.RawIOBase but # that does not work for io.BytesIO despite it implementing the # readinto() method. if not isinstance(file, io.IOBase): file = ctx.enter_context(open(file, 'rb')) if builder is None: builder = LexBuilder() parser = _parser.Parser(builder) yield from parser.lex(file) The provided code snippet includes necessary dependencies for implementing the `lex_iter_string` function. Write a Python function `def lex_iter_string(string, builder=None, **kwargs)` to solve the following problem: An iterator that yields all the tokens in the given string. Args: string: a str or bytes, the contents of the ledger to be parsed. Returns: An iterator, see ``lex_iter()`` for details. Here is the function: def lex_iter_string(string, builder=None, **kwargs): """An iterator that yields all the tokens in the given string. Args: string: a str or bytes, the contents of the ledger to be parsed. Returns: An iterator, see ``lex_iter()`` for details. """ if not isinstance(string, bytes): string = string.encode('utf8') file = io.BytesIO(string) yield from lex_iter(file, builder=builder, **kwargs)
An iterator that yields all the tokens in the given string. Args: string: a str or bytes, the contents of the ledger to be parsed. Returns: An iterator, see ``lex_iter()`` for details.
3,120
import codecs import datetime import enum import io import re import sys import textwrap from decimal import Decimal from typing import Optional from beancount.core import position from beancount.core import convert from beancount.core import inventory from beancount.core import amount from beancount.core import account from beancount.core import data from beancount.core import interpolate from beancount.core import display_context from beancount.utils import misc_utils The provided code snippet includes necessary dependencies for implementing the `align_position_strings` function. Write a Python function `def align_position_strings(strings)` to solve the following problem: A helper used to align rendered amounts positions to their first currency character (an uppercase letter). This class accepts a list of rendered positions and calculates the necessary width to render them stacked in a column so that the first currency word aligns. It does not go beyond that (further currencies, e.g. for the price or cost, are not aligned). This is perhaps best explained with an example. The following positions will be aligned around the column marked with '^': 45 HOOL {504.30 USD} 4 HOOL {504.30 USD, 2014-11-11} 9.95 USD -22473.32 CAD @ 1.10 USD ^ Strings without a currency character will be rendered flush left. Args: strings: A list of rendered position or amount strings. Returns: A pair of a list of aligned strings and the width of the aligned strings. Here is the function: def align_position_strings(strings): """A helper used to align rendered amounts positions to their first currency character (an uppercase letter). This class accepts a list of rendered positions and calculates the necessary width to render them stacked in a column so that the first currency word aligns. It does not go beyond that (further currencies, e.g. for the price or cost, are not aligned). This is perhaps best explained with an example. The following positions will be aligned around the column marked with '^': 45 HOOL {504.30 USD} 4 HOOL {504.30 USD, 2014-11-11} 9.95 USD -22473.32 CAD @ 1.10 USD ^ Strings without a currency character will be rendered flush left. Args: strings: A list of rendered position or amount strings. Returns: A pair of a list of aligned strings and the width of the aligned strings. """ # Maximum length before the alignment character. max_before = 0 # Maximum length after the alignment character. max_after = 0 # Maximum length of unknown strings. max_unknown = 0 string_items = [] search = re.compile('[A-Z]').search for string in strings: match = search(string) if match: index = match.start() if index != 0: max_before = max(index, max_before) max_after = max(len(string) - index, max_after) string_items.append((index, string)) continue # else max_unknown = max(len(string), max_unknown) string_items.append((None, string)) # Compute formatting string. max_total = max(max_before + max_after, max_unknown) max_after_prime = max_total - max_before fmt = "{{:>{0}}}{{:{1}}}".format(max_before, max_after_prime).format fmt_unknown = "{{:<{0}}}".format(max_total).format # Align the strings and return them. # pylint: disable=format-string-without-interpolation aligned_strings = [] for index, string in string_items: # pylint: disable=format-string-without-interpolation if index is not None: string = fmt(string[:index], string[index:]) else: string = fmt_unknown(string) aligned_strings.append(string) return aligned_strings, max_total
A helper used to align rendered amounts positions to their first currency character (an uppercase letter). This class accepts a list of rendered positions and calculates the necessary width to render them stacked in a column so that the first currency word aligns. It does not go beyond that (further currencies, e.g. for the price or cost, are not aligned). This is perhaps best explained with an example. The following positions will be aligned around the column marked with '^': 45 HOOL {504.30 USD} 4 HOOL {504.30 USD, 2014-11-11} 9.95 USD -22473.32 CAD @ 1.10 USD ^ Strings without a currency character will be rendered flush left. Args: strings: A list of rendered position or amount strings. Returns: A pair of a list of aligned strings and the width of the aligned strings.
3,121
import codecs import datetime import enum import io import re import sys import textwrap from decimal import Decimal from typing import Optional from beancount.core import position from beancount.core import convert from beancount.core import inventory from beancount.core import amount from beancount.core import account from beancount.core import data from beancount.core import interpolate from beancount.core import display_context from beancount.utils import misc_utils The provided code snippet includes necessary dependencies for implementing the `render_flag` function. Write a Python function `def render_flag(inflag: Optional[str]) -> str` to solve the following problem: Render a flag, which can be None, a symbol of a character to a string. Here is the function: def render_flag(inflag: Optional[str]) -> str: """Render a flag, which can be None, a symbol of a character to a string.""" if not inflag: return '' return inflag
Render a flag, which can be None, a symbol of a character to a string.
3,122
import codecs import datetime import enum import io import re import sys import textwrap from decimal import Decimal from typing import Optional from beancount.core import position from beancount.core import convert from beancount.core import inventory from beancount.core import amount from beancount.core import account from beancount.core import data from beancount.core import interpolate from beancount.core import display_context from beancount.utils import misc_utils def format_error(error): """Given an error objects, return a formatted string for it. Args: error: a namedtuple objects representing an error. It has to have an 'entry' attribute that may be either a single directive object or a list of directive objects. Returns: A string, the errors rendered. """ oss = io.StringIO() oss.write('{} {}\n'.format(render_source(error.source), error.message)) if error.entry is not None: entries = error.entry if isinstance(error.entry, list) else [error.entry] error_string = '\n'.join(format_entry(entry) for entry in entries) oss.write('\n') oss.write(textwrap.indent(error_string, ' ')) oss.write('\n') return oss.getvalue() The provided code snippet includes necessary dependencies for implementing the `print_error` function. Write a Python function `def print_error(error, file=None)` to solve the following problem: A convenience function that prints a single error to a file. Args: error: An error object. file: An optional file object to write the errors to. Here is the function: def print_error(error, file=None): """A convenience function that prints a single error to a file. Args: error: An error object. file: An optional file object to write the errors to. """ output = file or sys.stdout output.write(format_error(error)) output.write('\n')
A convenience function that prints a single error to a file. Args: error: An error object. file: An optional file object to write the errors to.
3,123
import codecs import contextlib import functools import inspect import textwrap import io import sys from beancount.parser import _parser from beancount.parser import grammar from beancount.parser import printer from beancount.parser import hashsrc from beancount.core import data from beancount.core.number import MISSING from beancount.parser.grammar import ParserError from beancount.parser.grammar import ParserSyntaxError from beancount.parser.grammar import DeprecatedError def is_entry_incomplete(entry): """Detect the presence of elided amounts in Transactions. Args: entries: A directive. Returns: A boolean, true if there are some missing portions of any postings found. """ if isinstance(entry, data.Transaction): if any(is_posting_incomplete(posting) for posting in entry.postings): return True return False def parse_string(string, report_filename=None, dedent=False, **kw): """Parse a beancount input file and return Ledger with the list of transactions and tree of accounts. Args: string: A string, the contents to be parsed instead of a file's. report_filename: A string, the source filename from which this string has been extracted, if any. This is stored in the metadata of the parsed entries. dedent: Whether to run textwrap.dedent() on the string before parsing. **kw: See parse.c. Return: Same as the output of parse_file(). """ if dedent: string = textwrap.dedent(string) if isinstance(string, str): string = string.encode('utf8') if report_filename is None: report_filename = '<string>' file = io.BytesIO(string) return parse_file(file, report_filename=report_filename, **kw) The provided code snippet includes necessary dependencies for implementing the `parse_doc` function. Write a Python function `def parse_doc(expect_errors=False, allow_incomplete=False)` to solve the following problem: Factory of decorators that parse the function's docstring as an argument. Note that the decorators thus generated only run the parser on the tests, not the loader, so is no validation, balance checks, nor plugins applied to the parsed text. Args: expect_errors: A boolean or None, with the following semantics, True: Expect errors and fail if there are none. False: Expect no errors and fail if there are some. None: Do nothing, no check. allow_incomplete: A boolean, if true, allow incomplete input. Otherwise barf if the input would require interpolation. The default value is set not to allow it because we want to minimize the features tests depend on. Returns: A decorator for test functions. Here is the function: def parse_doc(expect_errors=False, allow_incomplete=False): """Factory of decorators that parse the function's docstring as an argument. Note that the decorators thus generated only run the parser on the tests, not the loader, so is no validation, balance checks, nor plugins applied to the parsed text. Args: expect_errors: A boolean or None, with the following semantics, True: Expect errors and fail if there are none. False: Expect no errors and fail if there are some. None: Do nothing, no check. allow_incomplete: A boolean, if true, allow incomplete input. Otherwise barf if the input would require interpolation. The default value is set not to allow it because we want to minimize the features tests depend on. Returns: A decorator for test functions. """ def decorator(fun): """A decorator that parses the function's docstring as an argument. Args: fun: the function object to be decorated. Returns: A decorated test function. """ filename = inspect.getfile(fun) lines, lineno = inspect.getsourcelines(fun) # Skip over decorator invocation and function definition. This # is imperfect as it assumes that each consumes exactly one # line, but this is by far the most common case, and this is # mainly used in test, thus it is good enough. lineno += 2 @functools.wraps(fun) def wrapper(self): assert fun.__doc__ is not None, ( "You need to insert a docstring on {}".format(fun.__name__)) entries, errors, options_map = parse_string(fun.__doc__, report_filename=filename, report_firstline=lineno, dedent=True) if not allow_incomplete and any(is_entry_incomplete(entry) for entry in entries): self.fail("parse_doc() may not use interpolation.") if expect_errors is not None: if expect_errors is False and errors: oss = io.StringIO() printer.print_errors(errors, file=oss) self.fail("Unexpected errors found:\n{}".format(oss.getvalue())) elif expect_errors is True and not errors: self.fail("Expected errors, none found:") return fun(self, entries, errors, options_map) return wrapper return decorator
Factory of decorators that parse the function's docstring as an argument. Note that the decorators thus generated only run the parser on the tests, not the loader, so is no validation, balance checks, nor plugins applied to the parsed text. Args: expect_errors: A boolean or None, with the following semantics, True: Expect errors and fail if there are none. False: Expect no errors and fail if there are some. None: Do nothing, no check. allow_incomplete: A boolean, if true, allow incomplete input. Otherwise barf if the input would require interpolation. The default value is set not to allow it because we want to minimize the features tests depend on. Returns: A decorator for test functions.
3,124
import codecs import contextlib import functools import inspect import textwrap import io import sys from beancount.parser import _parser from beancount.parser import grammar from beancount.parser import printer from beancount.parser import hashsrc from beancount.core import data from beancount.core.number import MISSING from beancount.parser.grammar import ParserError from beancount.parser.grammar import ParserSyntaxError from beancount.parser.grammar import DeprecatedError def parse_many(string, level=0): """Parse a string with a snippet of Beancount input and replace vars from caller. Args: string: A string with some Beancount input. level: The number of extra stacks to ignore. Returns: A list of entries. Raises: AssertionError: If there are any errors. """ # Get the locals in the stack for the callers and produce the final text. frame = inspect.stack()[level+1] varkwds = frame[0].f_locals input_string = textwrap.dedent(string.format(**varkwds)) # Parse entries and check there are no errors. entries, errors, __ = parse_string(input_string) assert not errors return entries The provided code snippet includes necessary dependencies for implementing the `parse_one` function. Write a Python function `def parse_one(string)` to solve the following problem: Parse a string with single Beancount directive and replace vars from caller. Args: string: A string with some Beancount input. level: The number of extra stacks to ignore. Returns: A list of entries. Raises: AssertionError: If there are any errors. Here is the function: def parse_one(string): """Parse a string with single Beancount directive and replace vars from caller. Args: string: A string with some Beancount input. level: The number of extra stacks to ignore. Returns: A list of entries. Raises: AssertionError: If there are any errors. """ entries = parse_many(string, level=1) assert len(entries) == 1 return entries[0]
Parse a string with single Beancount directive and replace vars from caller. Args: string: A string with some Beancount input. level: The number of extra stacks to ignore. Returns: A list of entries. Raises: AssertionError: If there are any errors.
3,125
import collections import copy import traceback from os import path from datetime import date from decimal import Decimal import regex from beancount.core.number import ZERO from beancount.core.number import MISSING from beancount.core.amount import Amount from beancount.core import display_context from beancount.core.position import CostSpec from beancount.core.data import Transaction from beancount.core.data import Balance from beancount.core.data import Open from beancount.core.data import Close from beancount.core.data import Commodity from beancount.core.data import Pad from beancount.core.data import Event from beancount.core.data import Query from beancount.core.data import Price from beancount.core.data import Note from beancount.core.data import Document from beancount.core.data import Custom from beancount.core.data import new_metadata from beancount.core.data import Posting from beancount.core.data import Booking from beancount.core.data import EMPTY_SET from beancount.parser import lexer from beancount.parser import options from beancount.core import account from beancount.core import data The provided code snippet includes necessary dependencies for implementing the `valid_account_regexp` function. Write a Python function `def valid_account_regexp(options)` to solve the following problem: Build a regexp to validate account names from the options. Args: options: A dict of options, as per beancount.parser.options. Returns: A string, a regular expression that will match all account names. Here is the function: def valid_account_regexp(options): """Build a regexp to validate account names from the options. Args: options: A dict of options, as per beancount.parser.options. Returns: A string, a regular expression that will match all account names. """ names = map(options.__getitem__, ('name_assets', 'name_liabilities', 'name_equity', 'name_income', 'name_expenses')) # Replace the first term of the account regular expression with the specific # names allowed under the options configuration. This code is kept in sync # with {5672c7270e1e}. return regex.compile("(?:{})(?:{}{})+".format('|'.join(names), account.sep, account.ACC_COMP_NAME_RE))
Build a regexp to validate account names from the options. Args: options: A dict of options, as per beancount.parser.options. Returns: A string, a regular expression that will match all account names.
3,126
import collections import io import re import textwrap from beancount.core.number import D from beancount.core import data from beancount.core import account_types from beancount.core import account from beancount.core import display_context The provided code snippet includes necessary dependencies for implementing the `options_validate_processing_mode` function. Write a Python function `def options_validate_processing_mode(value)` to solve the following problem: Validate the options processing mode. Args: value: A string, the value provided as option. Returns: The new value, converted, if the conversion is successful. Raises: ValueError: If the value is invalid. Here is the function: def options_validate_processing_mode(value): """Validate the options processing mode. Args: value: A string, the value provided as option. Returns: The new value, converted, if the conversion is successful. Raises: ValueError: If the value is invalid. """ if value not in ('raw', 'default'): raise ValueError("Invalid value '{}'".format(value)) return value
Validate the options processing mode. Args: value: A string, the value provided as option. Returns: The new value, converted, if the conversion is successful. Raises: ValueError: If the value is invalid.
3,127
import collections import io import re import textwrap from beancount.core.number import D from beancount.core import data from beancount.core import account_types from beancount.core import account from beancount.core import display_context The provided code snippet includes necessary dependencies for implementing the `options_validate_plugin` function. Write a Python function `def options_validate_plugin(value)` to solve the following problem: Validate the plugin option. Args: value: A string, the value provided as option. Returns: The new value, converted, if the conversion is successful. Raises: ValueError: If the value is invalid. Here is the function: def options_validate_plugin(value): """Validate the plugin option. Args: value: A string, the value provided as option. Returns: The new value, converted, if the conversion is successful. Raises: ValueError: If the value is invalid. """ # Process the 'plugin' option specially: accept an optional # argument from it. NOTE: We will eventually phase this out and # replace it by a dedicated 'plugin' directive. match = re.match('(.*):(.*)', value) if match: plugin_name, plugin_config = match.groups() else: plugin_name, plugin_config = value, None return (plugin_name, plugin_config)
Validate the plugin option. Args: value: A string, the value provided as option. Returns: The new value, converted, if the conversion is successful. Raises: ValueError: If the value is invalid.
3,128
import collections import io import re import textwrap from beancount.core.number import D from beancount.core import data from beancount.core import account_types from beancount.core import account from beancount.core import display_context def D(strord=None): """Convert a string into a Decimal object. This is used in parsing amounts from files in the importers. This is the main function you should use to build all numbers the system manipulates (never use floating-point in an accounting system). Commas are stripped and ignored, as they are assumed to be thousands separators (the French comma separator as decimal is not supported). This function just returns the argument if it is already a Decimal object, for convenience. Args: strord: A string or Decimal instance. Returns: A Decimal instance. """ try: # Note: try a map lookup and optimize performance here. if strord is None or strord == '': return Decimal() elif isinstance(strord, str): return Decimal(_CLEAN_NUMBER_RE.sub('', strord)) elif isinstance(strord, Decimal): return strord elif isinstance(strord, (int, float)): return Decimal(strord) else: assert strord is None, "Invalid value to convert: {}".format(strord) except Exception as exc: raise ValueError("Impossible to create Decimal instance from {!s}: {}".format( strord, exc)) from exc The provided code snippet includes necessary dependencies for implementing the `options_validate_tolerance` function. Write a Python function `def options_validate_tolerance(value)` to solve the following problem: Validate the tolerance option. Args: value: A string, the value provided as option. Returns: The new value, converted, if the conversion is successful. Raises: ValueError: If the value is invalid. Here is the function: def options_validate_tolerance(value): """Validate the tolerance option. Args: value: A string, the value provided as option. Returns: The new value, converted, if the conversion is successful. Raises: ValueError: If the value is invalid. """ return D(value)
Validate the tolerance option. Args: value: A string, the value provided as option. Returns: The new value, converted, if the conversion is successful. Raises: ValueError: If the value is invalid.
3,129
import collections import io import re import textwrap from beancount.core.number import D from beancount.core import data from beancount.core import account_types from beancount.core import account from beancount.core import display_context def D(strord=None): """Convert a string into a Decimal object. This is used in parsing amounts from files in the importers. This is the main function you should use to build all numbers the system manipulates (never use floating-point in an accounting system). Commas are stripped and ignored, as they are assumed to be thousands separators (the French comma separator as decimal is not supported). This function just returns the argument if it is already a Decimal object, for convenience. Args: strord: A string or Decimal instance. Returns: A Decimal instance. """ try: # Note: try a map lookup and optimize performance here. if strord is None or strord == '': return Decimal() elif isinstance(strord, str): return Decimal(_CLEAN_NUMBER_RE.sub('', strord)) elif isinstance(strord, Decimal): return strord elif isinstance(strord, (int, float)): return Decimal(strord) else: assert strord is None, "Invalid value to convert: {}".format(strord) except Exception as exc: raise ValueError("Impossible to create Decimal instance from {!s}: {}".format( strord, exc)) from exc The provided code snippet includes necessary dependencies for implementing the `options_validate_tolerance_map` function. Write a Python function `def options_validate_tolerance_map(value)` to solve the following problem: Validate an option with a map of currency/tolerance pairs in a string. Args: value: A string, the value provided as option. Returns: The new value, converted, if the conversion is successful. Raises: ValueError: If the value is invalid. Here is the function: def options_validate_tolerance_map(value): """Validate an option with a map of currency/tolerance pairs in a string. Args: value: A string, the value provided as option. Returns: The new value, converted, if the conversion is successful. Raises: ValueError: If the value is invalid. """ # Process the setting of a key-value, whereby the value is a Decimal # representation. match = re.match('(.*):(.*)', value) if not match: raise ValueError("Invalid value '{}'".format(value)) currency, tolerance_str = match.groups() return (currency, D(tolerance_str))
Validate an option with a map of currency/tolerance pairs in a string. Args: value: A string, the value provided as option. Returns: The new value, converted, if the conversion is successful. Raises: ValueError: If the value is invalid.
3,130
import collections import io import re import textwrap from beancount.core.number import D from beancount.core import data from beancount.core import account_types from beancount.core import account from beancount.core import display_context The provided code snippet includes necessary dependencies for implementing the `options_validate_boolean` function. Write a Python function `def options_validate_boolean(value)` to solve the following problem: Validate a boolean option. Args: value: A string, the value provided as option. Returns: The new value, converted, if the conversion is successful. Raises: ValueError: If the value is invalid. Here is the function: def options_validate_boolean(value): """Validate a boolean option. Args: value: A string, the value provided as option. Returns: The new value, converted, if the conversion is successful. Raises: ValueError: If the value is invalid. """ return value.lower() in ('1', 'true', 'yes')
Validate a boolean option. Args: value: A string, the value provided as option. Returns: The new value, converted, if the conversion is successful. Raises: ValueError: If the value is invalid.
3,131
import collections import io import re import textwrap from beancount.core.number import D from beancount.core import data from beancount.core import account_types from beancount.core import account from beancount.core import display_context The provided code snippet includes necessary dependencies for implementing the `options_validate_booking_method` function. Write a Python function `def options_validate_booking_method(value)` to solve the following problem: Validate a booking method name. Args: value: A string, the value provided as option. Returns: The new value, converted, if the conversion is successful. Raises: ValueError: If the value is invalid. Here is the function: def options_validate_booking_method(value): """Validate a booking method name. Args: value: A string, the value provided as option. Returns: The new value, converted, if the conversion is successful. Raises: ValueError: If the value is invalid. """ try: return data.Booking[value] except KeyError as exc: raise ValueError(str(exc)) from exc
Validate a booking method name. Args: value: A string, the value provided as option. Returns: The new value, converted, if the conversion is successful. Raises: ValueError: If the value is invalid.
3,132
import collections import io import re import textwrap from beancount.core.number import D from beancount.core import data from beancount.core import account_types from beancount.core import account from beancount.core import display_context OptDesc = collections.namedtuple( 'OptDesc', 'name default_value example_value converter deprecated alias') UNSET = object() The provided code snippet includes necessary dependencies for implementing the `Opt` function. Write a Python function `def Opt(name, default_value, example_value=UNSET, converter=None, deprecated=False, alias=None)` to solve the following problem: Alternative constructor for OptDesc, with default values. Args: name: See OptDesc. default_value: See OptDesc. example_value: See OptDesc. converter: See OptDesc. deprecated: See OptDesc. alias: See OptDesc. Returns: An instance of OptDesc. Here is the function: def Opt(name, default_value, example_value=UNSET, converter=None, deprecated=False, alias=None): """Alternative constructor for OptDesc, with default values. Args: name: See OptDesc. default_value: See OptDesc. example_value: See OptDesc. converter: See OptDesc. deprecated: See OptDesc. alias: See OptDesc. Returns: An instance of OptDesc. """ if example_value is UNSET: example_value = default_value return OptDesc(name, default_value, example_value, converter, deprecated, alias)
Alternative constructor for OptDesc, with default values. Args: name: See OptDesc. default_value: See OptDesc. example_value: See OptDesc. converter: See OptDesc. deprecated: See OptDesc. alias: See OptDesc. Returns: An instance of OptDesc.
3,133
import collections import io import re import textwrap from beancount.core.number import D from beancount.core import data from beancount.core import account_types from beancount.core import account from beancount.core import display_context The provided code snippet includes necessary dependencies for implementing the `get_unrealized_account` function. Write a Python function `def get_unrealized_account(options)` to solve the following problem: Return the full account name for the unrealized account. Args: options: a dict of ledger options. Returns: A tuple of 2 account objects, one for booking current earnings, and one for current conversions. Here is the function: def get_unrealized_account(options): """Return the full account name for the unrealized account. Args: options: a dict of ledger options. Returns: A tuple of 2 account objects, one for booking current earnings, and one for current conversions. """ income = options['name_income'] return account.join(income, options['account_unrealized_gains'])
Return the full account name for the unrealized account. Args: options: a dict of ledger options. Returns: A tuple of 2 account objects, one for booking current earnings, and one for current conversions.
3,134
import collections import io import re import textwrap from beancount.core.number import D from beancount.core import data from beancount.core import account_types from beancount.core import account from beancount.core import display_context PUBLIC_OPTION_GROUPS = [ OptGroup(""" The title of this ledger / input file. This shows up at the top of every page. """, [Opt("title", "Beancount", "Joe Smith's Personal Ledger")]), OptGroup(""" Root names of every account. This can be used to customize your category names, so that if you prefer "Revenue" over "Income" or "Capital" over "Equity", you can set them here. The account names in your input files must match, and the parser will validate these. You should place these options at the beginning of your file, because they affect how the parser recognizes account names. """, [ Opt("name_assets", _TYPES.assets), Opt("name_liabilities", _TYPES.liabilities), Opt("name_equity", _TYPES.equity), Opt("name_income", _TYPES.income), Opt("name_expenses", _TYPES.expenses), ]), OptGroup(""" Leaf name of the equity account used for summarizing previous transactions into opening balances. """, [Opt("account_previous_balances", "Opening-Balances")]), OptGroup(""" Leaf name of the equity account used for transferring previous retained earnings from income and expenses accrued before the beginning of the exercise into the balance sheet. """, [Opt("account_previous_earnings", "Earnings:Previous")]), OptGroup(""" Leaf name of the equity account used for inserting conversions that will zero out remaining amounts due to transfers before the opening date. This will essentially "fixup" the basic accounting equation due to the errors that priced conversions introduce. """, [Opt("account_previous_conversions", "Conversions:Previous")]), OptGroup(""" Leaf name of the equity account used for transferring current retained earnings from income and expenses accrued during the current exercise into the balance sheet. This is most often called "Net Income". """, [Opt("account_current_earnings", "Earnings:Current")]), OptGroup(""" Leaf name of the equity account used for inserting conversions that will zero out remaining amounts due to transfers during the exercise period. """, [Opt("account_current_conversions", "Conversions:Current")]), OptGroup(""" The name of an account to be used to post unrealized gains to. This is used when making any kind of conversion from cost to price on a balance sheet (or any realization). The amount inserted - the difference between book value and market value - has to be posted to a gains account to keep the balance on the sheet. This has no effect on behavior, other than providing a configurable account name for such postings to occur. """, [Opt("account_unrealized_gains", "Earnings:Unrealized", "Earnings:Unrealized")]), OptGroup(""" The name of an account to be used to post to and accumulate rounding error. This is unset and this feature is disabled by default; setting this value to an account name will automatically enable the addition of postings on all transactions that have a residual amount. """, [Opt("account_rounding", None, "Rounding")]), OptGroup(""" The imaginary currency used to convert all units for conversions at a degenerate rate of zero. This can be any currency name that isn't used in the rest of the ledger. Choose something unique that makes sense in your language. """, [Opt("conversion_currency", "NOTHING")]), OptGroup(""" Mappings of currency to the tolerance used when it cannot be inferred automatically. The tolerance at hand is the one used for verifying (1) that transactions balance, (2) explicit balance checks from 'balance' directives balance, and (3) in the tolerance used for padding (from the 'pad' directive). The values must be strings in the following format: <currency>:<tolerance> for example, 'USD:0.005'. By default, the tolerance allowed for currencies without an inferred value is zero. As a special case, this value, that is, the fallback value used for all currencies without an explicit default can be overridden using the '*' currency, like this: '*:0.5'. Used by itself, this last example sets the fallabck tolerance as '0.5' for all currencies. For detailed documentation about how tolerances are handled, see this doc: http://furius.ca/beancount/doc/tolerances """, [Opt("inferred_tolerance_default", {}, "CHF:0.01", converter=options_validate_tolerance_map)]), OptGroup(""" A multiplier for inferred tolerance values. When the tolerance values aren't specified explicitly via the 'inferred_tolerance_default' option, the tolerance is inferred from the numbers in the input file. For example, if a transaction has posting with a value like '32.424 CAD', the tolerance for CAD will be inferred to be 0.001 times some multiplier. This is the muliplier value. We normally assume that the institution we're reproducing this posting from applies rounding, and so the default value for the multiplier is 0.5, that is, half of the smallest digit encountered. You can customize this multiplier by changing this option, typically expanding it to account for amounts slightly beyond the usual tolerance, for example, if you deal with institutions with bad of unexpected rounding behaviour. For detailed documentation about how tolerances are handled, see this doc: http://furius.ca/beancount/doc/tolerances """, [Opt("inferred_tolerance_multiplier", D("0.5"), "1.1", converter=D)]), OptGroup(""" Enable a feature that expands the maximum tolerance inferred on transactions to include values on cost currencies inferred by postings held at-cost or converted at price. Those postings can imply a tolerance value by multiplying the smallest digit of the unit by the cost or price value and taking half of that value. For example, if a posting has an amount of "2.345 RGAGX {45.00 USD}" attached to it, it implies a tolerance of 0.001 x 45.00 * M = 0.045 USD (where M is the inferred_tolerance_multiplier) and this is added to the mix to enlarge the tolerance allowed for units of USD on that transaction. All the normally inferred tolerances (see http://furius.ca/beancount/doc/tolerances) are still taken into account. Enabling this flag only makes the tolerances potentially wider. """, [Opt("infer_tolerance_from_cost", False, True)]), OptGroup(""" A list of directory roots, relative to the CWD, which should be searched for document files. For the document files to be automatically found they must have the following filename format: YYYY-MM-DD.(.*) """, [Opt("documents", [], "/path/to/your/documents/archive")]), OptGroup(""" A list of currencies that we single out during reporting and create dedicated columns for. This is used to indicate the main currencies that you work with in real life. (Refrain from listing all the possible currencies here, this is not what it is made for; just list the very principal currencies you use daily only.) Because our system is agnostic to any unit definition that occurs in the input file, we use this to display these values in table cells without their associated unit strings. This allows you to import the numbers in a spreadsheet (e.g, "101.00 USD" does not get parsed by a spreadsheet import, but "101.00" does). If you need to enter a list of operating currencies, you may input this option multiple times, that is, you repeat the entire directive once for each desired operating currency. """, [Opt("operating_currency", [], "USD")]), OptGroup(""" A boolean, true if the number formatting routines should output commas as thousand separators in numbers. """, [Opt("render_commas", False, "TRUE", converter=options_validate_boolean)]), OptGroup(""" A string that defines which set of plugins is to be run by the loader: if the mode is "default", a preset list of plugins are automatically run before any user plugin. If the mode is "raw", no preset plugins are run at all, only user plugins are run (the user should explicitly load the desired list of plugins by using the 'plugin' option. This is useful in case the user wants full control over the ordering in which the plugins are run). """, [Opt("plugin_processing_mode", "default", "raw", converter=options_validate_processing_mode)]), OptGroup(""" The number of lines beyond which a multi-line string will trigger an overly long line warning. This warning is meant to help detect a dangling quote by warning users of unexpectedly long strings. """, [Opt("long_string_maxlines", 64)]), OptGroup(""" The booking method to apply to ambiguous reductions of inventory lots. When a posting is matched against the contents of an account's inventory to reduce its contents and multiple lots match, the method dictates how this ambiguity is resolved. Methods include "STRICT" which raises an error, "FIFO" which selects the oldest lot, and "NONE" which allows any reduction to be added to the inventory despite the absence of a match (resulting in mixed inventories). See the following documents for details: http://furius.ca/beancount/doc/inventories http://furius.ca/beancount/doc/proposal-booking """, [Opt("booking_method", data.Booking.STRICT, "STRICT", converter=options_validate_booking_method)]), OptGroup(""" Support the pipe (|) symbol to for transaction separator. This is only provided as a temporary stopgap to ease transition, and will be removed eventually. This is why this option is marked as deprecated. """, [Opt("allow_pipe_separator", False, "TRUE", converter=options_validate_boolean, deprecated=('Allowing pipe separator temporary; ' 'this will go away eventually.'))]), OptGroup(""" Allow plugins to produce a None object for the 'tags' and 'links' attributes of a Transaction instance. By default, without this, those attributes are now ensured to be a Set type, and an empty frozenset() instance if there are no values This is only provided as a temporary mechanism to allow you some time to port your plugins code. """, [Opt("allow_deprecated_none_for_tags_and_links", False, "TRUE", converter=options_validate_boolean, deprecated=('Allowing None for tags and link ' 'will go away eventually.'))]), OptGroup(""" A boolean, if true, prepend the directory name of the top-level file to the PYTHONPATH. """, [Opt("insert_pythonpath", False, "TRUE", converter=options_validate_boolean)]), ] The provided code snippet includes necessary dependencies for implementing the `list_options` function. Write a Python function `def list_options()` to solve the following problem: Produce a formatted text of the available options and their description. Returns: A string, formatted nicely to be printed in 80 columns. Here is the function: def list_options(): """Produce a formatted text of the available options and their description. Returns: A string, formatted nicely to be printed in 80 columns. """ oss = io.StringIO() for group in PUBLIC_OPTION_GROUPS: for desc in group.options: oss.write('option "{}" "{}"\n'.format(desc.name, desc.example_value)) if desc.deprecated: oss.write(textwrap.fill( "THIS OPTION IS DEPRECATED: {}".format(desc.deprecated), initial_indent=" ", subsequent_indent=" ")) oss.write('\n\n') description = ' '.join(line.strip() for line in group.description.strip().splitlines()) oss.write(textwrap.fill(description, initial_indent=' ', subsequent_indent=' ')) oss.write('\n') if isinstance(desc.default_value, (list, dict, set)): oss.write('\n') oss.write(' (This option may be supplied multiple times.)\n') oss.write('\n\n') return oss.getvalue()
Produce a formatted text of the available options and their description. Returns: A string, formatted nicely to be printed in 80 columns.
3,135
import collections from beancount.core.number import MISSING from beancount.core.number import ZERO from beancount.core import amount from beancount.core import data from beancount.core import inventory from beancount.core import position from beancount.parser import booking_full BookingError = collections.namedtuple('BookingError', 'source message entry') The provided code snippet includes necessary dependencies for implementing the `validate_inventory_booking` function. Write a Python function `def validate_inventory_booking(entries, unused_options_map, booking_methods)` to solve the following problem: Validate that no position at cost is allowed to go negative. This routine checks that when a posting reduces a position, existing or not, that the subsequent inventory does not result in a position with a negative number of units. A negative number of units would only be required for short trades of trading spreads on futures, and right now this is not supported. It would not be difficult to support this, however, but we want to be strict about it, because being pedantic about this is otherwise a great way to detect user data entry mistakes. Args: entries: A list of directives. unused_options_map: An options map. booking_methods: A mapping of account name to booking method, accumulated in the main loop. Returns: A list of errors. Here is the function: def validate_inventory_booking(entries, unused_options_map, booking_methods): """Validate that no position at cost is allowed to go negative. This routine checks that when a posting reduces a position, existing or not, that the subsequent inventory does not result in a position with a negative number of units. A negative number of units would only be required for short trades of trading spreads on futures, and right now this is not supported. It would not be difficult to support this, however, but we want to be strict about it, because being pedantic about this is otherwise a great way to detect user data entry mistakes. Args: entries: A list of directives. unused_options_map: An options map. booking_methods: A mapping of account name to booking method, accumulated in the main loop. Returns: A list of errors. """ errors = [] balances = collections.defaultdict(inventory.Inventory) for entry in entries: if isinstance(entry, data.Transaction): for posting in entry.postings: # Update the balance of each posting on its respective account # without allowing booking to a negative position, and if an error # is encountered, catch it and return it. running_balance = balances[posting.account] position_, _ = running_balance.add_position(posting) # Skip this check if the booking method is set to ignore it. if booking_methods.get(posting.account, None) == data.Booking.NONE: continue # Check if the resulting inventory is mixed, which is not # allowed under the STRICT method. if running_balance.is_mixed(): errors.append( BookingError( entry.meta, ("Reducing position results in inventory with positive " "and negative lots: {}").format(position_), entry)) return errors
Validate that no position at cost is allowed to go negative. This routine checks that when a posting reduces a position, existing or not, that the subsequent inventory does not result in a position with a negative number of units. A negative number of units would only be required for short trades of trading spreads on futures, and right now this is not supported. It would not be difficult to support this, however, but we want to be strict about it, because being pedantic about this is otherwise a great way to detect user data entry mistakes. Args: entries: A list of directives. unused_options_map: An options map. booking_methods: A mapping of account name to booking method, accumulated in the main loop. Returns: A list of errors.
3,136
import collections from beancount.core.number import MISSING from beancount.core.number import ZERO from beancount.core import amount from beancount.core import data from beancount.core import inventory from beancount.core import position from beancount.parser import booking_full BookingError = collections.namedtuple('BookingError', 'source message entry') def convert_spec_to_cost(units, cost_spec): """Convert a posting's CostSpec instance to a Cost. Args: units: An instance of Amount. cost_spec: An instance of CostSpec. Returns: An instance of Cost. """ cost = cost_spec errors = [] if isinstance(units, amount.Amount): currency = units.currency if cost_spec is not None: number_per, number_total, cost_currency, date, label, merge = cost_spec # Compute the cost. if number_per is not MISSING or number_total is not None: if number_total is not None: # Compute the per-unit cost if there is some total cost # component involved. units_num = units.number cost_total = number_total if number_per is not MISSING: cost_total += number_per * units_num unit_cost = cost_total / abs(units_num) else: unit_cost = number_per cost = position.Cost(unit_cost, cost_currency, date, label) else: cost = None return cost ZERO = Decimal() The provided code snippet includes necessary dependencies for implementing the `convert_lot_specs_to_lots` function. Write a Python function `def convert_lot_specs_to_lots(entries)` to solve the following problem: For all the entries, convert the posting's position's CostSpec to Cost instances. In the simple method, the data provided in the CostSpec must unambiguously provide a way to compute the cost amount. This essentially replicates the way the old parser used to work, but allowing positions to have the fuzzy lot specifications instead of the resolved ones. We used to simply compute the costs locally, and this gets rid of the CostSpec to produce the Cost without fuzzy matching. This is only there for the sake of transition to the new matching logic. Args: entries: A list of incomplete directives as per the parser. Returns: A list of entries whose postings's position costs have been converted to Cost instances but that may still be incomplete. Raises: ValueError: If there's a unacceptable number. Here is the function: def convert_lot_specs_to_lots(entries): """For all the entries, convert the posting's position's CostSpec to Cost instances. In the simple method, the data provided in the CostSpec must unambiguously provide a way to compute the cost amount. This essentially replicates the way the old parser used to work, but allowing positions to have the fuzzy lot specifications instead of the resolved ones. We used to simply compute the costs locally, and this gets rid of the CostSpec to produce the Cost without fuzzy matching. This is only there for the sake of transition to the new matching logic. Args: entries: A list of incomplete directives as per the parser. Returns: A list of entries whose postings's position costs have been converted to Cost instances but that may still be incomplete. Raises: ValueError: If there's a unacceptable number. """ new_entries = [] errors = [] for entry in entries: if not isinstance(entry, data.Transaction): new_entries.append(entry) continue new_postings = [] for posting in entry.postings: try: units = posting.units cost_spec = posting.cost cost = convert_spec_to_cost(units, cost_spec) if cost_spec is not None and cost is None: errors.append( BookingError(entry.meta, "Cost syntax not supported; cost spec ignored", None)) if cost and isinstance(units, amount.Amount): # If there is a cost, we don't allow either a cost value of # zero, nor a zero number of units. Note that we allow a price # of zero as the only special case (for conversion entries), but # never for costs. if units.number == ZERO: raise ValueError('Amount is zero: "{}"'.format(units)) if cost.number is not None and cost.number < ZERO: raise ValueError('Cost is negative: "{}"'.format(cost)) except ValueError as exc: errors.append(BookingError(entry.meta, str(exc), None)) cost = None new_postings.append(posting._replace(cost=cost)) new_entries.append(entry._replace(postings=new_postings)) return new_entries, errors
For all the entries, convert the posting's position's CostSpec to Cost instances. In the simple method, the data provided in the CostSpec must unambiguously provide a way to compute the cost amount. This essentially replicates the way the old parser used to work, but allowing positions to have the fuzzy lot specifications instead of the resolved ones. We used to simply compute the costs locally, and this gets rid of the CostSpec to produce the Cost without fuzzy matching. This is only there for the sake of transition to the new matching logic. Args: entries: A list of incomplete directives as per the parser. Returns: A list of entries whose postings's position costs have been converted to Cost instances but that may still be incomplete. Raises: ValueError: If there's a unacceptable number.
3,137
import collections from decimal import Decimal from beancount.core.number import ZERO from beancount.core.data import Booking from beancount.core.amount import Amount from beancount.core.position import Cost from beancount.core import flags from beancount.core import position from beancount.core import inventory from beancount.core import convert def booking_method_STRICT(entry, posting, matches): """Strict booking method. This method fails if there are ambiguous matches. """ booked_reductions = [] booked_matches = [] errors = [] insufficient = False # In strict mode, we require at most a single matching posting. if len(matches) > 1: # If the total requested to reduce matches the sum of all the # ambiguous postings, match against all of them. sum_matches = sum(p.units.number for p in matches) if sum_matches == -posting.units.number: booked_reductions.extend( posting._replace(units=-match.units, cost=match.cost) for match in matches) else: errors.append( AmbiguousMatchError(entry.meta, 'Ambiguous matches for "{}": {}'.format( position.to_string(posting), ', '.join(position.to_string(match_posting) for match_posting in matches)), entry)) else: # Replace the posting's units and cost values. match = matches[0] sign = -1 if posting.units.number < ZERO else 1 number = min(abs(match.units.number), abs(posting.units.number)) match_units = Amount(number * sign, match.units.currency) booked_reductions.append(posting._replace(units=match_units, cost=match.cost)) booked_matches.append(match) insufficient = (match_units.number != posting.units.number) return booked_reductions, booked_matches, errors, insufficient The provided code snippet includes necessary dependencies for implementing the `booking_method_STRICT_WITH_SIZE` function. Write a Python function `def booking_method_STRICT_WITH_SIZE(entry, posting, matches)` to solve the following problem: Strict booking method, but disambiguate further with sizes. This booking method applies the same algorithm as the STRICT method, but if only one of the ambiguous lots matches the desired size, select that one automatically. Here is the function: def booking_method_STRICT_WITH_SIZE(entry, posting, matches): """Strict booking method, but disambiguate further with sizes. This booking method applies the same algorithm as the STRICT method, but if only one of the ambiguous lots matches the desired size, select that one automatically. """ (booked_reductions, booked_matches, errors, insufficient) = booking_method_STRICT(entry, posting, matches) # If we couldn't match strictly, attempt to find a match with the same # number of units. If there is one or more of these, accept the oldest lot. if errors and len(matches) > 1: number = -posting.units.number matching_units = [match for match in matches if number == match.units.number] if matching_units: matching_units.sort(key=lambda match: match.cost.date) # Replace the posting's units and cost values. match = matching_units[0] booked_reductions.append(posting._replace(units=-match.units, cost=match.cost)) booked_matches.append(match) insufficient = False errors = [] return booked_reductions, booked_matches, errors, insufficient
Strict booking method, but disambiguate further with sizes. This booking method applies the same algorithm as the STRICT method, but if only one of the ambiguous lots matches the desired size, select that one automatically.
3,138
import collections from decimal import Decimal from beancount.core.number import ZERO from beancount.core.data import Booking from beancount.core.amount import Amount from beancount.core.position import Cost from beancount.core import flags from beancount.core import position from beancount.core import inventory from beancount.core import convert def _booking_method_xifo(entry, posting, matches, sortattr, reverse_order): """FIFO and LIFO booking method implementations.""" booked_reductions = [] booked_matches = [] errors = [] insufficient = False # Each up the positions. sign = -1 if posting.units.number < ZERO else 1 remaining = abs(posting.units.number) for match in sorted(matches, key=lambda p: p.cost and getattr(p.cost, sortattr), reverse=reverse_order): if remaining <= ZERO: break # If the inventory somehow ended up with mixed lots, skip this one. if match.units.number * sign > ZERO: continue # Compute the amount of units we can reduce from this leg. size = min(abs(match.units.number), remaining) booked_reductions.append( posting._replace(units=Amount(size * sign, match.units.currency), cost=match.cost)) booked_matches.append(match) remaining -= size # If we couldn't eat up all the requested reduction, return an error. insufficient = (remaining > ZERO) return booked_reductions, booked_matches, errors, insufficient The provided code snippet includes necessary dependencies for implementing the `booking_method_FIFO` function. Write a Python function `def booking_method_FIFO(entry, posting, matches)` to solve the following problem: FIFO booking method implementation. Here is the function: def booking_method_FIFO(entry, posting, matches): """FIFO booking method implementation.""" return _booking_method_xifo(entry, posting, matches, "date", False)
FIFO booking method implementation.
3,139
import collections from decimal import Decimal from beancount.core.number import ZERO from beancount.core.data import Booking from beancount.core.amount import Amount from beancount.core.position import Cost from beancount.core import flags from beancount.core import position from beancount.core import inventory from beancount.core import convert def _booking_method_xifo(entry, posting, matches, sortattr, reverse_order): """FIFO and LIFO booking method implementations.""" booked_reductions = [] booked_matches = [] errors = [] insufficient = False # Each up the positions. sign = -1 if posting.units.number < ZERO else 1 remaining = abs(posting.units.number) for match in sorted(matches, key=lambda p: p.cost and getattr(p.cost, sortattr), reverse=reverse_order): if remaining <= ZERO: break # If the inventory somehow ended up with mixed lots, skip this one. if match.units.number * sign > ZERO: continue # Compute the amount of units we can reduce from this leg. size = min(abs(match.units.number), remaining) booked_reductions.append( posting._replace(units=Amount(size * sign, match.units.currency), cost=match.cost)) booked_matches.append(match) remaining -= size # If we couldn't eat up all the requested reduction, return an error. insufficient = (remaining > ZERO) return booked_reductions, booked_matches, errors, insufficient The provided code snippet includes necessary dependencies for implementing the `booking_method_LIFO` function. Write a Python function `def booking_method_LIFO(entry, posting, matches)` to solve the following problem: LIFO booking method implementation. Here is the function: def booking_method_LIFO(entry, posting, matches): """LIFO booking method implementation.""" return _booking_method_xifo(entry, posting, matches, "date", True)
LIFO booking method implementation.
3,140
import collections from decimal import Decimal from beancount.core.number import ZERO from beancount.core.data import Booking from beancount.core.amount import Amount from beancount.core.position import Cost from beancount.core import flags from beancount.core import position from beancount.core import inventory from beancount.core import convert def _booking_method_xifo(entry, posting, matches, sortattr, reverse_order): """FIFO and LIFO booking method implementations.""" booked_reductions = [] booked_matches = [] errors = [] insufficient = False # Each up the positions. sign = -1 if posting.units.number < ZERO else 1 remaining = abs(posting.units.number) for match in sorted(matches, key=lambda p: p.cost and getattr(p.cost, sortattr), reverse=reverse_order): if remaining <= ZERO: break # If the inventory somehow ended up with mixed lots, skip this one. if match.units.number * sign > ZERO: continue # Compute the amount of units we can reduce from this leg. size = min(abs(match.units.number), remaining) booked_reductions.append( posting._replace(units=Amount(size * sign, match.units.currency), cost=match.cost)) booked_matches.append(match) remaining -= size # If we couldn't eat up all the requested reduction, return an error. insufficient = (remaining > ZERO) return booked_reductions, booked_matches, errors, insufficient The provided code snippet includes necessary dependencies for implementing the `booking_method_HIFO` function. Write a Python function `def booking_method_HIFO(entry, posting, matches)` to solve the following problem: HIFO booking method implementation. Here is the function: def booking_method_HIFO(entry, posting, matches): """HIFO booking method implementation.""" return _booking_method_xifo(entry, posting, matches, "number", True)
HIFO booking method implementation.
3,141
import collections from decimal import Decimal from beancount.core.number import ZERO from beancount.core.data import Booking from beancount.core.amount import Amount from beancount.core.position import Cost from beancount.core import flags from beancount.core import position from beancount.core import inventory from beancount.core import convert The provided code snippet includes necessary dependencies for implementing the `booking_method_NONE` function. Write a Python function `def booking_method_NONE(entry, posting, matches)` to solve the following problem: NONE booking method implementation. Here is the function: def booking_method_NONE(entry, posting, matches): """NONE booking method implementation.""" # This never needs to match against any existing positions... we # disregard the matches, there's never any error. Note that this never # gets called in practice, we want to treat NONE postings as # augmentations. Default behaviour is to return them with their original # CostSpec, and the augmentation code will handle signaling an error if # there is insufficient detail to carry out the conversion to an # instance of Cost. # Note that it's an interesting question whether a reduction on an # account with NONE method which happens to match a single position # ought to be matched against it. We don't allow it for now. return [posting], [], False
NONE booking method implementation.
3,142
import collections from decimal import Decimal from beancount.core.number import ZERO from beancount.core.data import Booking from beancount.core.amount import Amount from beancount.core.position import Cost from beancount.core import flags from beancount.core import position from beancount.core import inventory from beancount.core import convert AmbiguousMatchError = collections.namedtuple('AmbiguousMatchError', 'source message entry') ZERO = Decimal() class Amount(_Amount): """An 'Amount' represents a number of a particular unit of something. It's essentially a typed number, with corresponding manipulation operations defined on it. """ __slots__ = () # Prevent the creation of new attributes. valid_types_number = (Decimal, type, type(None)) valid_types_currency = (str, type, type(None)) def __new__(cls, number, currency): """Constructor from a number and currency. Args: number: A Decimal instance. currency: A string, the currency symbol to use. """ assert isinstance(number, Amount.valid_types_number), repr(number) assert isinstance(currency, Amount.valid_types_currency), repr(currency) return _Amount.__new__(cls, number, currency) def to_string(self, dformat=DEFAULT_FORMATTER): """Convert an Amount instance to a printable string. Args: dformat: An instance of DisplayFormatter. Returns: A formatted string of the quantized amount and symbol. """ if isinstance(self.number, Decimal): number_fmt = dformat.format(self.number, self.currency) elif self.number is MISSING: number_fmt = '' else: number_fmt = str(self.number) return "{} {}".format(number_fmt, self.currency) def __str__(self): """Convert an Amount instance to a printable string with the defaults. Returns: A formatted string of the quantized amount and symbol. """ return self.to_string() __repr__ = __str__ def __bool__(self): """Boolean predicate returns true if the number is non-zero. Returns: A boolean, true if non-zero number. """ return self.number != ZERO def __eq__(self, other): """Equality predicate. Returns true if both number and currency are equal. Returns: A boolean. """ if other is None: return False return (self.number, self.currency) == (other.number, other.currency) def __lt__(self, other): """Ordering comparison. This is used in the sorting key of positions. Args: other: An instance of Amount. Returns: True if this is less than the other Amount. """ return sortkey(self) < sortkey(other) def __hash__(self): """A hashing function for amounts. The hash includes the currency. Returns: An integer, the hash for this amount. """ return hash((self.number, self.currency)) def __neg__(self): """Return the negative of this amount. Returns: A new instance of Amount, with the negative number of units. """ return Amount(-self.number, self.currency) def from_string(string): """Create an amount from a string. This is a miniature parser used for building tests. Args: string: A string of <number> <currency>. Returns: A new instance of Amount. """ match = re.match(r'\s*([-+]?[0-9.]+)\s+({currency})'.format(currency=CURRENCY_RE), string) if not match: raise ValueError("Invalid string for amount: '{}'".format(string)) number, currency = match.group(1, 2) return Amount(D(number), currency) Cost = NamedTuple('Cost', [ ('number', Decimal), ('currency', str), ('date', datetime.date), ('label', Optional[str])]) The provided code snippet includes necessary dependencies for implementing the `booking_method_AVERAGE` function. Write a Python function `def booking_method_AVERAGE(entry, posting, matches)` to solve the following problem: AVERAGE booking method implementation. Here is the function: def booking_method_AVERAGE(entry, posting, matches): """AVERAGE booking method implementation.""" booked_reductions = [] booked_matches = [] errors = [AmbiguousMatchError(entry.meta, "AVERAGE method is not supported", entry)] return booked_reductions, booked_matches, errors, False # FIXME: Future implementation here. # pylint: disable=unreachable if False: # pylint: disable=using-constant-test # DISABLED - This is the code for AVERAGE, which is currently disabled. # If there is more than a single match we need to ultimately merge the # postings. Also, if the reducing posting provides a specific cost, we # need to update the cost basis as well. Both of these cases are carried # out by removing all the matches and readding them later on. if len(matches) == 1 and ( not isinstance(posting.cost.number_per, Decimal) and not isinstance(posting.cost.number_total, Decimal)): # There is no cost. Just reduce the one leg. This should be the # normal case if we always merge augmentations and the user lets # Beancount deal with the cost. match = matches[0] sign = -1 if posting.units.number < ZERO else 1 number = min(abs(match.units.number), abs(posting.units.number)) match_units = Amount(number * sign, match.units.currency) booked_reductions.append(posting._replace(units=match_units, cost=match.cost)) insufficient = (match_units.number != posting.units.number) else: # Merge the matching postings to a single one. merged_units = inventory.Inventory() merged_cost = inventory.Inventory() for match in matches: merged_units.add_amount(match.units) merged_cost.add_amount(convert.get_weight(match)) if len(merged_units) != 1 or len(merged_cost) != 1: errors.append( AmbiguousMatchError( entry.meta, 'Cannot merge positions in multiple currencies: {}'.format( ', '.join(position.to_string(match_posting) for match_posting in matches)), entry)) else: if (isinstance(posting.cost.number_per, Decimal) or isinstance(posting.cost.number_total, Decimal)): errors.append( AmbiguousMatchError( entry.meta, "Explicit cost reductions aren't supported yet: {}".format( position.to_string(posting)), entry)) else: # Insert postings to remove all the matches. booked_reductions.extend( posting._replace(units=-match.units, cost=match.cost, flag=flags.FLAG_MERGING) for match in matches) units = merged_units[0].units date = matches[0].cost.date ## FIXME: Select which one, ## oldest or latest. cost_units = merged_cost[0].units cost = Cost(cost_units.number/units.number, cost_units.currency, date, None) # Insert a posting to refill those with a replacement match. booked_reductions.append( posting._replace(units=units, cost=cost, flag=flags.FLAG_MERGING)) # Now, match the reducing request against this lot. booked_reductions.append( posting._replace(units=posting.units, cost=cost)) insufficient = abs(posting.units.number) > abs(units.number)
AVERAGE booking method implementation.
3,143
import collections import copy import enum from decimal import Decimal import uuid from beancount.core.number import MISSING from beancount.core.number import ZERO from beancount.core.data import Transaction from beancount.core.data import Booking from beancount.core.amount import Amount from beancount.core.position import Position from beancount.core.position import Cost from beancount.core.position import CostSpec from beancount.parser import booking_method from beancount.core import position from beancount.core import inventory from beancount.core import interpolate The provided code snippet includes necessary dependencies for implementing the `unique_label` function. Write a Python function `def unique_label() -> str` to solve the following problem: Return a globally unique label for cost entries. Here is the function: def unique_label() -> str: "Return a globally unique label for cost entries." return str(uuid.uuid4())
Return a globally unique label for cost entries.
3,144
import collections import copy import enum from decimal import Decimal import uuid from beancount.core.number import MISSING from beancount.core.number import ZERO from beancount.core.data import Transaction from beancount.core.data import Booking from beancount.core.amount import Amount from beancount.core.position import Position from beancount.core.position import Cost from beancount.core.position import CostSpec from beancount.parser import booking_method from beancount.core import position from beancount.core import inventory from beancount.core import interpolate def _book(entries, options_map, methods, initial_balances=None): """Interpolate missing data from the entries using the full historical algorithm. Args: incomplete_entries: A list of directives, with some postings possibly left with incomplete amounts as produced by the parser. options_map: An options dict as produced by the parser. methods: A mapping of account name to their corresponding booking method. initial_balances: A dict of (account, inventory) pairs to start booking from. This is useful when attempting to book on top of an existing state. Returns: A triple of entries: A list of interpolated entries with all their postings completed. errors: New errors produced during interpolation. balances: A dict of account name and resulting balances. """ new_entries = [] errors = [] # Set initial state to start booking from. # # TODO(blais): In v3 we want to explode this to that this is a common # operation and also abstract the initial balances to a Realization object. balances = (collections.defaultdict(inventory.Inventory) if initial_balances is None else initial_balances) assert isinstance(balances, (dict, collections.defaultdict)) for entry in entries: if isinstance(entry, Transaction): # Group postings by currency. refer_groups, cat_errors = categorize_by_currency(entry, balances) if cat_errors: errors.extend(cat_errors) continue posting_groups = replace_currencies(entry.postings, refer_groups) # Get the list of tolerances. tolerances = interpolate.infer_tolerances(entry.postings, options_map) # Resolve reductions to a particular lot in their inventory balance. repl_postings = [] for currency, group_postings in posting_groups: # Important note: the group of 'postings' here is a subset of # that from entry.postings, and may include replicated # auto-postings. Never use entry.postings going forward. # (See http://furius.ca/beancount/doc/self-reductions for an # explanation of how we will eventually treat each currency # group in this block; Summary: We will need to run the # reductions prior to the augmentations in order to support # reductions between the postings of a single transaction.) # Disabled. if False: # pylint: disable=using-constant-test if has_self_reduction(group_postings, methods): errors.append(SelfReduxError( entry.meta, "Self-reduction is not allowed", entry)) # Perform booking reductions, that is, match postings which # reduce the ante-inventory of their accounts to an existing # position in the inventory against a possibly incomplete # CostSpec specification, and replace the postings' cost to the # fully-specified (with a date & label) existing Cost instance. # Note that 'balances' remains untouched. # # Also note that 'booked_postings' may include augmenting # postings whose 'cost' attribute has been left to a CostSpec # instance. Therefore, the postings held-at-cost may hold a # mixture of Cost and CostSpec instances. This is necessary to # let the interpolation do its magic on partially incomplete # CostSpec instances below. (booked_postings, booking_errors) = book_reductions(entry, group_postings, balances, methods) # If there were any errors, skip this group of postings. if booking_errors: errors.extend(booking_errors) continue # Interpolate missing numbers from all postings. This # includes partially incomplete CostSpec instances remaining # on augmenting postings. After this interpolation, all # 'inter_postings' consists entirely of postings holding # instances of Cost. (inter_postings, interpolation_errors, interpolated) = interpolate_group(booked_postings, balances, currency, tolerances) if interpolation_errors: errors.extend(interpolation_errors) repl_postings.extend(inter_postings) # Replace postings by interpolated ones. meta = entry.meta.copy() meta[interpolate.AUTOMATIC_TOLERANCES] = tolerances entry = entry._replace(postings=repl_postings, meta=meta) # Update the running balances for each account using the final, # booked and interpolated values. Note that we could optimize away # some of this in book_reductions() but we choose not to do so, as a # sanity check that the direct aggregation of the final booked lots # will compute the same result as that during the book_reductions() # process. for posting in repl_postings: balance = balances[posting.account] balance.add_position(posting) new_entries.append(entry) return new_entries, errors, balances The provided code snippet includes necessary dependencies for implementing the `book` function. Write a Python function `def book(entries, options_map, methods, initial_balances=None)` to solve the following problem: Interpolate missing data from the entries using the full historical algorithm. See the internal implementation _book() for details. This method only stripes some of the return values. See _book() for arguments and return values. Here is the function: def book(entries, options_map, methods, initial_balances=None): """Interpolate missing data from the entries using the full historical algorithm. See the internal implementation _book() for details. This method only stripes some of the return values. See _book() for arguments and return values. """ entries, errors, _ = _book(entries, options_map, methods, initial_balances) return entries, errors
Interpolate missing data from the entries using the full historical algorithm. See the internal implementation _book() for details. This method only stripes some of the return values. See _book() for arguments and return values.
3,145
import argparse import hashlib import textwrap import types import warnings from os import path def hash_parser_source_files(): """Compute a unique hash of the parser's Python code in order to bake that into the extension module. This is used at load-time to verify that the extension module and the corresponding Python codes match each other. If not, it issues a warning that you should rebuild your extension module. Returns: A string, the hexadecimal unique hash of relevant source code that should trigger a recompilation. """ md5 = hashlib.md5() for filename in PARSER_SOURCE_FILES: fullname = path.join(path.dirname(__file__), filename) if not path.exists(fullname): return None with open(fullname, 'rb') as file: md5.update(file.read()) # Note: Prepend a character in front of the hash because under Windows MSDEV # removes escapes, and if the hash starts with a number it fails to # recognize this is a string. A small compromise for portability. return md5.hexdigest() The provided code snippet includes necessary dependencies for implementing the `check_parser_source_files` function. Write a Python function `def check_parser_source_files(parser_module: types.ModuleType)` to solve the following problem: Check the extension module's source hash and issue a warning if the current source differs from that of the module. If the source files aren't located in the Python source directory, ignore the warning, we're probably running this from an installed based, in which case we don't need to check anything (this check is useful only for people running directly from source). Here is the function: def check_parser_source_files(parser_module: types.ModuleType): """Check the extension module's source hash and issue a warning if the current source differs from that of the module. If the source files aren't located in the Python source directory, ignore the warning, we're probably running this from an installed based, in which case we don't need to check anything (this check is useful only for people running directly from source). """ parser_source_hash = hash_parser_source_files() if parser_source_hash is None: return if parser_module.SOURCE_HASH and parser_module.SOURCE_HASH != parser_source_hash: warnings.warn( ("The Beancount parser C extension module is out-of-date ('{}' != '{}'). " "You need to rebuild.").format(parser_module.SOURCE_HASH, parser_source_hash))
Check the extension module's source hash and issue a warning if the current source differs from that of the module. If the source files aren't located in the Python source directory, ignore the warning, we're probably running this from an installed based, in which case we don't need to check anything (this check is useful only for people running directly from source).
3,146
import argparse import hashlib import textwrap import types import warnings from os import path def hash_parser_source_files(): """Compute a unique hash of the parser's Python code in order to bake that into the extension module. This is used at load-time to verify that the extension module and the corresponding Python codes match each other. If not, it issues a warning that you should rebuild your extension module. Returns: A string, the hexadecimal unique hash of relevant source code that should trigger a recompilation. """ md5 = hashlib.md5() for filename in PARSER_SOURCE_FILES: fullname = path.join(path.dirname(__file__), filename) if not path.exists(fullname): return None with open(fullname, 'rb') as file: md5.update(file.read()) # Note: Prepend a character in front of the hash because under Windows MSDEV # removes escapes, and if the hash starts with a number it fails to # recognize this is a string. A small compromise for portability. return md5.hexdigest() The provided code snippet includes necessary dependencies for implementing the `gen_include` function. Write a Python function `def gen_include()` to solve the following problem: Generate an include file for the parser source hash. Here is the function: def gen_include(): """Generate an include file for the parser source hash.""" return textwrap.dedent("""\ #ifndef __BEANCOUNT_PARSER_PARSE_SOURCE_HASH_H__ #define __BEANCOUNT_PARSER_PARSE_SOURCE_HASH_H__ #define PARSER_SOURCE_HASH {source_hash} #endif // __BEANCOUNT_PARSER_PARSE_SOURCE_HASH_H__ """.format(source_hash=hash_parser_source_files()))
Generate an include file for the parser source hash.
3,147
import calendar import collections import datetime import decimal import functools import io import itertools import logging import math import operator import random import re import sys import textwrap from dateutil import rrule import click from beancount.core.number import D from beancount.core.number import ZERO from beancount.core.number import round_to from beancount.core.account import join from beancount.core import data from beancount.core import amount from beancount.core import inventory from beancount.core import realization from beancount.core import display_context from beancount.core import convert from beancount.parser import parser from beancount.parser import booking from beancount.parser import printer from beancount.ops import validation from beancount.core import prices from beancount.scripts import format from beancount.core import getters from beancount.utils import misc_utils from beancount.utils import date_utils from beancount.parser.version import VERSION from beancount import loader ANNUAL_SALARY = D('120000') RENT_DIVISOR = D('50') RENT_INCREMENT = D('25') EMPLOYERS = [ ('Hooli', "1 Carloston Rd, Mountain Beer, CA"), ('BayBook', "1501 Billow Rd, Benlo Park, CA"), ('Babble', "1 Continuous Loop, Bupertina, CA"), ('Hoogle', "1600 Amphibious Parkway, River View, CA"), ] HOME_NAME = "New Metropolis" TRIP_DESTINATIONS = { "los-angeles": [ ("Mr. Marcel", "Expenses:Food:Restaurant", (40, 25)), ("Banana Leaf", "Expenses:Food:Restaurant", (25, 10)), ("Dupar's", "Expenses:Food:Restaurant", (30, 12)), ("Pampas Grill", "Expenses:Food:Restaurant", (25, 10)), ("Chipotle", "Expenses:Food:Restaurant", (16, 5)), ("Starbucks", "Expenses:Food:Coffee", (6, 2)), ("E.B.'s Beer and Wine", "Expenses:Food:Alcohol", (9, 5)), ], "chicago": [ ("Star of Siam", "Expenses:Food:Restaurant", (25, 10)), ("Mercadito", "Expenses:Food:Restaurant", (40, 15)), ("25 Degrees Burger Bar", "Expenses:Food:Restaurant", (22, 7)), ("Eataly Chicago", "Expenses:Food:Restaurant", (40, 25)), ("Another Sports Pub", "Expenses:Food:Alcohol", (12, 7)), ("Argo Tea", "Expenses:Food:Coffee", (6, 2)), ], "boston": [ ("Giacomo's Restaurant", "Expenses:Food:Restaurant", (40, 12)), ("Legal Seafood", "Expenses:Food:Restaurant", (35, 15)), ("Franklin Cafe", "Expenses:Food:Restaurant", (30, 12)), ("Starbucks", "Expenses:Food:Coffee", (6, 2)), ], "new-york": [ ("Uncle Boons", "Expenses:Food:Restaurant", (40, 15)), ("Cafe Select", "Expenses:Food:Restaurant", (30, 12)), ("Takahachi", "Expenses:Food:Restaurant", (50, 15)), ("Laut", "Expenses:Food:Restaurant", (32, 10)), ("La Colombe", "Expenses:Food:Coffee", (6, 3)), ("Gimme! Coffee", "Expenses:Food:Coffee", (7, 4)), ], "san-francisco": [ ("Bar Crudo", "Expenses:Food:Restaurant", (70, 20)), ("Pizza Delfina", "Expenses:Food:Restaurant", (20, 6)), ("Waterbar", "Expenses:Food:Restaurant", (50, 20)), ("Mission Chinese Food", "Expenses:Food:Restaurant", (27, 12)), ("Starbucks", "Expenses:Food:Coffee", (6, 2)), ], } FILE_PREAMBLE = """\ ;; -*- mode: org; mode: beancount; -*- ;; Birth: {date_birth} ;; Dates: {date_begin} - {date_end} ;; THIS FILE HAS BEEN AUTO-GENERATED. * Options option "title" "Example Beancount file" option "operating_currency" "CCY" """ def date_random_seq(date_begin, date_end, days_min, days_max): """Generate a sequence of dates with some random increase in days. Args: date_begin: The start date. date_end: The end date. days_min: The minimum number of days to advance on each iteration. days_max: The maximum number of days to advance on each iteration. Yields: Instances of datetime.date. """ assert days_min > 0 assert days_min <= days_max date = date_begin while date < date_end: nb_days_forward = random.randint(days_min, days_max) date += datetime.timedelta(days=nb_days_forward) if date >= date_end: break yield date def delay_dates(date_iter, delay_days_min, delay_days_max): """Delay the dates from the given iterator by some uniformly drawn number of days. Args: date_iter: An iterator of datetime.date instances. delay_days_min: The minimum amount of advance days for the transaction. delay_days_max: The maximum amount of advance days for the transaction. Yields: datetime.date instances. """ dates = list(date_iter) last_date = dates[-1] last_date = last_date.date() if isinstance(last_date, datetime.datetime) else last_date for dtime in dates: date = dtime.date() if isinstance(dtime, datetime.datetime) else dtime date += datetime.timedelta(days=random.randint(delay_days_min, delay_days_max)) if date >= last_date: break yield date def get_minimum_balance(entries, account, currency): """Compute the minimum balance of the given account according to the entries history. Args: entries: A list of directives. account: An account string. currency: A currency string, for which we want to compute the minimum. Returns: A Decimal number, the minimum amount throughout the history of this account. """ min_amount = ZERO for _, balances in postings_for(entries, [account]): balance = balances[account] current = balance.get_currency_units(currency).number if current < min_amount: min_amount = current return min_amount def generate_employment_income(employer_name, employer_address, annual_salary, account_deposit, account_retirement, date_begin, date_end): """Generate bi-weekly entries for payroll salary income. Args: employer_name: A string, the human-readable name of the employer. employer_address: A string, the address of the employer. annual_salary: A Decimal, the annual salary of the employee. account_deposit: An account string, the account to deposit the salary to. account_retirement: An account string, the account to deposit retirement contributions to. date_begin: The start date. date_end: The end date. Returns: A list of directives, including open directives for the account. """ preamble = parse(f""" {date_begin} event "employer" "{employer_name}, {employer_address}" {date_begin} open Income:CC:Employer1:Salary CCY ;{date_begin} open Income:CC:Employer1:AnnualBonus CCY {date_begin} open Income:CC:Employer1:GroupTermLife CCY {date_begin} open Income:CC:Employer1:Vacation VACHR {date_begin} open Assets:CC:Employer1:Vacation VACHR {date_begin} open Expenses:Vacation VACHR {date_begin} open Expenses:Health:Life:GroupTermLife {date_begin} open Expenses:Health:Medical:Insurance {date_begin} open Expenses:Health:Dental:Insurance {date_begin} open Expenses:Health:Vision:Insurance ;{date_begin} open Expenses:Vacation:Employer """) date_prev = None contrib_retirement = ZERO contrib_socsec = ZERO biweekly_pay = annual_salary / 26 gross = biweekly_pay medicare = gross * D('0.0231') federal = gross * D('0.2303') state = gross * D('0.0791') city = gross * D('0.0379') sdi = D('1.12') lifeinsurance = D('24.32') dental = D('2.90') medical = D('27.38') vision = D('42.30') fixed = (medicare + federal + state + city + sdi + dental + medical + vision) # Calculate vacation hours per-pay. with decimal.localcontext() as ctx: ctx.prec = 4 vacation_hrs = (ANNUAL_VACATION_DAYS * D('8')) / D('26') transactions = [] for dtime in misc_utils.skipiter( rrule.rrule(rrule.WEEKLY, byweekday=rrule.TH, dtstart=date_begin, until=date_end), 2): date = dtime.date() year = date.year if not date_prev or date_prev.year != date.year: contrib_retirement = RETIREMENT_LIMITS.get(date.year, RETIREMENT_LIMITS[None]) contrib_socsec = D('7000') date_prev = date retirement_uncapped = math.ceil((gross * D('0.25')) / 100) * 100 retirement = min(contrib_retirement, retirement_uncapped) contrib_retirement -= retirement socsec_uncapped = gross * D('0.0610') socsec = min(contrib_socsec, socsec_uncapped) contrib_socsec -= socsec with decimal.localcontext() as ctx: ctx.prec = 6 deposit = (gross - retirement - fixed - socsec) retirement_neg = -retirement gross_neg = -gross lifeinsurance_neg = -lifeinsurance vacation_hrs_neg = -vacation_hrs transactions.extend(parse(f""" {date} * "{employer_name}" "Payroll" {account_deposit} {deposit:.2f} CCY """ + ("" if retirement == ZERO else f"""\ {account_retirement} {retirement:.2f} CCY Assets:CC:Federal:PreTax401k {retirement_neg:.2f} DEFCCY Expenses:Taxes:Y{year}:CC:Federal:PreTax401k {retirement:.2f} DEFCCY """) + f"""\ Income:CC:Employer1:Salary {gross_neg:.2f} CCY Income:CC:Employer1:GroupTermLife {lifeinsurance_neg:.2f} CCY Expenses:Health:Life:GroupTermLife {lifeinsurance:.2f} CCY Expenses:Health:Dental:Insurance {dental} CCY Expenses:Health:Medical:Insurance {medical} CCY Expenses:Health:Vision:Insurance {vision} CCY Expenses:Taxes:Y{year}:CC:Medicare {medicare:.2f} CCY Expenses:Taxes:Y{year}:CC:Federal {federal:.2f} CCY Expenses:Taxes:Y{year}:CC:State {state:.2f} CCY Expenses:Taxes:Y{year}:CC:CityNYC {city:.2f} CCY Expenses:Taxes:Y{year}:CC:SDI {sdi:.2f} CCY Expenses:Taxes:Y{year}:CC:SocSec {socsec:.2f} CCY Assets:CC:Employer1:Vacation {vacation_hrs:.2f} VACHR Income:CC:Employer1:Vacation {vacation_hrs_neg:.2f} VACHR """)) return preamble + transactions def generate_tax_preamble(date_birth): """Generate tax declarations not specific to any particular year. Args: date_birth: A date instance, the birth date of the character. Returns: A list of directives. """ return parse(f""" ;; Tax accounts not specific to a year. {date_birth} open Income:CC:Federal:PreTax401k DEFCCY {date_birth} open Assets:CC:Federal:PreTax401k DEFCCY """) def generate_tax_accounts(year, date_max): """Generate accounts and contribution directives for a particular tax year. Args: year: An integer, the year we're to generate this for. date_max: The maximum date to produce an entry for. Returns: A list of directives. """ date_year = datetime.date(year, 1, 1) date_filing = (datetime.date(year + 1, 3, 20) + datetime.timedelta(days=random.randint(0, 5))) date_federal = (date_filing + datetime.timedelta(days=random.randint(0, 4))) date_state = (date_filing + datetime.timedelta(days=random.randint(0, 4))) quantum = D('0.01') amount_federal = D(max(random.normalvariate(500, 120), 12)).quantize(quantum) amount_federal_neg = -amount_federal amount_state = D(max(random.normalvariate(300, 100), 10)).quantize(quantum) amount_state_neg = -amount_state amount_payable = -(amount_federal + amount_state) amount_limit = RETIREMENT_LIMITS.get(year, RETIREMENT_LIMITS[None]) amount_limit_neg = -amount_limit entries = parse(f""" ;; Open tax accounts for that year. {date_year} open Expenses:Taxes:Y{year}:CC:Federal:PreTax401k DEFCCY {date_year} open Expenses:Taxes:Y{year}:CC:Medicare CCY {date_year} open Expenses:Taxes:Y{year}:CC:Federal CCY {date_year} open Expenses:Taxes:Y{year}:CC:CityNYC CCY {date_year} open Expenses:Taxes:Y{year}:CC:SDI CCY {date_year} open Expenses:Taxes:Y{year}:CC:State CCY {date_year} open Expenses:Taxes:Y{year}:CC:SocSec CCY ;; Check that the tax amounts have been fully used. {date_year} balance Assets:CC:Federal:PreTax401k 0 DEFCCY {date_year} * "Allowed contributions for one year" Income:CC:Federal:PreTax401k {amount_limit_neg} DEFCCY Assets:CC:Federal:PreTax401k {amount_limit} DEFCCY {date_filing} * "Filing taxes for {year}" Expenses:Taxes:Y{year}:CC:Federal {amount_federal:.2f} CCY Expenses:Taxes:Y{year}:CC:State {amount_state:.2f} CCY Liabilities:AccountsPayable {amount_payable:.2f} CCY {date_federal} * "FEDERAL TAXPYMT" Assets:CC:Bank1:Checking {amount_federal_neg:.2f} CCY Liabilities:AccountsPayable {amount_federal:.2f} CCY {date_state} * "STATE TAX & FINANC PYMT" Assets:CC:Bank1:Checking {amount_state_neg:.2f} CCY Liabilities:AccountsPayable {amount_state:.2f} CCY """) return [entry for entry in entries if entry.date < date_max] def generate_retirement_employer_match(entries, account_invest, account_income): """Generate employer matching contributions into a retirement account. Args: entries: A list of directives that cover the retirement account. account_invest: The name of the retirement cash account. account_income: The name of the income account. Returns: A list of new entries generated for employer contributions. """ match_frac = D('0.50') new_entries = parse(f""" {entries[0].date} open {account_income} CCY """) for txn_posting, balances in postings_for(entries, [account_invest]): amount = txn_posting.posting.units.number * match_frac amount_neg = -amount date = txn_posting.txn.date + ONE_DAY new_entries.extend(parse(f""" {date} * "Employer match for contribution" {account_invest} {amount:.2f} CCY {account_income} {amount_neg:.2f} CCY """)) return new_entries def generate_retirement_investments(entries, account, commodities_items, price_map): """Invest money deposited to the given retirement account. Args: entries: A list of directives account: The root account for all retirement investment sub-accounts. commodities_items: A list of (commodity, fraction to be invested in) items. price_map: A dict of prices, as per beancount.core.prices.build_price_map(). Returns: A list of new directives for the given investments. This also generates account opening directives for the desired investment commodities. """ open_entries = [] account_cash = join(account, 'Cash') date_origin = entries[0].date open_entries.extend(parse(f""" {date_origin} open {account} CCY institution: "Retirement_Institution" address: "Retirement_Address" phone: "Retirement_Phone" {date_origin} open {account_cash} CCY number: "882882" """)) for currency, _ in commodities_items: open_entries.extend(parse(f""" {date_origin} open {account}:{currency} {currency} number: "882882" """)) new_entries = [] for txn_posting, balances in postings_for(entries, [account_cash]): balance = balances[account_cash] amount_to_invest = balance.get_currency_units('CCY').number # Find the date the following Monday, the date to invest. txn_date = txn_posting.txn.date while txn_date.weekday() != calendar.MONDAY: txn_date += ONE_DAY amount_invested = ZERO for commodity, fraction in commodities_items: amount_fraction = amount_to_invest * D(fraction) # Find the price at that date. _, price = prices.get_price(price_map, (commodity, 'CCY'), txn_date) units = (amount_fraction / price).quantize(D('0.001')) amount_cash = (units * price).quantize(D('0.01')) amount_cash_neg = -amount_cash new_entries.extend(parse(f""" {txn_date} * "Investing {fraction:.0%} of cash in {commodity}" {account}:{commodity} {units:.3f} {commodity} {{{price:.2f} CCY}} {account}:Cash {amount_cash_neg:.2f} CCY """)) balance.add_amount(amount.Amount(-amount_cash, 'CCY')) return data.sorted(open_entries + new_entries) def generate_banking(entries, date_begin, date_end, amount_initial): """Generate a checking account opening. Args: entries: A list of entries which affect this account. date_begin: A date instance, the beginning date. date_end: A date instance, the end date. amount_initial: A Decimal instance, the amount to initialize the checking account with. Returns: A list of directives. """ amount_initial_neg = -amount_initial new_entries = parse(f""" {date_begin} open Assets:CC:Bank1 institution: "Bank1_Institution" address: "Bank1_Address" phone: "Bank1_Phone" {date_begin} open Assets:CC:Bank1:Checking CCY account: "00234-48574897" ;; {date_begin} open Assets:CC:Bank1:Savings CCY {date_begin} * "Opening Balance for checking account" Assets:CC:Bank1:Checking {amount_initial} CCY Equity:Opening-Balances {amount_initial_neg} CCY """) date_balance = date_begin + datetime.timedelta(days=1) account = 'Assets:CC:Bank1:Checking' for txn_posting, balances in postings_for(data.sorted(entries + new_entries), [account], before=True): if txn_posting.txn.date >= date_balance: break amount_balance = balances[account].get_currency_units('CCY').number bal_entries = parse(f""" {date_balance} balance Assets:CC:Bank1:Checking {amount_balance} CCY """) return new_entries + bal_entries def generate_taxable_investment(date_begin, date_end, entries, price_map, stocks): """Generate opening directives and transactions for an investment account. Args: date_begin: A date instance, the beginning date. date_end: A date instance, the end date. entries: A list of entries that contains at least the transfers to the investment account's cash account. price_map: A dict of prices, as per beancount.core.prices.build_price_map(). stocks: A list of strings, the list of commodities to invest in. Returns: A list of directives. """ account = 'Assets:CC:Investment' income = 'Income:CC:Investment' account_cash = join(account, 'Cash') account_gains = '{income}:PnL'.format(income=income) dividends = 'Dividend' accounts_stocks = ['Assets:CC:Investment:{}'.format(commodity) for commodity in stocks] open_entries = parse(f""" {date_begin} open {account}:Cash CCY {date_begin} open {account_gains} CCY """) for stock in stocks: open_entries.extend(parse(f""" {date_begin} open {account}:{stock} {stock} {date_begin} open {income}:{stock}:{dividends} CCY """)) # Figure out dates at which dividends should be distributed, near the end of # each quarter. days_to = datetime.timedelta(days=3*90-10) dividend_dates = [] for quarter_begin in iter_quarters(date_begin, date_end): end_of_quarter = quarter_begin + days_to if not (date_begin < end_of_quarter < date_end): continue dividend_dates.append(end_of_quarter) # Iterate over all the dates, but merging in the postings for the cash # account. min_amount = D('1000.00') round_amount = D('100.00') commission = D('8.95') round_units = D('1') frac_invest = D('1.00') frac_dividend = D('0.004') p_daily_buy = 1./15 # days p_daily_sell = 1./90 # days stocks_inventory = inventory.Inventory() new_entries = [] dividend_date_iter = iter(dividend_dates) next_dividend_date = next(dividend_date_iter, None) for date, balances in iter_dates_with_balance(date_begin, date_end, entries, [account_cash]): # Check if we should insert a dividend. Note that we could not factor # this out because we want to explicitly reinvest the cash dividends and # we also want the dividends to be proportional to the amount of # invested stock, so one feeds on the other and vice-versa. if next_dividend_date and date > next_dividend_date: # Compute the total balances for the stock accounts in order to # create a realistic dividend. total = inventory.Inventory() for account_stock in accounts_stocks: total.add_inventory(balances[account_stock]) # Create an entry offering dividends of 1% of the portfolio. portfolio_cost = total.reduce(convert.get_cost).get_currency_units('CCY').number amount_cash = (frac_dividend * portfolio_cost).quantize(D('0.01')) amount_cash_neg = -amount_cash stock = random.choice(stocks) cash_dividend = parse(f""" {next_dividend_date} * "Dividends on portfolio" {account}:Cash {amount_cash:.2f} CCY {income}:{stock}:{dividends} {amount_cash_neg:.2f} CCY """)[0] new_entries.append(cash_dividend) # Advance the next dividend date. next_dividend_date = next(dividend_date_iter, None) # If the balance is high, buy with high probability. balance = balances[account_cash] total_cash = balance.get_currency_units('CCY').number assert total_cash >= ZERO, ('Cash balance is negative: {}'.format(total_cash)) invest_cash = total_cash * frac_invest - commission if invest_cash > min_amount: if random.random() < p_daily_buy: commodities = random.sample(stocks, random.randint(1, len(stocks))) lot_amount = round_to(invest_cash / len(commodities), round_amount) invested_amount = ZERO for stock in commodities: # Find the price at that date. _, price = prices.get_price(price_map, (stock, 'CCY'), date) units = round_to((lot_amount / price), round_units) if units <= ZERO: continue amount_cash = -(units * price + commission) # logging.info('Buying %s %s @ %s CCY = %s CCY', # units, stock, price, units * price) buy = parse(f""" {date} * "Buy shares of {stock}" {account}:Cash {amount_cash:.2f} CCY {account}:{stock} {units:.0f} {stock} {{{price:.2f} CCY}} Expenses:Financial:Commissions {commission:.2f} CCY """)[0] new_entries.append(buy) account_stock = ':'.join([account, stock]) balances[account_cash].add_position(buy.postings[0]) balances[account_stock].add_position(buy.postings[1]) stocks_inventory.add_position(buy.postings[1]) # Don't sell on days you buy. continue # Otherwise, sell with low probability. if not stocks_inventory.is_empty() and random.random() < p_daily_sell: # Choose the lot with the highest gain or highest loss. gains = [] for position in stocks_inventory.get_positions(): base_quote = (position.units.currency, position.cost.currency) _, price = prices.get_price(price_map, base_quote, date) if price == position.cost.number: continue # Skip lots without movement. market_value = position.units.number * price book_value = convert.get_cost(position).number gain = market_value - book_value gains.append((gain, market_value, price, position)) if not gains: continue # Sell either biggest winner or biggest loser. biggest = bool(random.random() < 0.5) lot_tuple = sorted(gains)[0 if biggest else -1] gain, market_value, price, sell_position = lot_tuple #logging.info('Selling {} for {}'.format(sell_position, market_value)) sell_position = -sell_position stock = sell_position.units.currency amount_cash = market_value - commission amount_gain = -gain sell = parse(f""" {date} * "Sell shares of {stock}" {account}:{stock} {sell_position} @ {price:.2f} CCY {account}:Cash {amount_cash:.2f} CCY Expenses:Financial:Commissions {commission:.2f} CCY {account_gains} {amount_gain:.2f} CCY """)[0] new_entries.append(sell) balances[account_cash].add_position(sell.postings[1]) stocks_inventory.add_position(sell.postings[0]) continue return open_entries + new_entries def generate_clearing_entries(date_iter, payee, narration, entries, account_clear, account_from): """Generate entries to clear the value of an account. Args: date_iter: An iterator of datetime.date instances. payee: A string, the payee name to use on the transactions. narration: A string, the narration to use on the transactions. entries: A list of entries. account_clear: The account to clear. account_from: The source account to clear 'account_clear' from. Returns: A list of directives. """ new_entries = [] # The next date we're looking for. date_iter = iter(date_iter) next_date = next(date_iter, None) if not next_date: return new_entries # Iterate over all the postings of the account to clear. for txn_posting, balances in postings_for(entries, [account_clear]): balance_clear = balances[account_clear] # Check if we need to clear. if next_date <= txn_posting.txn.date: pos_amount = balance_clear.get_currency_units('CCY') neg_amount = -pos_amount new_entries.extend(parse(f""" {next_date} * "{payee}" "{narration}" {account_clear} {neg_amount.number:.2f} CCY {account_from} {pos_amount.number:.2f} CCY """)) balance_clear.add_amount(neg_amount) # Advance to the next date we're looking for. next_date = next(date_iter, None) if not next_date: break return new_entries def generate_outgoing_transfers(entries, account, account_out, transfer_minimum, transfer_threshold, transfer_increment): """Generate transfers of accumulated funds out of an account. This monitors the balance of an account and when it is beyond a threshold, generate out transfers form that account to another account. Args: entries: A list of existing entries that affect this account so far. The generated entries will also affect this account. account: An account string, the account to monitor. account_out: An account string, the savings account to make transfers to. transfer_minimum: The minimum amount of funds to always leave in this account after a transfer. transfer_threshold: The minimum amount of funds to be able to transfer out without breaking the minimum. transfer_increment: A Decimal, the increment to round transfers to. Returns: A list of new directives, the transfers to add to the given account. """ last_date = entries[-1].date # Reverse the balance amounts taking into account the minimum balance for # all time in the future. amounts = [(balances[account].get_currency_units('CCY').number, txn_posting) for txn_posting, balances in postings_for(entries, [account])] reversed_amounts = [] last_amount, _ = amounts[-1] for current_amount, _ in reversed(amounts): if current_amount < last_amount: reversed_amounts.append(current_amount) last_amount = current_amount else: reversed_amounts.append(last_amount) capped_amounts = reversed(reversed_amounts) # Create transfers outward where the future allows it. new_entries = [] offset_amount = ZERO for current_amount, (_, txn_posting) in zip(capped_amounts, amounts): if txn_posting.txn.date >= last_date: break adjusted_amount = current_amount - offset_amount if adjusted_amount > (transfer_minimum + transfer_threshold): amount_transfer = round_to(adjusted_amount - transfer_minimum, transfer_increment) date = txn_posting.txn.date + datetime.timedelta(days=1) amount_transfer_neg = -amount_transfer new_entries.extend(parse(f""" {date} * "Transfering accumulated savings to other account" {account} {amount_transfer_neg:2f} CCY {account_out} {amount_transfer:2f} CCY """)) offset_amount += amount_transfer return new_entries def generate_expense_accounts(date_birth): """Generate directives for expense accounts. Args: date_birth: Birth date of the character. Returns: A list of directives. """ return parse(f""" {date_birth} open Expenses:Food:Groceries {date_birth} open Expenses:Food:Restaurant {date_birth} open Expenses:Food:Coffee {date_birth} open Expenses:Food:Alcohol {date_birth} open Expenses:Transport:Tram {date_birth} open Expenses:Home:Rent {date_birth} open Expenses:Home:Electricity {date_birth} open Expenses:Home:Internet {date_birth} open Expenses:Home:Phone {date_birth} open Expenses:Financial:Fees {date_birth} open Expenses:Financial:Commissions """) def generate_open_entries(date, accounts, currency=None): """Generate a list of Open entries for the given accounts: Args: date: A datetime.date instance for the open entries. accounts: A list of account strings. currency: An optional currency constraint. Returns: A list of Open directives. """ assert isinstance(accounts, (list, tuple)) return parse(''.join( '{date} open {account} {currency}\n'.format(date=date, account=account, currency=currency or '') for account in accounts)) def generate_balance_checks(entries, account, date_iter): """Generate balance check entries to the given frequency. Args: entries: A list of directives that contain all the transactions for the accounts. account: The name of the account for which to generate. date_iter: Iterator of dates. We generate balance checks at these dates. Returns: A list of balance check entries. """ balance_checks = [] date_iter = iter(date_iter) next_date = next(date_iter) with misc_utils.swallow(StopIteration): for txn_posting, balance in postings_for(entries, [account], before=True): while txn_posting.txn.date >= next_date: amount = balance[account].get_currency_units('CCY').number balance_checks.extend(parse(f""" {next_date} balance {account} {amount} CCY """)) next_date = next(date_iter) return balance_checks def validate_output(contents, positive_accounts, currency): """Check that the output file validates. Args: contents: A string, the output file. positive_accounts: A list of strings, account names to check for non-negative balances. currency: A string, the currency to check minimums for. Raises: AssertionError: If the output does not validate. """ loaded_entries, _, _ = loader.load_string( contents, log_errors=sys.stderr, extra_validations=validation.HARDCORE_VALIDATIONS) # Sanity checks: Check that the checking balance never goes below zero. for account in positive_accounts: check_non_negative(loaded_entries, account, currency) def generate_banking_expenses(date_begin, date_end, account, rent_amount): """Generate expenses paid out of a checking account, typically living expenses. Args: date_begin: The start date. date_end: The end date. account: The checking account to generate expenses to. rent_amount: The amount of rent. Returns: A list of directives. """ fee_expenses = generate_periodic_expenses( rrule.rrule(rrule.MONTHLY, bymonthday=4, dtstart=date_begin, until=date_end), "BANK FEES", "Monthly bank fee", account, 'Expenses:Financial:Fees', lambda: D('4.00')) rent_expenses = generate_periodic_expenses( delay_dates(rrule.rrule(rrule.MONTHLY, dtstart=date_begin, until=date_end), 2, 5), "RiverBank Properties", "Paying the rent", account, 'Expenses:Home:Rent', lambda: random.normalvariate(float(rent_amount), 0)) electricity_expenses = generate_periodic_expenses( delay_dates(rrule.rrule(rrule.MONTHLY, dtstart=date_begin, until=date_end), 7, 8), "EDISON POWER", "", account, 'Expenses:Home:Electricity', lambda: random.normalvariate(65, 0)) internet_expenses = generate_periodic_expenses( delay_dates(rrule.rrule(rrule.MONTHLY, dtstart=date_begin, until=date_end), 20, 22), "Wine-Tarner Cable", "", account, 'Expenses:Home:Internet', lambda: random.normalvariate(80, 0.10)) phone_expenses = generate_periodic_expenses( delay_dates(rrule.rrule(rrule.MONTHLY, dtstart=date_begin, until=date_end), 17, 19), "Verizon Wireless", "", account, 'Expenses:Home:Phone', lambda: random.normalvariate(60, 10)) return data.sorted(fee_expenses + rent_expenses + electricity_expenses + internet_expenses + phone_expenses) def generate_regular_credit_expenses(date_birth, date_begin, date_end, account_credit, account_checking): """Generate expenses paid out of a credit card account, including payments to the credit card. Args: date_birth: The user's birth date. date_begin: The start date. date_end: The end date. account_credit: The credit card account to generate expenses against. account_checking: The checking account to generate payments from. Returns: A list of directives. """ restaurant_expenses = generate_periodic_expenses( date_random_seq(date_begin, date_end, 1, 5), RESTAURANT_NAMES, RESTAURANT_NARRATIONS, account_credit, 'Expenses:Food:Restaurant', lambda: min(random.lognormvariate(math.log(30), math.log(1.5)), random.randint(200, 220))) groceries_expenses = generate_periodic_expenses( date_random_seq(date_begin, date_end, 5, 20), GROCERIES_NAMES, "Buying groceries", account_credit, 'Expenses:Food:Groceries', lambda: min(random.lognormvariate(math.log(80), math.log(1.3)), random.randint(250, 300))) subway_expenses = generate_periodic_expenses( date_random_seq(date_begin, date_end, 27, 33), "Metro Transport Authority", "Tram tickets", account_credit, 'Expenses:Transport:Tram', lambda: D('120.00')) credit_expenses = data.sorted(restaurant_expenses + groceries_expenses + subway_expenses) # Entries to open accounts. credit_preamble = generate_open_entries(date_birth, [account_credit], 'CCY') return data.sorted(credit_preamble + credit_expenses) def compute_trip_dates(date_begin, date_end): """Generate dates at reasonable intervals for trips during the given time period. Args: date_begin: The start date. date_end: The end date. Yields: Pairs of dates for the trips within the period. """ # Min and max number of days remaining at home. days_at_home = (4*30, 13*30) # Length of trip. days_trip = (8, 22) # Number of days to ensure no trip at the beginning and the end. days_buffer = 21 date_begin += datetime.timedelta(days=days_buffer) date_end -= datetime.timedelta(days=days_buffer) date = date_begin while 1: duration_at_home = datetime.timedelta(days=random.randint(*days_at_home)) duration_trip = datetime.timedelta(days=random.randint(*days_trip)) date_trip_begin = date + duration_at_home date_trip_end = date_trip_begin + duration_trip if date_trip_end >= date_end: break yield (date_trip_begin, date_trip_end) date = date_trip_end def generate_trip_entries(date_begin, date_end, tag, config, trip_city, home_city, account_credit): """Generate more dense expenses for a trip. Args: date_begin: A datetime.date instance, the beginning of the trip. date_end: A datetime.date instance, the end of the trip. tag: A string, the name of the tag. config: A list of (payee name, account name, (mu, 3sigma)), where mu is the mean of the prices to generate and 3sigma is 3 times the standard deviation. trip_city: A string, the capitalized name of the destination city. home_city: A string, the name of the home city. account_credit: A string, the name of the credit card account to pay the expenses from. Returns: A list of entries for the trip, all tagged with the given tag. """ p_day_generate = 0.3 new_entries = [] for date in date_iter(date_begin, date_end): for payee, account_expense, (mu, sigma3) in config: if random.random() < p_day_generate: amount = random.normalvariate(mu, sigma3 / 3.) amount_neg = -amount new_entries.extend(parse(f""" {date} * "{payee}" "" #{tag} {account_credit} {amount_neg:.2f} CCY {account_expense} {amount:.2f} CCY """)) # Consume the vacation days. vacation_hrs = (date_end - date_begin).days * 8 # hrs/day new_entries.extend(parse(f""" {date_end} * "Consume vacation days" Assets:CC:Employer1:Vacation -{vacation_hrs:.2f} VACHR Expenses:Vacation {vacation_hrs:.2f} VACHR """)) # Generate events for the trip. new_entries.extend(parse(f""" {date_begin} event "location" "{trip_city}" {date_end} event "location" "{home_city}" """)) return new_entries def generate_prices(date_begin, date_end, currencies, cost_currency): """Generate weekly or monthly price entries for the given currencies. Args: date_begin: The start date. date_end: The end date. currencies: A list of currency strings to generate prices for. cost_currency: A string, the cost currency. Returns: A list of Price directives. """ digits = D('0.01') entries = [] counter = itertools.count() for currency in currencies: start_price = random.uniform(30, 200) growth = random.uniform(0.02, 0.13) # %/year mu = growth * (7 / 365) sigma = random.uniform(0.005, 0.02) # Vol for dtime, price_float in zip(rrule.rrule(rrule.WEEKLY, byweekday=rrule.FR, dtstart=date_begin, until=date_end), price_series(start_price, mu, sigma)): price = D(price_float).quantize(digits) meta = data.new_metadata(generate_prices.__name__, next(counter)) entry = data.Price(meta, dtime.date(), currency, amount.Amount(price, cost_currency)) entries.append(entry) return entries def replace(string, replacements, strip=False): """Apply word-boundaried regular expression replacements to an indented string. Args: string: Some input template string. replacements: A dict of regexp to replacement value. strip: A boolean, true if we should strip the input. Returns: The input string with the replacements applied to it, with the indentation removed. """ output = textwrap.dedent(string) if strip: output = output.strip() for from_, to_ in replacements.items(): if not isinstance(to_, str) and not callable(to_): to_ = str(to_) output = re.sub(r'\b{}\b'.format(from_), to_, output) return output def generate_commodity_entries(date_birth): """Create a list of Commodity entries for all the currencies we're using. Args: date_birth: A datetime.date instance, the date of birth of the user. Returns: A list of Commodity entries for all the commodities in use. """ return parse(f""" 1792-01-01 commodity USD name: "US Dollar" export: "CASH" {date_birth} commodity VACHR name: "Employer Vacation Hours" export: "IGNORE" {date_birth} commodity IRAUSD name: "US 401k and IRA Contributions" export: "IGNORE" 2009-05-01 commodity RGAGX name: "American Funds The Growth Fund of America Class R-6" export: "MUTF:RGAGX" price: "USD:google/MUTF:RGAGX" 1995-09-18 commodity VBMPX name: "Vanguard Total Bond Market Index Fund Institutional Plus Shares" export: "MUTF:VBMPX" price: "USD:google/MUTF:VBMPX" 2004-01-20 commodity ITOT name: "iShares Core S&P Total U.S. Stock Market ETF" export: "NYSEARCA:ITOT" price: "USD:google/NYSEARCA:ITOT" 2007-07-20 commodity VEA name: "Vanguard FTSE Developed Markets ETF" export: "NYSEARCA:VEA" price: "USD:google/NYSEARCA:VEA" 2004-01-26 commodity VHT name: "Vanguard Health Care ETF" export: "NYSEARCA:VHT" price: "USD:google/NYSEARCA:VHT" 2004-11-01 commodity GLD name: "SPDR Gold Trust (ETF)" export: "NYSEARCA:GLD" price: "USD:google/NYSEARCA:GLD" 1900-01-01 commodity VMMXX export: "MUTF:VMMXX (MONEY:USD)" """) def contextualize_file(contents, employer): """Replace generic strings in the generated file with realistic strings. Args: contents: A string, the generic file contents. Returns: A string, the contextualized version. """ replacements = { 'CC': 'US', 'Bank1': 'BofA', 'Bank1_Institution': 'Bank of America', 'Bank1_Address': '123 America Street, LargeTown, USA', 'Bank1_Phone': '+1.012.345.6789', 'CreditCard1': 'Chase:Slate', 'CreditCard2': 'Amex:BlueCash', 'Employer1': employer, 'Retirement': 'Vanguard', 'Retirement_Institution': 'Vanguard Group', 'Retirement_Address': "P.O. Box 1110, Valley Forge, PA 19482-1110", 'Retirement_Phone': "+1.800.523.1188", 'Investment': 'ETrade', # Commodities 'CCY': 'USD', 'VACHR': 'VACHR', 'DEFCCY': 'IRAUSD', 'MFUND1': 'VBMPX', 'MFUND2': 'RGAGX', 'STK1': 'ITOT', 'STK2': 'VEA', 'STK3': 'VHT', 'STK4': 'GLD', } new_contents = replace(contents, replacements) return new_contents, replacements ZERO = Decimal() def D(strord=None): """Convert a string into a Decimal object. This is used in parsing amounts from files in the importers. This is the main function you should use to build all numbers the system manipulates (never use floating-point in an accounting system). Commas are stripped and ignored, as they are assumed to be thousands separators (the French comma separator as decimal is not supported). This function just returns the argument if it is already a Decimal object, for convenience. Args: strord: A string or Decimal instance. Returns: A Decimal instance. """ try: # Note: try a map lookup and optimize performance here. if strord is None or strord == '': return Decimal() elif isinstance(strord, str): return Decimal(_CLEAN_NUMBER_RE.sub('', strord)) elif isinstance(strord, Decimal): return strord elif isinstance(strord, (int, float)): return Decimal(strord) else: assert strord is None, "Invalid value to convert: {}".format(strord) except Exception as exc: raise ValueError("Impossible to create Decimal instance from {!s}: {}".format( strord, exc)) from exc def round_to(number, increment): """Round a number *down* to a particular increment. Args: number: A Decimal, the number to be rounded. increment: A Decimal, the size of the increment. Returns: A Decimal, the rounded number. """ return int((number / increment)) * increment def join(*components: Tuple[str]) -> Account: """Join the names with the account separator. Args: *components: Strings, the components of an account name. Returns: A string, joined in a single account name. """ return sep.join(components) The provided code snippet includes necessary dependencies for implementing the `write_example_file` function. Write a Python function `def write_example_file(date_birth, date_begin, date_end, reformat, file)` to solve the following problem: Generate the example file. Args: date_birth: A datetime.date instance, the birth date of our character. date_begin: A datetime.date instance, the beginning date at which to generate transactions. date_end: A datetime.date instance, the end date at which to generate transactions. reformat: A boolean, true if we should apply global reformatting to this file. file: A file object, where to write out the output. Here is the function: def write_example_file(date_birth, date_begin, date_end, reformat, file): """Generate the example file. Args: date_birth: A datetime.date instance, the birth date of our character. date_begin: A datetime.date instance, the beginning date at which to generate transactions. date_end: A datetime.date instance, the end date at which to generate transactions. reformat: A boolean, true if we should apply global reformatting to this file. file: A file object, where to write out the output. """ # The following code entirely writes out the output to generic names, such # as "Employer1", "Bank1", and "CCY" (for principal currency). Those names # are purposely chosen to be unique, and only near the very end do we make # renamings to more specific and realistic names. # Name of the checking account. account_opening = 'Equity:Opening-Balances' account_payable = 'Liabilities:AccountsPayable' account_checking = 'Assets:CC:Bank1:Checking' account_credit = 'Liabilities:CC:CreditCard1' account_retirement = 'Assets:CC:Retirement' account_investing = 'Assets:CC:Investment:Cash' # Commodities. commodity_entries = generate_commodity_entries(date_birth) # Estimate the rent. rent_amount = round_to(ANNUAL_SALARY / RENT_DIVISOR, RENT_INCREMENT) # Get a random employer. employer_name, employer_address = random.choice(EMPLOYERS) logging.info("Generating Salary Employment Income") income_entries = generate_employment_income(employer_name, employer_address, ANNUAL_SALARY, account_checking, join(account_retirement, 'Cash'), date_begin, date_end) logging.info("Generating Expenses from Banking Accounts") banking_expenses = generate_banking_expenses(date_begin, date_end, account_checking, rent_amount) logging.info("Generating Regular Expenses via Credit Card") credit_regular_entries = generate_regular_credit_expenses( date_birth, date_begin, date_end, account_credit, account_checking) logging.info("Generating Credit Card Expenses for Trips") trip_entries = [] destinations = sorted(TRIP_DESTINATIONS.items()) destinations.extend(destinations) random.shuffle(destinations) for (date_trip_begin, date_trip_end), (destination_name, config) in zip( compute_trip_dates(date_begin, date_end), destinations): # Compute a suitable tag. tag = 'trip-{}-{}'.format(destination_name.lower().replace(' ', '-'), date_trip_begin.year) #logging.info("%s -- %s %s", tag, date_trip_begin, date_trip_end) # Remove regular entries during this trip. credit_regular_entries = [entry for entry in credit_regular_entries if not(date_trip_begin <= entry.date < date_trip_end)] # Generate entries for the trip. this_trip_entries = generate_trip_entries( date_trip_begin, date_trip_end, tag, config, destination_name.replace('-', ' ').title(), HOME_NAME, account_credit) trip_entries.extend(this_trip_entries) logging.info("Generating Credit Card Payment Entries") credit_payments = generate_clearing_entries( delay_dates(rrule.rrule(rrule.MONTHLY, dtstart=date_begin, until=date_end, bymonthday=7), 0, 4), "CreditCard1", "Paying off credit card", credit_regular_entries, account_credit, account_checking) credit_entries = credit_regular_entries + trip_entries + credit_payments logging.info("Generating Tax Filings and Payments") tax_preamble = generate_tax_preamble(date_birth) # Figure out all the years we need tax accounts for. years = set() for account_name in getters.get_accounts(income_entries): match = re.match(r'Expenses:Taxes:Y(\d\d\d\d)', account_name) if match: years.add(int(match.group(1))) taxes = [(year, generate_tax_accounts(year, date_end)) for year in sorted(years)] tax_entries = tax_preamble + functools.reduce(operator.add, (entries for _, entries in taxes)) logging.info("Generating Opening of Banking Accounts") # Open banking accounts and gift the checking account with a balance that # will offset all the amounts to ensure a positive balance throughout its # lifetime. entries_for_banking = data.sorted(income_entries + banking_expenses + credit_entries + tax_entries) minimum = get_minimum_balance(entries_for_banking, account_checking, 'CCY') banking_entries = generate_banking(entries_for_banking, date_begin, date_end, max(-minimum, ZERO)) logging.info("Generating Transfers to Investment Account") banking_transfers = generate_outgoing_transfers( data.sorted(income_entries + banking_entries + banking_expenses + credit_entries + tax_entries), account_checking, account_investing, transfer_minimum=D('200'), transfer_threshold=D('3000'), transfer_increment=D('500')) logging.info("Generating Prices") # Generate price entries for investment currencies and create a price map to # use for later for generating investment transactions. funds_allocation = {'MFUND1': 0.40, 'MFUND2': 0.60} stocks = ['STK1', 'STK2', 'STK3', 'STK4'] price_entries = generate_prices(date_begin, date_end, sorted(funds_allocation.keys()) + stocks, 'CCY') price_map = prices.build_price_map(price_entries) logging.info("Generating Employer Match Contribution") account_match = 'Income:US:Employer1:Match401k' retirement_match = generate_retirement_employer_match(income_entries, join(account_retirement, 'Cash'), account_match) logging.info("Generating Retirement Investments") retirement_entries = generate_retirement_investments( income_entries + retirement_match, account_retirement, sorted(funds_allocation.items()), price_map) logging.info("Generating Taxes Investments") investment_entries = generate_taxable_investment(date_begin, date_end, banking_transfers, price_map, stocks) logging.info("Generating Expense Accounts") expense_accounts_entries = generate_expense_accounts(date_birth) logging.info("Generating Equity Accounts") equity_entries = generate_open_entries(date_birth, [account_opening, account_payable]) logging.info("Generating Balance Checks") credit_checks = generate_balance_checks(credit_entries, account_credit, date_random_seq(date_begin, date_end, 20, 30)) banking_checks = generate_balance_checks(data.sorted(income_entries + banking_entries + banking_expenses + banking_transfers + credit_entries + tax_entries), account_checking, date_random_seq(date_begin, date_end, 20, 30)) logging.info("Outputting and Formatting Entries") dcontext = display_context.DisplayContext() default_int_digits = 8 for currency, precision in {'USD': 2, 'CAD': 2, 'VACHR':0, 'IRAUSD': 2, 'VBMPX': 3, 'RGAGX': 3, 'ITOT': 0, 'VEA': 0, 'VHT': 0, 'GLD': 0}.items(): int_digits = default_int_digits if precision > 0: int_digits += 1 + precision dcontext.update(D('{{:0{}.{}f}}'.format(int_digits, precision).format(0)), currency) output = io.StringIO() def output_section(title, entries): output.write('\n\n\n{}\n\n'.format(title)) printer.print_entries(data.sorted(entries), dcontext, file=output) output.write(FILE_PREAMBLE.format(**locals())) output_section('* Commodities', commodity_entries) output_section('* Equity Accounts', equity_entries) output_section('* Banking', data.sorted(banking_entries + banking_expenses + banking_transfers + banking_checks)) output_section('* Credit-Cards', data.sorted(credit_entries + credit_checks)) output_section('* Taxable Investments', investment_entries) output_section('* Retirement Investments', data.sorted(retirement_entries + retirement_match)) output_section('* Sources of Income', income_entries) output_section('* Taxes', tax_preamble) for year, entries in taxes: output_section('** Tax Year {}'.format(year), entries) output_section('* Expenses', expense_accounts_entries) output_section('* Prices', price_entries) output_section('* Cash', []) logging.info("Contextualizing to Realistic Names") contents, replacements = contextualize_file(output.getvalue(), employer_name) if reformat: contents = format.align_beancount(contents) logging.info("Writing contents") file.write(contents) logging.info("Validating Results") validate_output(contents, [replace(account, replacements) for account in [account_checking]], replace('CCY', replacements))
Generate the example file. Args: date_birth: A datetime.date instance, the birth date of our character. date_begin: A datetime.date instance, the beginning date at which to generate transactions. date_end: A datetime.date instance, the end date at which to generate transactions. reformat: A boolean, true if we should apply global reformatting to this file. file: A file object, where to write out the output.
3,148
from typing import List, Tuple import collections import logging import os import re import sys import click from beancount import loader from beancount.core import account from beancount.core import account_types from beancount.core import compare from beancount.core import convert from beancount.core import data from beancount.core.display_context import Align from beancount.core import getters from beancount.core import inventory from beancount.core import prices from beancount.core import realization from beancount.parser.context import render_file_context from beancount.parser import lexer from beancount.parser import options from beancount.parser import parser from beancount.parser import printer from beancount.parser.version import VERSION from beancount.scripts.directories import validate_directories def doctor(): pass
null
3,149
from typing import List, Tuple import collections import logging import os import re import sys import click from beancount import loader from beancount.core import account from beancount.core import account_types from beancount.core import compare from beancount.core import convert from beancount.core import data from beancount.core.display_context import Align from beancount.core import getters from beancount.core import inventory from beancount.core import prices from beancount.core import realization from beancount.parser.context import render_file_context from beancount.parser import lexer from beancount.parser import options from beancount.parser import parser from beancount.parser import printer from beancount.parser.version import VERSION from beancount.scripts.directories import validate_directories The provided code snippet includes necessary dependencies for implementing the `lex` function. Write a Python function `def lex(filename)` to solve the following problem: Dump the lexer output for a Beancount syntax file. Here is the function: def lex(filename): """Dump the lexer output for a Beancount syntax file.""" for token, lineno, text, obj in lexer.lex_iter(filename): sys.stdout.write('{:12} {:6d} {}\n'.format( '(None)' if token is None else token, lineno, repr(text)))
Dump the lexer output for a Beancount syntax file.
3,150
from typing import List, Tuple import collections import logging import os import re import sys import click from beancount import loader from beancount.core import account from beancount.core import account_types from beancount.core import compare from beancount.core import convert from beancount.core import data from beancount.core.display_context import Align from beancount.core import getters from beancount.core import inventory from beancount.core import prices from beancount.core import realization from beancount.parser.context import render_file_context from beancount.parser import lexer from beancount.parser import options from beancount.parser import parser from beancount.parser import printer from beancount.parser.version import VERSION from beancount.scripts.directories import validate_directories The provided code snippet includes necessary dependencies for implementing the `parse` function. Write a Python function `def parse(filename)` to solve the following problem: Parse the a ledger in debug mode. Run the parser on ledger FILENAME with debug mode active. Here is the function: def parse(filename): """Parse the a ledger in debug mode. Run the parser on ledger FILENAME with debug mode active. """ entries, errors, _ = parser.parse_file(filename, debug=True)
Parse the a ledger in debug mode. Run the parser on ledger FILENAME with debug mode active.
3,151
from typing import List, Tuple import collections import logging import os import re import sys import click from beancount import loader from beancount.core import account from beancount.core import account_types from beancount.core import compare from beancount.core import convert from beancount.core import data from beancount.core.display_context import Align from beancount.core import getters from beancount.core import inventory from beancount.core import prices from beancount.core import realization from beancount.parser.context import render_file_context from beancount.parser import lexer from beancount.parser import options from beancount.parser import parser from beancount.parser import printer from beancount.parser.version import VERSION from beancount.scripts.directories import validate_directories The provided code snippet includes necessary dependencies for implementing the `roundtrip` function. Write a Python function `def roundtrip(filename)` to solve the following problem: Round-trip test on arbitrary ledger. Read transactions from ledger FILENAME, print them out, re-read them again and compare them. Both sets of parsed entries should be equal. Both printed files are output to disk, so you can also run diff on them yourself afterwards. Here is the function: def roundtrip(filename): """Round-trip test on arbitrary ledger. Read transactions from ledger FILENAME, print them out, re-read them again and compare them. Both sets of parsed entries should be equal. Both printed files are output to disk, so you can also run diff on them yourself afterwards. """ round1_filename = round2_filename = None try: logging.basicConfig(level=logging.INFO, format='%(levelname)-8s: %(message)s') logging.info("Read the entries") entries, errors, options_map = loader.load_file(filename) printer.print_errors(errors, file=sys.stderr) logging.info("Print them out to a file") basename, extension = os.path.splitext(filename) round1_filename = ''.join([basename, '.roundtrip1', extension]) with open(round1_filename, 'w') as outfile: printer.print_entries(entries, file=outfile) logging.info("Read the entries from that file") # Note that we don't want to run any of the auto-generation here, but # parsing now returns incomplete objects and we assume idempotence on a # file that was output from the printer after having been processed, so # it shouldn't add anything new. That is, a processed file printed and # resolve when parsed again should contain the same entries, i.e. # nothing new should be generated. entries_roundtrip, errors, options_map = loader.load_file(round1_filename) # Print out the list of errors from parsing the results. if errors: print(',----------------------------------------------------------------------') printer.print_errors(errors, file=sys.stdout) print('`----------------------------------------------------------------------') logging.info("Print what you read to yet another file") round2_filename = ''.join([basename, '.roundtrip2', extension]) with open(round2_filename, 'w') as outfile: printer.print_entries(entries_roundtrip, file=outfile) logging.info("Compare the original entries with the re-read ones") same, missing1, missing2 = compare.compare_entries(entries, entries_roundtrip) if same: logging.info('Entries are the same. Congratulations.') else: logging.error('Entries differ!') print() print('\n\nMissing from original:') for entry in entries: print(entry) print(compare.hash_entry(entry)) print(printer.format_entry(entry)) print() print('\n\nMissing from round-trip:') for entry in missing2: print(entry) print(compare.hash_entry(entry)) print(printer.format_entry(entry)) print() finally: for rfilename in (round1_filename, round2_filename): if os.path.exists(rfilename): os.remove(rfilename)
Round-trip test on arbitrary ledger. Read transactions from ledger FILENAME, print them out, re-read them again and compare them. Both sets of parsed entries should be equal. Both printed files are output to disk, so you can also run diff on them yourself afterwards.
3,152
from typing import List, Tuple import collections import logging import os import re import sys import click from beancount import loader from beancount.core import account from beancount.core import account_types from beancount.core import compare from beancount.core import convert from beancount.core import data from beancount.core.display_context import Align from beancount.core import getters from beancount.core import inventory from beancount.core import prices from beancount.core import realization from beancount.parser.context import render_file_context from beancount.parser import lexer from beancount.parser import options from beancount.parser import parser from beancount.parser import printer from beancount.parser.version import VERSION from beancount.scripts.directories import validate_directories def validate_directories(entries, document_dirs): """Validate a directory hierarchy against a ledger's account names. Read a ledger's list of account names and check that all the capitalized subdirectory names under the given roots match the account names. Args: entries: A list of directives. document_dirs: A list of string, the directory roots to walk and validate. """ # Get the list of accounts declared in the ledge. accounts = getters.get_accounts(entries) # For each of the roots, validate the hierarchy of directories. for document_dir in document_dirs: errors = validate_directory(accounts, document_dir) for error in errors: print("ERROR: {}".format(error)) The provided code snippet includes necessary dependencies for implementing the `directories` function. Write a Python function `def directories(filename, dirs)` to solve the following problem: Validate a directory hierarchy against the ledger's account names. Read a ledger's list of account names and check that all the capitalized subdirectory names under the given roots match the account names. Args: filename: A string, the Beancount input filename. args: The rest of the arguments provided on the command-line, which in this case will be interpreted as the names of root directories to validate against the accounts in the given ledger. Here is the function: def directories(filename, dirs): """Validate a directory hierarchy against the ledger's account names. Read a ledger's list of account names and check that all the capitalized subdirectory names under the given roots match the account names. Args: filename: A string, the Beancount input filename. args: The rest of the arguments provided on the command-line, which in this case will be interpreted as the names of root directories to validate against the accounts in the given ledger. """ entries, _, __ = loader.load_file(filename) validate_directories(entries, dirs)
Validate a directory hierarchy against the ledger's account names. Read a ledger's list of account names and check that all the capitalized subdirectory names under the given roots match the account names. Args: filename: A string, the Beancount input filename. args: The rest of the arguments provided on the command-line, which in this case will be interpreted as the names of root directories to validate against the accounts in the given ledger.
3,153
from typing import List, Tuple import collections import logging import os import re import sys import click from beancount import loader from beancount.core import account from beancount.core import account_types from beancount.core import compare from beancount.core import convert from beancount.core import data from beancount.core.display_context import Align from beancount.core import getters from beancount.core import inventory from beancount.core import prices from beancount.core import realization from beancount.parser.context import render_file_context from beancount.parser import lexer from beancount.parser import options from beancount.parser import parser from beancount.parser import printer from beancount.parser.version import VERSION from beancount.scripts.directories import validate_directories The provided code snippet includes necessary dependencies for implementing the `list_options` function. Write a Python function `def list_options()` to solve the following problem: List available options. Here is the function: def list_options(): """List available options.""" print(options.list_options())
List available options.
3,154
from typing import List, Tuple import collections import logging import os import re import sys import click from beancount import loader from beancount.core import account from beancount.core import account_types from beancount.core import compare from beancount.core import convert from beancount.core import data from beancount.core.display_context import Align from beancount.core import getters from beancount.core import inventory from beancount.core import prices from beancount.core import realization from beancount.parser.context import render_file_context from beancount.parser import lexer from beancount.parser import options from beancount.parser import parser from beancount.parser import printer from beancount.parser.version import VERSION from beancount.scripts.directories import validate_directories The provided code snippet includes necessary dependencies for implementing the `print_options` function. Write a Python function `def print_options(filename)` to solve the following problem: List options parsed from a ledger. Here is the function: def print_options(filename): """List options parsed from a ledger.""" _, __, options_map = loader.load_file(filename) for key, value in sorted(options_map.items()): print('{}: {}'.format(key, value))
List options parsed from a ledger.
3,155
from typing import List, Tuple import collections import logging import os import re import sys import click from beancount import loader from beancount.core import account from beancount.core import account_types from beancount.core import compare from beancount.core import convert from beancount.core import data from beancount.core.display_context import Align from beancount.core import getters from beancount.core import inventory from beancount.core import prices from beancount.core import realization from beancount.parser.context import render_file_context from beancount.parser import lexer from beancount.parser import options from beancount.parser import parser from beancount.parser import printer from beancount.parser.version import VERSION from beancount.scripts.directories import validate_directories def render_file_context(entries, options_map, filename, lineno): """Render the context before and after a particular transaction is applied. Args: entries: A list of directives. options_map: A dict of options, as produced by the parser. filename: A string, the name of the file from which the transaction was parsed. lineno: An integer, the line number in the file the transaction was parsed from. Returns: A multiline string of text, which consists of the context before the transaction is applied, the transaction itself, and the context after it is applied. You can just print that, it is in form that is intended to be consumed by the user. """ # Find the closest entry. closest_entry = data.find_closest(entries, filename, lineno) if closest_entry is None: raise SystemExit("No entry could be found before {}:{}".format(filename, lineno)) # Run just the parser stage (no booking nor interpolation, which would # remove the postings) on the input file to produced the corresponding # unbooked transaction, so that we can get the list of accounts. if path.exists(filename): parsed_entries, _, __= parser.parse_file(filename) # Note: We cannot bisect as we cannot rely on sorting behavior from the parser. lineno = closest_entry.meta['lineno'] closest_parsed_entries = [parsed_entry for parsed_entry in parsed_entries if parsed_entry.meta['lineno'] == lineno] if len(closest_parsed_entries) != 1: # This is an internal error, this should never occur. raise RuntimeError( "Parsed entry corresponding to real entry not found in original filename.") closest_parsed_entry = next(iter(closest_parsed_entries)) else: closest_parsed_entry = None return render_entry_context(entries, options_map, closest_entry, closest_parsed_entry) The provided code snippet includes necessary dependencies for implementing the `context` function. Write a Python function `def context(filename, location)` to solve the following problem: Describe transaction context. The transaction is looked up in ledger FILENAME at LOCATION. The LOCATION argument is either a line number or a filename:lineno tuple to indicate a location in a ledger included from the main input file. Here is the function: def context(filename, location): """Describe transaction context. The transaction is looked up in ledger FILENAME at LOCATION. The LOCATION argument is either a line number or a filename:lineno tuple to indicate a location in a ledger included from the main input file. """ search_filename, lineno = location if search_filename is None: search_filename = filename # Load the input files. entries, errors, options_map = loader.load_file(filename) str_context = render_file_context(entries, options_map, search_filename, lineno) sys.stdout.write(str_context)
Describe transaction context. The transaction is looked up in ledger FILENAME at LOCATION. The LOCATION argument is either a line number or a filename:lineno tuple to indicate a location in a ledger included from the main input file.
3,156
from typing import List, Tuple import collections import logging import os import re import sys import click from beancount import loader from beancount.core import account from beancount.core import account_types from beancount.core import compare from beancount.core import convert from beancount.core import data from beancount.core.display_context import Align from beancount.core import getters from beancount.core import inventory from beancount.core import prices from beancount.core import realization from beancount.parser.context import render_file_context from beancount.parser import lexer from beancount.parser import options from beancount.parser import parser from beancount.parser import printer from beancount.parser.version import VERSION from beancount.scripts.directories import validate_directories def render_mini_balances(entries, options_map, conversion=None, price_map=None): """Render a treeified list of the balances for the given transactions. Args: entries: A list of selected transactions to render. options_map: The parsed options. conversion: Conversion method string, None, 'value' or 'cost'. price_map: A price map from the original entries. If this isn't provided, the inventories are rendered directly. If it is, their contents are converted to market value. """ # Render linked entries (in date order) as errors (for Emacs). errors = [RenderError(entry.meta, '', entry) for entry in entries] printer.print_errors(errors) # Print out balances. real_root = realization.realize(entries) dformat = options_map['dcontext'].build(alignment=Align.DOT, reserved=2) # TODO(blais): I always want to be able to convert at cost. We need # arguments capability. # # TODO(blais): Ideally this conversion inserts a new transactions to # 'Unrealized' to account for the difference between cost and market value. # Insert one and update the realization. Add an update() method to the # realization, given a transaction. acctypes = options.get_account_types(options_map) if conversion == 'value': assert price_map is not None # Warning: Mutate the inventories in-place, converting them to market # value. balance_diff = inventory.Inventory() for real_account in realization.iter_children(real_root): balance_cost = real_account.balance.reduce(convert.get_cost) balance_value = real_account.balance.reduce(convert.get_value, price_map) real_account.balance = balance_value balance_diff.add_inventory(balance_cost) balance_diff.add_inventory(-balance_value) if not balance_diff.is_empty(): account_unrealized = account.join(acctypes.income, options_map["account_unrealized_gains"]) unrealized = realization.get_or_create(real_root, account_unrealized) unrealized.balance.add_inventory(balance_diff) elif conversion == 'cost': for real_account in realization.iter_children(real_root): real_account.balance = real_account.balance.reduce(convert.get_cost) realization.dump_balances(real_root, dformat, file=sys.stdout) # Print out net income change. net_income = inventory.Inventory() for real_node in realization.iter_children(real_root): if account_types.is_income_statement_account(real_node.account, acctypes): net_income.add_inventory(real_node.balance) print() print('Net Income: {}'.format(-net_income)) def find_linked_entries(entries, links, follow_links: bool): """Find all linked entries. Note that there is an option here: You can either just look at the links on the closest entry, or you can include the links of the linked transactions as well. Whichever one you want depends on how you use your links. Best would be to query the user (in Emacs) when there are many links present. """ linked_entries = [] if not follow_links: linked_entries = [entry for entry in entries if (isinstance(entry, data.Transaction) and entry.links and entry.links & links)] else: links = set(links) linked_entries = [] while True: num_linked = len(linked_entries) linked_entries = [entry for entry in entries if (isinstance(entry, data.Transaction) and entry.links and entry.links & links)] if len(linked_entries) == num_linked: break for entry in linked_entries: if entry.links: links.update(entry.links) return linked_entries def find_tagged_entries(entries, tag): """Find all entries with the given tag.""" return [entry for entry in entries if (isinstance(entry, data.Transaction) and entry.tags and tag in entry.tags)] The provided code snippet includes necessary dependencies for implementing the `linked` function. Write a Python function `def linked(filename, location_spec)` to solve the following problem: List related transactions. List all transaction in ledger FILENAME linked to LINK or tagged with TAG, or linked to the one at LOCATION, or linked to any transaction in REGION. The LINK and TAG arguments must include the leading ^ or # charaters. The LOCATION argument is either a line number or a filename:lineno tuple to indicate a location in a ledger file included from the main input file. The REGION argument is either a stard:end line numbers tuple or a filename:start:end triplet to indicate a region in a ledger file included from the main input file. Here is the function: def linked(filename, location_spec): """List related transactions. List all transaction in ledger FILENAME linked to LINK or tagged with TAG, or linked to the one at LOCATION, or linked to any transaction in REGION. The LINK and TAG arguments must include the leading ^ or # charaters. The LOCATION argument is either a line number or a filename:lineno tuple to indicate a location in a ledger file included from the main input file. The REGION argument is either a stard:end line numbers tuple or a filename:start:end triplet to indicate a region in a ledger file included from the main input file. """ # Load the input file. entries, errors, options_map = loader.load_file(filename) # Link name. if re.match(r"\^(.*)$", location_spec): search_filename = options_map['filename'] links = {location_spec[1:]} linked_entries = find_linked_entries(entries, links, False) # Tag name. elif re.match(r"#(.*)$", location_spec): search_filename = options_map['filename'] tag = location_spec[1:] linked_entries = find_tagged_entries(entries, tag) else: # Parse the argument as a line number or a # "<filename>:<lineno>:<lineno>" spec to pull context from, with # optional filename and optional last line number. # # If a filename is not provided, the ledger's top-level filename is used # (this is the common case). An explicit filename is used to get context # in included files. # # If a single line number is provided the closest transaction is # selected. If an internal of line numbers is provided, the list of all # transactions whose first line is inside the interval are selected. match = re.match(r"(\d+)(?::(\d+))?$", location_spec) if match: included_filename = None first_line, last_line = match.groups() else: match = re.match(r"(.+?):(\d+)(?::(\d+))?$", location_spec) if match: included_filename, first_line, last_line = match.groups() else: raise SystemExit("Invalid line number or link format for location.") search_filename = (os.path.abspath(included_filename) if included_filename else options_map['filename']) lineno = int(first_line) if last_line is None: # Find the closest entry. closest_entry = data.find_closest(entries, search_filename, lineno) selected_entries = [closest_entry] # Find its links. if closest_entry is None: raise SystemExit("No entry could be found before {}:{}".format( search_filename, lineno)) links = (closest_entry.links if isinstance(closest_entry, data.Transaction) else data.EMPTY_SET) else: # Find all the entries in the interval, following all links. last_lineno = int(last_line) links = set() selected_entries = [] for entry in data.filter_txns(entries): if (entry.meta['filename'] == search_filename and lineno <= entry.meta['lineno'] <= last_lineno): links.update(entry.links) selected_entries.append(entry) # Get the linked entries, or just the closest one, if no links. linked_entries = (find_linked_entries(entries, links, True) if links else selected_entries) render_mini_balances(linked_entries, options_map, None)
List related transactions. List all transaction in ledger FILENAME linked to LINK or tagged with TAG, or linked to the one at LOCATION, or linked to any transaction in REGION. The LINK and TAG arguments must include the leading ^ or # charaters. The LOCATION argument is either a line number or a filename:lineno tuple to indicate a location in a ledger file included from the main input file. The REGION argument is either a stard:end line numbers tuple or a filename:start:end triplet to indicate a region in a ledger file included from the main input file.
3,157
from typing import List, Tuple import collections import logging import os import re import sys import click from beancount import loader from beancount.core import account from beancount.core import account_types from beancount.core import compare from beancount.core import convert from beancount.core import data from beancount.core.display_context import Align from beancount.core import getters from beancount.core import inventory from beancount.core import prices from beancount.core import realization from beancount.parser.context import render_file_context from beancount.parser import lexer from beancount.parser import options from beancount.parser import parser from beancount.parser import printer from beancount.parser.version import VERSION from beancount.scripts.directories import validate_directories def resolve_region_to_entries( entries: List[data.Entries], filename: str, region: Tuple[str, int, int] ) -> List[data.Entries]: """Resolve a filename and region to a list of entries.""" search_filename, first_lineno, last_lineno = region if search_filename is None: search_filename = filename # Find all the entries in the region. (To be clear, this isn't like the # 'linked' command, none of the links are followed.) region_entries = [ entry for entry in data.filter_txns(entries) if (entry.meta['filename'] == search_filename and first_lineno <= entry.meta['lineno'] <= last_lineno)] return region_entries help='Convert balances output to market value or cost.') def render_mini_balances(entries, options_map, conversion=None, price_map=None): """Render a treeified list of the balances for the given transactions. Args: entries: A list of selected transactions to render. options_map: The parsed options. conversion: Conversion method string, None, 'value' or 'cost'. price_map: A price map from the original entries. If this isn't provided, the inventories are rendered directly. If it is, their contents are converted to market value. """ # Render linked entries (in date order) as errors (for Emacs). errors = [RenderError(entry.meta, '', entry) for entry in entries] printer.print_errors(errors) # Print out balances. real_root = realization.realize(entries) dformat = options_map['dcontext'].build(alignment=Align.DOT, reserved=2) # TODO(blais): I always want to be able to convert at cost. We need # arguments capability. # # TODO(blais): Ideally this conversion inserts a new transactions to # 'Unrealized' to account for the difference between cost and market value. # Insert one and update the realization. Add an update() method to the # realization, given a transaction. acctypes = options.get_account_types(options_map) if conversion == 'value': assert price_map is not None # Warning: Mutate the inventories in-place, converting them to market # value. balance_diff = inventory.Inventory() for real_account in realization.iter_children(real_root): balance_cost = real_account.balance.reduce(convert.get_cost) balance_value = real_account.balance.reduce(convert.get_value, price_map) real_account.balance = balance_value balance_diff.add_inventory(balance_cost) balance_diff.add_inventory(-balance_value) if not balance_diff.is_empty(): account_unrealized = account.join(acctypes.income, options_map["account_unrealized_gains"]) unrealized = realization.get_or_create(real_root, account_unrealized) unrealized.balance.add_inventory(balance_diff) elif conversion == 'cost': for real_account in realization.iter_children(real_root): real_account.balance = real_account.balance.reduce(convert.get_cost) realization.dump_balances(real_root, dformat, file=sys.stdout) # Print out net income change. net_income = inventory.Inventory() for real_node in realization.iter_children(real_root): if account_types.is_income_statement_account(real_node.account, acctypes): net_income.add_inventory(real_node.balance) print() print('Net Income: {}'.format(-net_income)) The provided code snippet includes necessary dependencies for implementing the `region` function. Write a Python function `def region(filename, region, conversion)` to solve the following problem: Print out a list of transactions within REGION and compute balances. The REGION argument is either a stard:end line numbers tuple or a filename:start:end triplet to indicate a region in a ledger file included from the main input file. Here is the function: def region(filename, region, conversion): """Print out a list of transactions within REGION and compute balances. The REGION argument is either a stard:end line numbers tuple or a filename:start:end triplet to indicate a region in a ledger file included from the main input file. """ entries, errors, options_map = loader.load_file(filename) region_entries = resolve_region_to_entries(entries, filename, region) price_map = prices.build_price_map(entries) if conversion == 'value' else None render_mini_balances(region_entries, options_map, conversion, price_map)
Print out a list of transactions within REGION and compute balances. The REGION argument is either a stard:end line numbers tuple or a filename:start:end triplet to indicate a region in a ledger file included from the main input file.
3,158
from typing import List, Tuple import collections import logging import os import re import sys import click from beancount import loader from beancount.core import account from beancount.core import account_types from beancount.core import compare from beancount.core import convert from beancount.core import data from beancount.core.display_context import Align from beancount.core import getters from beancount.core import inventory from beancount.core import prices from beancount.core import realization from beancount.parser.context import render_file_context from beancount.parser import lexer from beancount.parser import options from beancount.parser import parser from beancount.parser import printer from beancount.parser.version import VERSION from beancount.scripts.directories import validate_directories The provided code snippet includes necessary dependencies for implementing the `missing_open` function. Write a Python function `def missing_open(filename)` to solve the following problem: Print Open directives missing in FILENAME. This can be useful during demos in order to quickly generate all the required Open directives without having to type them manually. Here is the function: def missing_open(filename): """Print Open directives missing in FILENAME. This can be useful during demos in order to quickly generate all the required Open directives without having to type them manually. """ entries, errors, options_map = loader.load_file(filename) # Get accounts usage and open directives. first_use_map, _ = getters.get_accounts_use_map(entries) open_close_map = getters.get_account_open_close(entries) new_entries = [] for account, first_use_date in first_use_map.items(): if account not in open_close_map: new_entries.append( data.Open(data.new_metadata(filename, 0), first_use_date, account, None, None)) dcontext = options_map['dcontext'] printer.print_entries(data.sorted(new_entries), dcontext)
Print Open directives missing in FILENAME. This can be useful during demos in order to quickly generate all the required Open directives without having to type them manually.
3,159
from typing import List, Tuple import collections import logging import os import re import sys import click from beancount import loader from beancount.core import account from beancount.core import account_types from beancount.core import compare from beancount.core import convert from beancount.core import data from beancount.core.display_context import Align from beancount.core import getters from beancount.core import inventory from beancount.core import prices from beancount.core import realization from beancount.parser.context import render_file_context from beancount.parser import lexer from beancount.parser import options from beancount.parser import parser from beancount.parser import printer from beancount.parser.version import VERSION from beancount.scripts.directories import validate_directories The provided code snippet includes necessary dependencies for implementing the `display_context` function. Write a Python function `def display_context(filename)` to solve the following problem: Print the precision inferred from the parsed numbers in the input file. Here is the function: def display_context(filename): """Print the precision inferred from the parsed numbers in the input file.""" entries, errors, options_map = loader.load_file(filename) dcontext = options_map['dcontext'] sys.stdout.write(str(dcontext))
Print the precision inferred from the parsed numbers in the input file.
3,160
import sys import types def check_dependencies(): """Check the runtime dependencies and report their version numbers. Returns: A list of pairs of (package-name, version-number, sufficient) whereby if a package has not been installed, its 'version-number' will be set to None. Otherwise, it will be a string with the version number in it. 'sufficient' will be True if the version if sufficient for this installation of Beancount. """ return [ # Check for a complete installation of Python itself. check_python(), check_cdecimal(), # Modules we really do need installed. check_import('dateutil'), check_import('ply', module_name='ply.yacc', min_version='3.4'), # Optionally required to upload data to Google Drive. # TODO(blais, 2023-11-18): oauth2client is deprecated. check_import('googleapiclient'), check_import('oauth2client'), check_import('httplib2'), # Optionally required to support various price source fetchers. check_import('requests', min_version='2.0'), # Optionally required to support imports (identify, extract, file) code. check_python_magic(), ] The provided code snippet includes necessary dependencies for implementing the `list_dependencies` function. Write a Python function `def list_dependencies(file=sys.stderr)` to solve the following problem: Check the dependencies and produce a listing on the given file. Args: file: A file object to write the output to. Here is the function: def list_dependencies(file=sys.stderr): """Check the dependencies and produce a listing on the given file. Args: file: A file object to write the output to. """ print("Dependencies:") for package, version, sufficient in check_dependencies(): print(" {:16}: {} {}".format( package, version or 'NOT INSTALLED', "(INSUFFICIENT)" if version and not sufficient else ""), file=file)
Check the dependencies and produce a listing on the given file. Args: file: A file object to write the output to.
3,161
import collections import datetime import functools from beancount.core import account_types from beancount.core import amount from beancount.core import data from beancount.core.number import ZERO from beancount.parser import options ONE_DAY = datetime.timedelta(days=1) ZERO = Decimal() The provided code snippet includes necessary dependencies for implementing the `check_drained` function. Write a Python function `def check_drained(entries, options_map)` to solve the following problem: Check that closed accounts are empty. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found. Here is the function: def check_drained(entries, options_map): """Check that closed accounts are empty. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found. """ acctypes = options.get_account_types(options_map) is_covered = functools.partial( account_types.is_balance_sheet_account, account_types=acctypes ) new_entries = [] currencies = collections.defaultdict(set) balances = collections.defaultdict(set) for entry in entries: if isinstance(entry, data.Transaction): # Accumulate all the currencies seen in each account over time. for posting in entry.postings: if is_covered(posting.account): currencies[posting.account].add(posting.units.currency) elif isinstance(entry, data.Open): # Accumulate all the currencies declared in the account opening. if is_covered(entry.account) and entry.currencies: for currency in entry.currencies: currencies[entry.account].add(currency) elif isinstance(entry, data.Balance): # Ignore balances where directives are present. if is_covered(entry.account): balances[entry.account].add((entry.date, entry.amount.currency)) if isinstance(entry, data.Close): if is_covered(entry.account): for currency in currencies[entry.account]: # Skip balance insertion due to the presence of an explicit one. if (entry.date, currency) in balances[entry.account]: continue # Insert a balance directive. balance_entry = data.Balance( # Note: We use the close directive's meta so that # balance errors direct the user to the corresponding # close directive. entry.meta, entry.date + ONE_DAY, entry.account, amount.Amount(ZERO, currency), None, None, ) new_entries.append(balance_entry) new_entries.append(entry) return new_entries, []
Check that closed accounts are empty. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found.
3,162
import collections import re from beancount.core import data OneCommodityError = collections.namedtuple('OneCommodityError', 'source message entry') The provided code snippet includes necessary dependencies for implementing the `validate_one_commodity` function. Write a Python function `def validate_one_commodity(entries, unused_options_map, config=None)` to solve the following problem: Check that each account has units in only a single commodity. This is an extra constraint that you may want to apply optionally, despite Beancount's ability to support inventories and aggregations with more than one commodity. I believe this also matches GnuCash's model, where each account has a single commodity attached to it. Args: entries: A list of directives. unused_options_map: An options map. config: The plugin configuration string, a regular expression to match against the subset of accounts to check. Returns: A list of new errors, if any were found. Here is the function: def validate_one_commodity(entries, unused_options_map, config=None): """Check that each account has units in only a single commodity. This is an extra constraint that you may want to apply optionally, despite Beancount's ability to support inventories and aggregations with more than one commodity. I believe this also matches GnuCash's model, where each account has a single commodity attached to it. Args: entries: A list of directives. unused_options_map: An options map. config: The plugin configuration string, a regular expression to match against the subset of accounts to check. Returns: A list of new errors, if any were found. """ accounts_re = re.compile(config) if config else None # Mappings of account name to lists of currencies for each units and cost. units_map = collections.defaultdict(set) cost_map = collections.defaultdict(set) # Mappings to use just for getting a relevant source. units_source_map = {} cost_source_map = {} # Gather the set of accounts to skip from the Open directives. skip_accounts = set() for entry in entries: if not isinstance(entry, data.Open): continue if (not entry.meta.get("onecommodity", True) or (accounts_re and not accounts_re.match(entry.account)) or (entry.currencies and len(entry.currencies) > 1)): skip_accounts.add(entry.account) # Accumulate all the commodities used. for entry in entries: if isinstance(entry, data.Transaction): for posting in entry.postings: if posting.account in skip_accounts: continue units = posting.units units_map[posting.account].add(units.currency) if len(units_map[posting.account]) > 1: units_source_map[posting.account] = entry cost = posting.cost if cost: cost_map[posting.account].add(cost.currency) if len(cost_map[posting.account]) > 1: cost_source_map[posting.account] = entry elif isinstance(entry, data.Balance): if entry.account in skip_accounts: continue units_map[entry.account].add(entry.amount.currency) if len(units_map[entry.account]) > 1: units_source_map[entry.account] = entry elif isinstance(entry, data.Open): if entry.currencies and len(entry.currencies) > 1: skip_accounts.add(entry.account) # Check units. errors = [] for account, currencies in units_map.items(): if account in skip_accounts: continue if len(currencies) > 1: errors.append(OneCommodityError( units_source_map[account].meta, "More than one currency in account '{}': {}".format( account, ','.join(currencies)), None)) # Check costs. for account, currencies in cost_map.items(): if account in skip_accounts: continue if len(currencies) > 1: errors.append(OneCommodityError( cost_source_map[account].meta, "More than one cost currency in account '{}': {}".format( account, ','.join(currencies)), None)) return entries, errors
Check that each account has units in only a single commodity. This is an extra constraint that you may want to apply optionally, despite Beancount's ability to support inventories and aggregations with more than one commodity. I believe this also matches GnuCash's model, where each account has a single commodity attached to it. Args: entries: A list of directives. unused_options_map: An options map. config: The plugin configuration string, a regular expression to match against the subset of accounts to check. Returns: A list of new errors, if any were found.
3,163
import collections import re from beancount.core import data from beancount.core.amount import CURRENCY_RE ConfigError = collections.namedtuple('ConfigError', 'source message entry') CheckCommodityError = collections.namedtuple('CheckCommodityError', 'source message entry') ANONYMOUS = {PRICE_CONTEXT, METADATA_CONTEXT} def get_commodity_map_ex(entries, metadata=False): """Find and extract commodities in the stream of directives.""" # Find commodity names in metadata. # # TODO(dnicolodi) Unfortunately detecting commodities in metadata # values may result in false positives: common used string are # matched by the regular expression. Revisit this when commodities # will be represented with their own type. ignore = set(['filename', 'lineno', '__automatic__']) regexp = re.compile(CURRENCY_RE) def currencies_in_meta(entry): if entry.meta is not None: for key, value in entry.meta.items(): if isinstance(value, str) and key not in ignore: if regexp.fullmatch(value): yield value commodities_map = {} occurrences = set() for entry in entries: if isinstance(entry, data.Commodity): commodities_map[entry.currency] = entry elif isinstance(entry, data.Open): if entry.currencies: for currency in entry.currencies: occurrences.add((entry.account, currency)) elif isinstance(entry, data.Transaction): for posting in entry.postings: # Main currency. units = posting.units occurrences.add((posting.account, units.currency)) # Currency in cost. cost = posting.cost if cost: occurrences.add((posting.account, cost.currency)) # Currency in price. price = posting.price if price: occurrences.add((posting.account, price.currency)) # Currency in posting metadata. if metadata: for currency in currencies_in_meta(posting): occurrences.add((posting.account, currency)) elif isinstance(entry, data.Balance): occurrences.add((entry.account, entry.amount.currency)) elif isinstance(entry, data.Price): occurrences.add((PRICE_CONTEXT, entry.currency)) occurrences.add((PRICE_CONTEXT, entry.amount.currency)) # Entry metadata. if metadata: for currency in currencies_in_meta(entry): occurrences.add((METADATA_CONTEXT, currency)) return occurrences, commodities_map The provided code snippet includes necessary dependencies for implementing the `validate_commodity_directives` function. Write a Python function `def validate_commodity_directives(entries, options_map, config_str=None)` to solve the following problem: Find all commodities used and ensure they have a corresponding Commodity directive. Args: entries: A list of directives. options_map: An options map. config_str: The configuration as a string version of a float. Returns: A list of new errors, if any were found. Here is the function: def validate_commodity_directives(entries, options_map, config_str=None): """Find all commodities used and ensure they have a corresponding Commodity directive. Args: entries: A list of directives. options_map: An options map. config_str: The configuration as a string version of a float. Returns: A list of new errors, if any were found. """ errors = [] # pylint: disable=eval-used if config_str: config_obj = eval(config_str, {}, {}) if not isinstance(config_obj, dict): errors.append(ConfigError( data.new_metadata('<commodity_attr>', 0), "Invalid configuration for check_commodity plugin; skipping.", None)) return entries, errors else: config_obj = {} # Compile the regular expressions, producing an error if invalid. ignore_map = {} for key, value in config_obj.items(): kv = [] for pattern in key, value: try: kv.append(re.compile(pattern).match) except re.error: meta = data.new_metadata('<check_commodity>', 0) errors.append( CheckCommodityError( meta, "Invalid regexp: '{}' for {}".format(value, key), None)) if len(kv) == 2: ignore_map[kv[0]] = kv[1] # Get all the occurrences of commodities and a mapping of the directives. # # TODO(blais): Establish a distinction at the parser level for commodities # and strings, so that we can turn detection of them in metadata. occurrences, commodity_map = get_commodity_map_ex(entries, metadata=False) # Process all currencies with context. issued = set() ignored = set() anonymous = set() for context, currency in sorted(occurrences): if context in ANONYMOUS: anonymous.add((context, currency)) continue commodity_entry = commodity_map.get(currency, None) # Skip if the commodity was declared, or if an error for that commodity # has already been issued. if commodity_entry is not None or currency in issued: continue # If any of the ignore patterns matches, ignore and record ignored. if any((context_re(context) and currency_re(currency)) for context_re, currency_re in ignore_map.items()): ignored.add(currency) continue # Issue error. meta = data.new_metadata('<check_commodity>', 0) errors.append( CheckCommodityError( meta, "Missing Commodity directive for '{}' in '{}'".format( currency, context), None)) # Process it only once. issued.add(currency) # Process all currencies out of context, automatically ignoring those which # have already been issued with account context.. for context, currency in sorted(anonymous): commodity_entry = commodity_map.get(currency, None) # Skip if (a) the commodity was declared, any of the ignore patterns # matches, or an error for that commodity has already been issued. if (commodity_entry is not None or currency in issued or currency in ignored): continue # Issue error. meta = data.new_metadata('<check_commodity>', 0) errors.append( CheckCommodityError( meta, "Missing Commodity directive for '{}' in '{}'".format( currency, context), None)) return entries, errors
Find all commodities used and ensure they have a corresponding Commodity directive. Args: entries: A list of directives. options_map: An options map. config_str: The configuration as a string version of a float. Returns: A list of new errors, if any were found.
3,164
import datetime from beancount.core.number import ZERO from beancount.core import data from beancount.core import amount ZERO = Decimal() The provided code snippet includes necessary dependencies for implementing the `check_closing` function. Write a Python function `def check_closing(entries, options_map)` to solve the following problem: Expand 'closing' metadata to a zero balance check. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found. Here is the function: def check_closing(entries, options_map): """Expand 'closing' metadata to a zero balance check. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found. """ new_entries = [] for entry in entries: if isinstance(entry, data.Transaction): for i, posting in enumerate(entry.postings): if posting.meta and posting.meta.get('closing', False): # Remove the metadata. meta = posting.meta.copy() del meta['closing'] posting = posting._replace(meta=meta) entry.postings[i] = posting # Insert a balance. date = entry.date + datetime.timedelta(days=1) balance = data.Balance(data.new_metadata("<check_closing>", 0), date, posting.account, amount.Amount(ZERO, posting.units.currency), None, None) new_entries.append(balance) new_entries.append(entry) return new_entries, []
Expand 'closing' metadata to a zero balance check. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found.
3,165
import collections from beancount.core import getters from beancount.core import data from beancount.core import realization LeafOnlyError = collections.namedtuple('LeafOnlyError', 'source message entry') The provided code snippet includes necessary dependencies for implementing the `validate_leaf_only` function. Write a Python function `def validate_leaf_only(entries, unused_options_map)` to solve the following problem: Check for non-leaf accounts that have postings on them. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found. Here is the function: def validate_leaf_only(entries, unused_options_map): """Check for non-leaf accounts that have postings on them. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found. """ real_root = realization.realize(entries, compute_balance=False) default_meta = data.new_metadata('<leafonly>', 0) open_close_map = None # Lazily computed. errors = [] for real_account in realization.iter_children(real_root): if len(real_account) > 0 and real_account.txn_postings: if open_close_map is None: open_close_map = getters.get_account_open_close(entries) try: open_entry = open_close_map[real_account.account][0] except KeyError: open_entry = None errors.append(LeafOnlyError( open_entry.meta if open_entry else default_meta, "Non-leaf account '{}' has postings on it".format(real_account.account), open_entry)) return entries, errors
Check for non-leaf accounts that have postings on them. Args: entries: A list of directives. unused_options_map: An options map. Returns: A list of new errors, if any were found.