### Install beanprice using pip Source: https://github.com/beancount/beanprice/blob/master/README.md Install the beanprice script by cloning the repository and installing it via pip. This command fetches the latest version directly from the GitHub repository. ```shell pip install git+https://github.com/beancount/beanprice.git ``` -------------------------------- ### Basic Source String Format Source: https://context7.com/beancount/beanprice/llms.txt Specifies a price source using the format QUOTE_CURRENCY:module/TICKER. This example fetches the AAPL price quoted in USD from Yahoo Finance. ```bash # Basic format: QUOTE_CURRENCY:module/TICKER # Fetches AAPL price quoted in USD from Yahoo Finance bean-price -e 'USD:yahoo/AAPL' ``` -------------------------------- ### Inverse Rate with '^' Prefix Source: https://context7.com/beancount/beanprice/llms.txt Fetch an inverse rate by prefixing the ticker with '^'. This example fetches the USD/CAD rate and inverts it to get the CAD/USD rate. ```bash # Inverse rate with ^ prefix (inverts the fetched rate) # Fetches USD/CAD rate and inverts to get CAD/USD bean-price -e 'USD:yahoo/^CADUSD=X' ``` -------------------------------- ### Multiple Sources with Fallback Source: https://context7.com/beancount/beanprice/llms.txt Define multiple price sources separated by commas. Beanprice will try them in order, using the first one that successfully returns a price. This example tries Yahoo Finance first, then Coinbase. ```bash # Multiple sources with fallback (comma-separated) # Tries Yahoo first, then Coinbase if Yahoo fails bean-price -e 'USD:yahoo/AAPL,coinbase/AAPL' ``` -------------------------------- ### Enable Verbose Output for Debugging Source: https://context7.com/beancount/beanprice/llms.txt Enable verbose logging to get detailed output for debugging purposes. This can help diagnose issues with price fetching or configuration. ```bash # Enable verbose output for debugging bean-price -v -e 'USD:yahoo/AAPL' ``` -------------------------------- ### Yahoo Finance Source Command Line Usage Source: https://context7.com/beancount/beanprice/llms.txt Examples of how to use the Yahoo Finance source directly from the command line using `bean-price`. Different tickers represent stocks, currencies, and indices. ```bash # bean-price -e 'USD:yahoo/AAPL' # US stock # bean-price -e 'USD:yahoo/MSFT' # Another stock # bean-price -e 'GBP:yahoo/GBPUSD=X' # Currency pair # bean-price -e 'USD:yahoo/^GSPC' # S&P 500 index # bean-price -e 'EUR:yahoo/VEA.DE' # European exchange ``` -------------------------------- ### Beancount commodity price metadata example Source: https://github.com/beancount/beanprice/blob/master/README.md Example of how to define commodity price metadata within a Beancount file. This specifies the commodity (AAPL) and the source for its price (USD:yahoo/AAPL). ```beancount 2000-01-01 commodity AAPL price: "USD:yahoo/AAPL" ``` -------------------------------- ### Fetch Cryptocurrency Prices with Coinbase Source Source: https://context7.com/beancount/beanprice/llms.txt Use the `Source` class or `fetch_quote` helper to get latest or historical cryptocurrency prices. Tickers are in 'BASE-QUOTE' format (e.g., 'BTC-USD'). ```python from beanprice.sources.coinbase import Source, fetch_quote # Using the Source class coinbase = Source() # Get latest Bitcoin price in USD result = coinbase.get_latest_price("BTC-USD") print(f"Bitcoin: {result.price} {result.quote_currency}") # Bitcoin: 42500.00 USD # Get latest Ethereum price in EUR result = coinbase.get_latest_price("ETH-EUR") print(f"Ethereum: {result.price} {result.quote_currency}") # Get historical price from datetime import datetime from dateutil.tz import tzutc historical_time = datetime(2024, 1, 1, 0, 0, tzinfo=tzutc()) result = coinbase.get_historical_price("BTC-USD", historical_time) print(f"BTC on 2024-01-01: {result.price}") # Using the fetch_quote helper directly from beanprice.sources.coinbase import fetch_quote spot_price = fetch_quote("ETH-GBP") print(f"ETH spot: {spot_price.price} GBP") historical = fetch_quote("ETH-GBP", historical_time) print(f"ETH historical: {historical.price} GBP") ``` -------------------------------- ### Get Price Jobs from Beancount File Source: https://context7.com/beancount/beanprice/llms.txt Use `get_price_jobs_at_date` to extract active price jobs for a specific date from Beancount entries. `get_price_jobs_up_to_date` retrieves all price jobs up to a given date, suitable for update operations. ```python from beancount import loader from beanprice.price import ( get_price_jobs_at_date, get_price_jobs_up_to_date, fetch_price, setup_cache, DatedPrice, PriceSource, ) import datetime # Load Beancount file entries, errors, options = loader.load_file("ledger.beancount") # Get price jobs for a specific date date = datetime.date(2024, 1, 15) jobs = get_price_jobs_at_date( entries, date=date, inactive=False, # Only active holdings undeclared_source=None, # Require price metadata ) print(f"Found {len(jobs)} price jobs for {date}") for job in jobs: print(f" {job.base}/{job.quote} from {[s.module.__name__ for s in job.sources]}") # Get all price jobs up to today (for --update mode) jobs = get_price_jobs_up_to_date( entries, date_last=datetime.date.today(), inactive=False, undeclared_source=None, update_rate="weekday", # daily, weekday, or weekly compress_days=1, ) ``` -------------------------------- ### Beancount Commodity with Single Price Source Source: https://context7.com/beancount/beanprice/llms.txt Define a commodity in your Beancount ledger with a single price source specified in the 'price' metadata field. This example uses Yahoo Finance for AAPL. ```beancount ; Stock with single price source 2000-01-01 commodity AAPL price: "USD:yahoo/AAPL" ``` -------------------------------- ### Initialize and Use Yahoo Finance Source Source: https://context7.com/beancount/beanprice/llms.txt Instantiate the `Source` from `beanprice.sources.yahoo` to fetch prices. It automatically handles authentication. Supports latest, historical, and daily price series. ```python from beanprice.sources.yahoo import Source # Initialize the Yahoo source (handles cookies/crumb automatically) yahoo = Source() # Get latest price for a stock result = yahoo.get_latest_price("AAPL") print(f"Price: {result.price}") # Decimal('185.92') print(f"Time: {result.time}") # 2024-01-15 16:00:00-05:00 print(f"Currency: {result.quote_currency}") # USD # Get historical price from datetime import datetime from dateutil.tz import tzutc historical_time = datetime(2024, 1, 1, 16, 0, tzinfo=tzutc()) result = yahoo.get_historical_price("AAPL", historical_time) print(f"Historical price: {result.price}") # Get daily price series from datetime import timedelta end_time = datetime.now(tzutc()) start_time = end_time - timedelta(days=30) series = yahoo.get_daily_prices("AAPL", start_time, end_time) for price_point in series: print(f"{price_point.time.date()}: {price_point.price}") ``` -------------------------------- ### Fetch and Process Prices with beanprice Source: https://context7.com/beancount/beanprice/llms.txt After obtaining price jobs, use `fetch_price` to retrieve the actual price data. `setup_cache` can be used to configure a cache for fetched prices to reduce API calls. Custom `DatedPrice` jobs can also be created and fetched. ```python from beancount import loader from beanprice.price import ( get_price_jobs_at_date, get_price_jobs_up_to_date, fetch_price, setup_cache, DatedPrice, PriceSource, ) import datetime # Load Beancount file entries, errors, options = loader.load_file("ledger.beancount") # Get price jobs for a specific date date = datetime.date(2024, 1, 15) jobs = get_price_jobs_at_date( entries, date=date, inactive=False, # Only active holdings undeclared_source=None, # Require price metadata ) print(f"Found {len(jobs)} price jobs for {date}") for job in jobs: print(f" {job.base}/{job.quote} from {[s.module.__name__ for s in job.sources]}") # Get all price jobs up to today (for --update mode) jobs = get_price_jobs_up_to_date( entries, date_last=datetime.date.today(), inactive=False, undeclared_source=None, update_rate="weekday", # daily, weekday, or weekly compress_days=1, ) # Fetch prices for the jobs setup_cache("/tmp/bean-price.cache", clear_cache=False) for job in jobs: price_entry = fetch_price(job, swap_inverted=False) if price_entry: print(f"{price_entry.date} price {price_entry.currency} {price_entry.amount}") # Create custom DatedPrice job from beanprice.price import import_source yahoo_module = import_source("yahoo") custom_job = DatedPrice( base="AAPL", quote="USD", date=None, # None means fetch latest sources=[PriceSource(yahoo_module, "AAPL", invert=False)] ) result = fetch_price(custom_job) ``` -------------------------------- ### Dry Run to See Potential Price Fetches Source: https://context7.com/beancount/beanprice/llms.txt Perform a dry run to preview which prices the tool would fetch without actually retrieving or applying them. This is useful for verification. ```bash # Dry run to see what prices would be fetched bean-price --dry-run ledger.beancount ``` -------------------------------- ### Configure and Use Price Caching System Source: https://context7.com/beancount/beanprice/llms.txt Beanprice offers an automatic disk-based caching system. Use `setup_cache` to configure location and expiration, and `fetch_cached_price` to retrieve data. `reset_cache` clears the cache. ```python from beanprice.price import setup_cache, reset_cache, fetch_cached_price from beanprice.sources.yahoo import Source import datetime # Setup cache with default location (temp directory) # Cache expires after 30 minutes for latest prices setup_cache("/tmp/bean-price.cache", clear_cache=False) # Fetch with caching enabled yahoo = Source() # First call fetches from network and caches result result = fetch_cached_price(yahoo, "AAPL", None) # None = latest price # Second call returns cached result (within 30 min) result = fetch_cached_price(yahoo, "AAPL", None) # Historical prices are cached with indefinite expiration past_date = datetime.date(2024, 1, 1) result = fetch_cached_price(yahoo, "AAPL", past_date) # Clear cache when done reset_cache() # Command line cache options # bean-price ledger.beancount # Uses default cache # bean-price --cache=/path/to/cache ledger.bc # Custom cache location # bean-price --no-cache -e 'USD:yahoo/AAPL' # Disable caching # bean-price --clear-cache ledger.beancount # Clear before fetching ``` -------------------------------- ### Fetch prices from a Beancount ledger file Source: https://github.com/beancount/beanprice/blob/master/README.md Fetch prices for commodities defined in your Beancount ledger file. Ensure that commodities have price metadata specifying the source, like 'USD:yahoo/AAPL'. ```shell bean-price ledger.beancount ``` -------------------------------- ### Fetch Prices from Beancount Ledger File Source: https://context7.com/beancount/beanprice/llms.txt This command analyzes your Beancount ledger file to determine and fetch the prices for commodities with price metadata. ```bash # Fetch prices from a Beancount ledger file (uses commodity metadata) bean-price /path/to/ledger.beancount ``` -------------------------------- ### Implement Custom Price Source Class Source: https://github.com/beancount/beanprice/blob/master/README.md Inherit from `beanprice.Source` and implement `get_latest_price` and `get_historical_price` methods to fetch price data. The `get_latest_price` method is mandatory. ```python from beanprice import source class Source(source.Source): def get_latest_price(self, ticker) -> source.SourcePrice | None: pass def get_historical_price(self, ticker, time): pass ``` -------------------------------- ### Custom Module Price Source Source: https://context7.com/beancount/beanprice/llms.txt Specify a custom price source module from your own Python package. Replace 'my_package.my_module' with your actual module path. ```bash # Custom module from your own package bean-price -e 'USD:my_package.my_module/TICKER' ``` -------------------------------- ### Using the SourcePrice Named Tuple Source: https://context7.com/beancount/beanprice/llms.txt The `SourcePrice` named tuple is the standard return type for price sources. Ensure all timestamps are timezone-aware. ```python from decimal import Decimal from datetime import datetime from dateutil.tz import tzutc from beanprice.source import SourcePrice # Creating a SourcePrice price = SourcePrice( price=Decimal("185.92"), time=datetime(2024, 1, 15, 16, 0, 0, tzinfo=tzutc()), quote_currency="USD" ) # Accessing fields print(f"Price: {price.price}") # Decimal('185.92') print(f"Time: {price.time}") # 2024-01-15 16:00:00+00:00 print(f"Currency: {price.quote_currency}") # USD # Time MUST be timezone-aware (required by beanprice) assert price.time.tzinfo is not None # SourcePrice is immutable, use _replace to create modified copy adjusted = price._replace(price=Decimal("186.00")) # None indicates failed fetch def get_price(ticker): try: # fetch logic... return SourcePrice(Decimal("100"), datetime.now(tzutc()), "USD") except Exception: return None # Indicates failure, try next source ``` -------------------------------- ### Retry Network Requests with `retrying_urlopen` Source: https://context7.com/beancount/beanprice/llms.txt Use `retrying_urlopen` from `beanprice.net_utils` to fetch URLs with automatic retries on timeouts. You can configure the timeout duration and the maximum number of retries. Permanent failures like 404 will return None. ```python from beanprice.net_utils import retrying_urlopen # Fetch URL with automatic retry on timeout url = "https://api.example.com/price/AAPL" response = retrying_urlopen(url, timeout=5, max_retry=5) if response is not None: content = response.read() print(f"Fetched {len(content)} bytes") else: print("Failed to fetch after retries") # Custom timeout and retry settings response = retrying_urlopen( "https://slow-api.example.com/data", timeout=10, # 10 second timeout per attempt max_retry=3 # Try up to 3 times ) # Returns None on permanent failure (404, etc.) response = retrying_urlopen("https://api.example.com/notfound") assert response is None # 404 returns None ``` -------------------------------- ### Multiple Quote Currencies Source: https://context7.com/beancount/beanprice/llms.txt Fetch prices for a commodity in multiple quote currencies simultaneously. Use space or semicolon separators. ```bash # Multiple quote currencies (space or semicolon separated) bean-price -e 'USD:yahoo/AAPL;EUR:yahoo/AAPL' ``` -------------------------------- ### Custom Price Source Implementation Skeleton Source: https://context7.com/beancount/beanprice/llms.txt This Python code skeleton shows how to create a custom price source module by implementing the `Source` class interface. You need to define `get_latest_price()` and optionally `get_historical_price()`. ```python from beancount.price import Source class MyCustomSource(Source): def get_latest_price(self, commodity_name, date_obj): # Implementation to fetch latest price pass def get_historical_price(self, commodity_name, date_obj): # Optional: Implementation to fetch historical price pass ``` -------------------------------- ### Fetch Currency Exchange Rates with ECB Source Source: https://context7.com/beancount/beanprice/llms.txt Utilize the `Source` class from `beanprice.sources.ecbrates` to retrieve latest or historical currency exchange rates. Rates are EUR-based, but cross-rates are supported. ```python from beanprice.sources.ecbrates import Source # Initialize ECB source ecb = Source() # Get latest EUR to USD rate result = ecb.get_latest_price("EUR-USD") print(f"EUR/USD: {result.price}") # EUR/USD: 1.0850 # Get latest USD to GBP (derived from EUR rates) result = ecb.get_latest_price("USD-GBP") print(f"USD/GBP: {result.price}") # Get historical exchange rate from datetime import datetime from dateutil.tz import tzutc historical_time = datetime(2024, 1, 1, 12, 0, tzinfo=tzutc()) result = ecb.get_historical_price("EUR-CHF", historical_time) print(f"EUR/CHF on 2024-01-01: {result.price}") # Cross-rate calculation (JPY to GBP via EUR) result = ecb.get_latest_price("JPY-GBP") print(f"JPY/GBP: {result.price}") ``` -------------------------------- ### Fetch Inverse Currency Rate Source: https://context7.com/beancount/beanprice/llms.txt Use this command to fetch an inverse currency rate, typically for currencies quoted in reverse (e.g., CAD/USD instead of USD/CAD). The '^' prefix indicates an inverse rate. ```bash # Fetch inverse rate (for currencies quoted in reverse) bean-price -e 'USD:yahoo/^CADUSD=X' ``` -------------------------------- ### Fetch Prices with Concurrent Workers Source: https://context7.com/beancount/beanprice/llms.txt Improve fetching speed by utilizing multiple concurrent workers. Adjust the number based on your system's capabilities and network. A value of 4 is shown here. ```bash # Fetch prices with multiple concurrent workers bean-price -w 4 ledger.beancount ``` -------------------------------- ### Implement Custom Price Source Source: https://context7.com/beancount/beanprice/llms.txt Extend the `beanprice.source.Source` class to create a custom price fetching mechanism. Ensure prices are timezone-aware. This is useful for integrating with private APIs or less common exchanges. ```python from decimal import Decimal from datetime import datetime from dateutil.tz import tz import requests from beanprice import source class Source(source.Source): """Custom price source implementation.""" def get_latest_price(self, ticker: str) -> source.SourcePrice | None: """Fetch the current latest price for the given ticker. Args: ticker: The symbol to fetch (e.g., "AAPL", "BTC-USD") Returns: SourcePrice with price, timezone-aware time, and quote currency, or None if the fetch failed. """ try: # Your API call here response = requests.get(f"https://api.example.com/price/{ticker}") response.raise_for_status() data = response.json() price = Decimal(str(data["price"])) # Time MUST be timezone-aware trade_time = datetime.now(tz.tzutc()) currency = data.get("currency", "USD") return source.SourcePrice(price, trade_time, currency) except Exception: return None def get_historical_price( self, ticker: str, time: datetime ) -> source.SourcePrice | None: """Fetch the price at a specific historical date. Args: ticker: The symbol to fetch time: A timezone-aware datetime for the target date Returns: SourcePrice or None if fetch failed. """ try: date_str = time.strftime("%Y-%m-%d") response = requests.get( f"https://api.example.com/history/{ticker}", params={"date": date_str} ) response.raise_for_status() data = response.json() price = Decimal(str(data["close"])) # Convert to timezone-aware datetime trade_time = datetime.fromisoformat(data["date"]).replace(tzinfo=tz.tzutc()) currency = data.get("currency", "USD") return source.SourcePrice(price, trade_time, currency) except Exception: return None def get_prices_series( self, ticker: str, time_begin: datetime, time_end: datetime ) -> list[source.SourcePrice] | None: """Fetch a series of historical daily prices (optional). Args: ticker: The symbol to fetch time_begin: Start of date range (timezone-aware) time_end: End of date range (timezone-aware) Returns: List of SourcePrice sorted by date, or None if fetch failed. """ try: response = requests.get( f"https://api.example.com/series/{ticker}", params={ "start": time_begin.strftime("%Y-%m-%d"), "end": time_end.strftime("%Y-%m-%d"), }, ) response.raise_for_status() data = response.json() return [ source.SourcePrice( Decimal(str(item["close"])), datetime.fromisoformat(item["date"]).replace(tzinfo=tz.tzutc()), data.get("currency", "USD") ) for item in data["prices"] ] except Exception: return None # Usage in Beancount file: # 2000-01-01 commodity XYZ # price: "USD:my_sources.custom_source/XYZ" ``` -------------------------------- ### Update Prices with Weekly Frequency Source: https://context7.com/beancount/beanprice/llms.txt Configure the price update process to use a weekly frequency instead of the default daily. This is useful for less volatile assets or to reduce API calls. ```bash # Update with weekly frequency instead of daily bean-price --update --update-rate=weekly ledger.beancount ``` -------------------------------- ### Currency Exchange Rate from ECB Source: https://context7.com/beancount/beanprice/llms.txt Retrieve currency exchange rates, such as EUR to CHF, using the European Central Bank (ECB) rates source. ```bash # Currency exchange rate from ECB bean-price -e 'CHF:ecbrates/EUR-CHF' ``` -------------------------------- ### Cryptocurrency Price from Coinbase Source: https://context7.com/beancount/beanprice/llms.txt Fetch the price of a cryptocurrency like Bitcoin (BTC-USD) quoted in USD from Coinbase. ```bash # Cryptocurrency from Coinbase bean-price -e 'USD:coinbase/BTC-USD' ``` -------------------------------- ### Update prices in a Beancount ledger file Source: https://github.com/beancount/beanprice/blob/master/README.md Update existing prices in your Beancount ledger file up to the present day. Use the --update flag along with the ledger file path. ```shell bean-price --update ledger.beancount ``` -------------------------------- ### Run Beancount Tests Source: https://github.com/beancount/beanprice/blob/master/README.md Execute the Beancount test suite using pytest. ```bash pytest beanprice ``` -------------------------------- ### Fetch Latest Stock Price with Yahoo Finance Source: https://context7.com/beancount/beanprice/llms.txt Use this command to fetch the latest price for a specific stock using Yahoo Finance. The output is formatted as a Beancount price directive. ```bash # Fetch latest price for a specific stock using Yahoo Finance bean-price -e 'USD:yahoo/AAPL' # Output: 2024-01-15 price AAPL 185.92 USD ``` -------------------------------- ### Fetch a single stock price Source: https://github.com/beancount/beanprice/blob/master/README.md Fetch the latest price for a specific stock symbol (e.g., AAPL) from a designated source (e.g., Yahoo) using the bean-price command-line tool. The '-e' flag specifies the commodity and source. ```shell bean-price -e 'USD:yahoo/AAPL' ``` -------------------------------- ### Beancount Commodity with Multiple Fallback Sources Source: https://context7.com/beancount/beanprice/llms.txt Configure a commodity with multiple fallback price sources. Beanprice will attempt to fetch the price from these sources in the order they are listed. ```beancount ; Stock with multiple fallback sources 2000-01-01 commodity GOOGL price: "USD:yahoo/GOOGL,alphavantage/GOOGL" ``` -------------------------------- ### Beancount Commodity with Multiple Quote Currencies Source: https://context7.com/beancount/beanprice/llms.txt Configure a commodity to fetch prices in multiple quote currencies, such as USD and EUR, using different sources if necessary. ```beancount ; Multiple quote currencies 2000-01-01 commodity VEA price: "USD:yahoo/VEA EUR:yahoo/VEA.DE" ``` -------------------------------- ### Fetch Historical Price for a Specific Date Source: https://context7.com/beancount/beanprice/llms.txt Retrieve a historical price for a given stock on a specific date. Ensure the date format is YYYY-MM-DD. ```bash # Fetch historical price for a specific date bean-price -e 'USD:yahoo/AAPL' --date=2024-01-01 ``` -------------------------------- ### Update All Prices from Last Known to Today Source: https://context7.com/beancount/beanprice/llms.txt This command updates all prices in your Beancount ledger from the last recorded price to the current date. It requires the ledger file path. ```bash # Update all prices from last known price to today bean-price --update ledger.beancount ``` -------------------------------- ### Manage Timezone Contexts for Testing Source: https://context7.com/beancount/beanprice/llms.txt The `intimezone` context manager allows you to temporarily set the timezone for code execution, which is useful for testing timezone-dependent logic. The timezone automatically resets after the context manager exits. ```python from beanprice.date_utils import parse_date_liberally, intimezone import datetime # Testing with timezone context manager with intimezone("America/New_York"): # Code here runs as if in New York timezone now = datetime.datetime.now() print(f"NY time: {now}") with intimezone("Europe/London"): # Code here runs as if in London timezone now = datetime.datetime.now() print(f"London time: {now}") # Timezone resets after context exits ``` -------------------------------- ### Beancount Commodity with Cryptocurrency Source Source: https://context7.com/beancount/beanprice/llms.txt Specify a cryptocurrency like BTC with its price source from Coinbase, quoted in USD. ```beancount ; Cryptocurrency with Coinbase source 2015-01-01 commodity BTC price: "USD:coinbase/BTC-USD" ``` -------------------------------- ### Lint Beancount Code Source: https://github.com/beancount/beanprice/blob/master/README.md Check Beancount code for style and potential errors using pylint. ```bash pylint beanprice ``` -------------------------------- ### Use Custom Price Source in Beancount Source: https://github.com/beancount/beanprice/blob/master/README.md Specify your custom price source in the commodity definition using the format `CURRENCY:package.module/CommodityName`. ```beancount 1900-01-01 commodity XYZ price: "AUD:my_package.my_module/XYZ" ``` -------------------------------- ### Beancount Commodity with Inverse Currency Rate Source: https://context7.com/beancount/beanprice/llms.txt Define a commodity for a currency like CAD, specifying an inverse rate source to fetch its value against USD. ```beancount ; Currency with inverse rate 2000-01-01 commodity CAD price: "USD:yahoo/^CADUSD=X" ``` -------------------------------- ### Fetch All Commodities Including Inactive Ones Source: https://context7.com/beancount/beanprice/llms.txt This option ensures that prices are fetched for all commodities, including those marked as inactive in your Beancount ledger. ```bash # Fetch all commodities including inactive ones bean-price --all ledger.beancount ``` -------------------------------- ### Swap Inverted Currencies Instead of Inverting Rate Source: https://context7.com/beancount/beanprice/llms.txt When fetching inverse rates, this option swaps the currencies instead of inverting the rate. This can be useful for specific exchange rate conventions. ```bash # Swap currencies instead of inverting rate bean-price --swap-inverted -e 'CAD:yahoo/^CADUSD=X' ``` -------------------------------- ### Beancount Commodity with European Central Bank Source Source: https://context7.com/beancount/beanprice/llms.txt Define a commodity like EUR and specify its price source from the European Central Bank (ECB) for USD exchange rates. ```beancount ; Currency from European Central Bank 2000-01-01 commodity EUR price: "USD:ecbrates/EUR-USD" ``` -------------------------------- ### Beancount Commodity with Chinese Fund Source Source: https://context7.com/beancount/beanprice/llms.txt Fetch prices for specific funds, like 'FUND001', using a dedicated source such as EastMoney for CNY-denominated assets. ```beancount ; Chinese fund from EastMoney 2020-01-01 commodity FUND001 price: "CNY:eastmoneyfund/001" ``` -------------------------------- ### Clear Cache Before Fetching Prices Source: https://context7.com/beancount/beanprice/llms.txt Manually clear the Beanprice cache before initiating a price fetch. This ensures that all data is re-downloaded. ```bash # Clear cache before fetching bean-price --clear-cache ledger.beancount ``` -------------------------------- ### Beancount Commodity with Empty Price Metadata Source: https://context7.com/beancount/beanprice/llms.txt Setting the 'price' metadata to an empty string disables price fetching for that commodity. This is useful for commodities where prices are not available or not needed. ```beancount ; Empty price metadata disables fetching 2000-01-01 commodity PRIVATE price: "" ``` -------------------------------- ### Type Check Beancount Code Source: https://github.com/beancount/beanprice/blob/master/README.md Perform static type checking on Beancount code using mypy. ```bash mypy beanprice ``` -------------------------------- ### Disable Caching for Fresh Data Source: https://context7.com/beancount/beanprice/llms.txt Force Beanprice to fetch fresh data by disabling its cache. This is useful when you suspect cached data is outdated or incorrect. ```bash # Disable caching for fresh data bean-price --no-cache -e 'USD:yahoo/AAPL' ``` -------------------------------- ### Parse Dates Liberally with beanprice Source: https://context7.com/beancount/beanprice/llms.txt Use `parse_date_liberally` to parse various date formats from user input. It can also accept custom `dateutil` kwargs for more specific parsing, such as setting `dayfirst` to True. ```python from beanprice.date_utils import parse_date_liberally, intimezone import datetime # Parse various date formats liberally date1 = parse_date_liberally("2024-01-15") date2 = parse_date_liberally("Jan 15, 2024") date3 = parse_date_liberally("15/01/2024") date4 = parse_date_liberally("January 15 2024") print(f"All parse to: {date1}") # datetime.date(2024, 1, 15) # Parse with custom dateutil kwargs date = parse_date_liberally("01/02/2024", {"dayfirst": True}) print(f"Day first: {date}") # 2024-02-01 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.