### Install Prek for Linting and Testing Source: https://github.com/klaasnicolaas/python-energyzero/blob/main/README.md Sets up the prek framework for linting and testing. This command installs the necessary hooks and configurations for commit checks. ```bash poetry run prek install ``` -------------------------------- ### Install EnergyZero package Source: https://github.com/klaasnicolaas/python-energyzero/blob/main/README.md Use pip to install the library in your Python environment. ```bash pip install energyzero ``` -------------------------------- ### Install Project Dependencies with Poetry Source: https://github.com/klaasnicolaas/python-energyzero/blob/main/README.md Installs all project packages, including development requirements, using Poetry. Poetry manages virtual environments and dependencies. ```bash poetry install ``` -------------------------------- ### Get Gas Prices (REST) Source: https://context7.com/klaasnicolaas/python-energyzero/llms.txt Retrieve daily gas prices using the REST backend. Gas prices are fixed for 24 hours starting at 06:00 each morning. Prices are returned in EUR/m³. ```python import asyncio from datetime import UTC, datetime from energyzero import EnergyZero, PriceType async def main() -> None: async with EnergyZero() as client: today = datetime.now(UTC).astimezone().date() # All-in gas price (including VAT and surcharges) gas = await client.get_gas_prices( start_date=today, price_type=PriceType.ALL_IN, ) # Market gas price (excluding VAT and surcharges) gas_market = await client.get_gas_prices( start_date=today, price_type=PriceType.MARKET, ) print(f"Current gas price: €{gas.current_price:.4f}/m³") print(f"Average gas price: €{gas.average_price:.4f}/m³") print(f"Market price (excl VAT): €{gas_market.current_price:.4f}/m³") min_price, max_price = gas.extreme_prices print(f"Min: €{min_price:.4f}, Max: €{max_price:.4f}") asyncio.run(main()) ``` -------------------------------- ### Get Electricity Prices (GraphQL) Source: https://context7.com/klaasnicolaas/python-energyzero/llms.txt Retrieve electricity prices for date ranges using the GraphQL backend. Always returns hourly intervals. Requires both start_date and end_date. ```python import asyncio from datetime import datetime, timedelta import pytz from energyzero import EnergyZero, APIBackend, PriceType async def main() -> None: async with EnergyZero(backend=APIBackend.GRAPHQL) as client: local_tz = pytz.timezone("Europe/Amsterdam") today = datetime.now(local_tz).date() tomorrow = today + timedelta(days=1) # Single day query (end_date is required for GraphQL) energy_today = await client.get_electricity_prices( start_date=today, end_date=today, price_type=PriceType.ALL_IN, ) # Multi-day range query energy_range = await client.get_electricity_prices( start_date=today, end_date=tomorrow, price_type=PriceType.MARKET_WITH_VAT, ) print(f"Today's average: €{energy_today.average_price:.4f}/kWh") print(f"Two-day average: €{energy_range.average_price:.4f}/kWh") print(f"Lowest time (local): {energy_today.lowest_price_time_range.astimezone(local_tz)}") # Access raw price blocks with detailed cost breakdown for block in energy_today.raw_blocks[:3]: print(f"Time: {block.time_range}") print(f" Energy excl VAT: €{block.energy_price_excl:.4f}") print(f" Energy incl VAT: €{block.energy_price_incl:.4f}") print(f" Total incl: €{block.total_incl:.4f}") asyncio.run(main()) ``` -------------------------------- ### Get Gas Prices (GraphQL) Source: https://context7.com/klaasnicolaas/python-energyzero/llms.txt Retrieve gas prices for date ranges using the GraphQL backend. Supports multi-day queries with detailed cost breakdowns. ```python import asyncio from datetime import datetime, timedelta import pytz from energyzero import EnergyZero, APIBackend, PriceType async def main() -> None: async with EnergyZero(backend=APIBackend.GRAPHQL) as client: local_tz = pytz.timezone("Europe/Amsterdam") today = datetime.now(local_tz).date() # Single day gas prices gas_today = await client.get_gas_prices( start_date=today, end_date=today, price_type=PriceType.ALL_IN, ) # Multi-day gas price query next_week = today + timedelta(days=7) gas_week = await client.get_gas_prices( start_date=today, end_date=next_week, price_type=PriceType.ALL_IN_EXCL_VAT, ) print(f"Today's gas price: €{gas_today.current_price:.4f}/m³") print(f"Weekly average: €{gas_week.average_price:.4f}/m³") print(f"Lowest day: {gas_week.lowest_price_time_range.astimezone(local_tz)}") asyncio.run(main()) ``` -------------------------------- ### Fetch energy prices using the REST client Source: https://github.com/klaasnicolaas/python-energyzero/blob/main/README.md Demonstrates how to initialize the EnergyZero client and retrieve electricity and gas prices for specific dates. ```python import asyncio from datetime import UTC, datetime, timedelta from energyzero import EnergyZero, Interval, PriceType async def main() -> None: """Fetch today/tomorrow energy prices using the REST backend (default).""" async with EnergyZero() as client: today = datetime.now(UTC).astimezone().date() tomorrow = today + timedelta(days=1) electricity_today = await client.get_electricity_prices( start_date=today, interval=Interval.QUARTER, price_type=PriceType.ALL_IN, ) gas_today = await client.get_gas_prices( start_date=today, price_type=PriceType.ALL_IN, ) # Loop over additional days as needed electricity_tomorrow = await client.get_electricity_prices( start_date=tomorrow, interval=Interval.QUARTER, price_type=PriceType.MARKET_WITH_VAT, ) gas_tomorrow = await client.get_gas_prices( start_date=tomorrow, price_type=PriceType.MARKET, ) print(electricity_today.average_price, gas_today.current_price) print(electricity_tomorrow.average_price, gas_tomorrow.current_price) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Initialize EnergyZero Client Source: https://context7.com/klaasnicolaas/python-energyzero/llms.txt Configure the client using either the default REST backend or the GraphQL backend, with options for custom timeouts and existing aiohttp sessions. ```python import asyncio from energyzero import EnergyZero, APIBackend async def main() -> None: # Default REST backend with 10-second timeout async with EnergyZero() as client: # Use client for API calls pass # GraphQL backend with custom timeout async with EnergyZero( backend=APIBackend.GRAPHQL, request_timeout=15.0, ) as client: # Use client for multi-day queries pass # Using existing aiohttp session from aiohttp import ClientSession async with ClientSession() as session: client = EnergyZero(session=session) # API calls here await client.close() asyncio.run(main()) ``` -------------------------------- ### Fetch Electricity and Gas Prices Source: https://context7.com/klaasnicolaas/python-energyzero/llms.txt A complete implementation for fetching and displaying electricity and gas price summaries with error handling. ```python import asyncio from datetime import UTC, datetime, timedelta from energyzero import ( EnergyZero, EnergyPrices, EnergyZeroConnectionError, EnergyZeroNoDataError, Interval, PriceType, TimeRange, ) def format_price(price: float | None) -> str: return f"€{price:.4f}" if price is not None else "N/A" def print_electricity_summary(label: str, data: EnergyPrices) -> None: print(f"\n=== {label} ===") if len(data.prices) == 0: print("No data available") return min_price, max_price = data.extreme_prices print(f"Average: {format_price(data.average_price)}/kWh") print(f"Range: {format_price(min_price)} - {format_price(max_price)}/kWh") print(f"Cheapest: {data.lowest_price_time_range.astimezone()}") print(f"Most expensive: {data.highest_price_time_range.astimezone()}") if data.current_price is not None: print(f"Current: {format_price(data.current_price)}/kWh") print(f"Current as % of max: {data.pct_of_max_price}%") print(f"Slots at/below current: {data.time_ranges_priced_equal_or_lower}") async def fetch_day( client: EnergyZero, target_date, interval: Interval = Interval.QUARTER, ) -> EnergyPrices | None: try: return await client.get_electricity_prices( start_date=target_date, interval=interval, price_type=PriceType.ALL_IN, ) except (EnergyZeroConnectionError, EnergyZeroNoDataError) as err: print(f"Could not fetch {target_date}: {err}") return None async def main() -> None: async with EnergyZero() as client: today = datetime.now(UTC).astimezone().date() tomorrow = today + timedelta(days=1) # Fetch electricity prices elec_today = await fetch_day(client, today) elec_tomorrow = await fetch_day(client, tomorrow) if elec_today: print_electricity_summary(f"Electricity {today}", elec_today) if elec_tomorrow: print_electricity_summary(f"Electricity {tomorrow}", elec_tomorrow) # Fetch gas prices try: gas = await client.get_gas_prices( start_date=today, price_type=PriceType.ALL_IN, ) print(f"\n=== Gas {today} ===") print(f"Current: {format_price(gas.current_price)}/m³") print(f"Average: {format_price(gas.average_price)}/m³") except EnergyZeroNoDataError: print("\nNo gas prices available") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Fetch and Analyze Electricity Prices Source: https://context7.com/klaasnicolaas/python-energyzero/llms.txt Retrieves today's electricity prices with quarter-hour intervals and demonstrates how to access current price, future prices, price ranges, and time slots. ```python import asyncio from datetime import UTC, datetime, timedelta from energyzero import EnergyZero, Interval, PriceType, TimeRange async def main() -> None: async with EnergyZero() as client: today = datetime.now(UTC).astimezone().date() prices = await client.get_electricity_prices( start_date=today, interval=Interval.QUARTER, ) # Current price (based on system time) current = prices.current_price print(f"Current price: €{current:.4f}/kWh" if current else "No current price") # Price at a specific time specific_time = datetime.now(UTC) + timedelta(hours=2) future_price = prices.price_at_time(specific_time) print(f"Price in 2 hours: €{future_price:.4f}/kWh" if future_price else "Unknown") # Get min/max prices min_price, max_price = prices.extreme_prices print(f"Price range: €{min_price:.4f} - €{max_price:.4f}") # Time ranges with extreme prices cheapest_range: TimeRange = prices.lowest_price_time_range expensive_range: TimeRange = prices.highest_price_time_range print(f"Cheapest: {cheapest_range.astimezone()}") print(f"Most expensive: {expensive_range.astimezone()}") # Current price as percentage of maximum pct = prices.pct_of_max_price print(f"Current is {pct}% of max price") # Count of time slots cheaper than or equal to current cheaper_slots = prices.time_ranges_priced_equal_or_lower print(f"Slots at or below current price: {cheaper_slots}") # Iterate over all timestamp prices for entry in prices.timestamp_prices[:5]: tr: TimeRange = entry["timerange"] price: float = entry["price"] print(f"{tr.astimezone()}: €{price:.4f}") asyncio.run(main()) ``` -------------------------------- ### Work with TimeRange Objects Source: https://context7.com/klaasnicolaas/python-energyzero/llms.txt Demonstrates how to use the TimeRange model to check if a time falls within a range, convert timezones, and create custom time ranges for filtering. ```python import asyncio from datetime import UTC, datetime, timedelta import pytz from energyzero import EnergyZero, TimeRange async def main() -> None: async with EnergyZero() as client: today = datetime.now(UTC).astimezone().date() prices = await client.get_electricity_prices(start_date=today) # Get a TimeRange from results cheapest: TimeRange = prices.lowest_price_time_range # Check if a specific time falls within the range now = datetime.now(UTC) is_current = cheapest.contains(now) print(f"Currently in cheapest slot: {is_current}") # Convert to local timezone for display local_tz = pytz.timezone("Europe/Amsterdam") local_range = cheapest.astimezone(local_tz) print(f"Cheapest slot (UTC): {cheapest}") print(f"Cheapest slot (local): {local_range}") # Access start and end times print(f"Starts: {cheapest.start_including}") print(f"Ends: {cheapest.end_excluding}") # Create custom TimeRange for filtering custom_start = datetime(2024, 1, 15, 10, 0, 0, tzinfo=UTC) custom_end = datetime(2024, 1, 15, 14, 0, 0, tzinfo=UTC) custom_range = TimeRange(custom_start, custom_end) test_time = datetime(2024, 1, 15, 12, 0, 0, tzinfo=UTC) print(f"12:00 in range: {custom_range.contains(test_time)}") # True asyncio.run(main()) ``` -------------------------------- ### Handle API Exceptions Source: https://context7.com/klaasnicolaas/python-energyzero/llms.txt Demonstrates how to catch specific exceptions like EnergyZeroConnectionError and EnergyZeroNoDataError when interacting with the API. ```python import asyncio from datetime import UTC, datetime, timedelta from energyzero import ( EnergyZero, EnergyZeroError, EnergyZeroConnectionError, EnergyZeroNoDataError, ) async def main() -> None: async with EnergyZero(request_timeout=5.0) as client: today = datetime.now(UTC).astimezone().date() try: prices = await client.get_electricity_prices(start_date=today) print(f"Current price: €{prices.current_price:.4f}") except EnergyZeroConnectionError as err: # Network issues, timeouts, HTTP errors print(f"Connection failed: {err}") if err.status: print(f"HTTP status: {err.status}") if err.data: print(f"Response data: {err.data}") except EnergyZeroNoDataError as err: # No data available for requested period (e.g., future dates) print(f"No data available: {err}") except EnergyZeroError as err: # Base exception for other API errors print(f"API error: {err}") # Handling no data for tomorrow's prices (may not be published yet) tomorrow = today + timedelta(days=1) try: tomorrow_prices = await client.get_electricity_prices(start_date=tomorrow) print(f"Tomorrow's average: €{tomorrow_prices.average_price:.4f}") except EnergyZeroNoDataError: print("Tomorrow's prices not yet available (published 14:00-15:00)") # Safe access to EnergyPrices properties prices = await client.get_electricity_prices(start_date=today) try: min_p, max_p = prices.extreme_prices except EnergyZeroNoDataError: print("No prices in dataset to calculate extremes") asyncio.run(main()) ``` -------------------------------- ### Retrieve detailed price breakdown with EnergyPriceBlock Source: https://context7.com/klaasnicolaas/python-energyzero/llms.txt Requires the GraphQL backend to access raw price blocks and cost breakdowns. ```python import asyncio from datetime import datetime import pytz from energyzero import EnergyZero, APIBackend, EnergyPriceBlock async def main() -> None: async with EnergyZero(backend=APIBackend.GRAPHQL) as client: local_tz = pytz.timezone("Europe/Amsterdam") today = datetime.now(local_tz).date() prices = await client.get_electricity_prices( start_date=today, end_date=today, ) # Access raw price blocks with full cost breakdown for block in prices.raw_blocks[:3]: block: EnergyPriceBlock print(f"Time range: {block.time_range.astimezone(local_tz)}") print(f" Energy price (excl VAT): €{block.energy_price_excl:.5f}") print(f" Energy price (incl VAT): €{block.energy_price_incl:.5f}") print(f" VAT rate: {block.vat}") # Additional costs (e.g., energy tax, transport) for cost in block.additional_costs: print(f" {cost['name']}: €{cost['priceIncl']:.5f}") # Calculated totals print(f" Total (excl VAT): €{block.total_excl:.5f}") print(f" Total (incl VAT): €{block.total_incl:.5f}") print() asyncio.run(main()) ``` -------------------------------- ### Configure price types with PriceType enum Source: https://context7.com/klaasnicolaas/python-energyzero/llms.txt Controls whether VAT and surcharges are included in the retrieved electricity prices. ```python import asyncio from datetime import UTC, datetime from energyzero import EnergyZero, PriceType async def main() -> None: async with EnergyZero() as client: today = datetime.now(UTC).astimezone().date() # MARKET: Wholesale price excluding VAT, no surcharges market = await client.get_electricity_prices( start_date=today, price_type=PriceType.MARKET, ) # MARKET_WITH_VAT: Market price including VAT, no surcharges market_vat = await client.get_electricity_prices( start_date=today, price_type=PriceType.MARKET_WITH_VAT, ) # ALL_IN_EXCL_VAT: Market + surcharges, excluding VAT all_in_excl = await client.get_electricity_prices( start_date=today, price_type=PriceType.ALL_IN_EXCL_VAT, ) # ALL_IN: Final consumer rate with VAT and all surcharges (default) all_in = await client.get_electricity_prices( start_date=today, price_type=PriceType.ALL_IN, ) print(f"Market (excl VAT): €{market.current_price:.5f}") print(f"Market (incl VAT): €{market_vat.current_price:.5f}") print(f"All-in (excl VAT): €{all_in_excl.current_price:.5f}") print(f"All-in (incl VAT): €{all_in.current_price:.5f}") asyncio.run(main()) ``` -------------------------------- ### Retrieve Electricity Prices via REST API Source: https://context7.com/klaasnicolaas/python-energyzero/llms.txt Fetch electricity pricing data for a specific day, supporting both quarter-hour and hourly intervals with configurable price types. ```python import asyncio from datetime import UTC, datetime, timedelta from energyzero import EnergyZero, Interval, PriceType async def main() -> None: async with EnergyZero() as client: today = datetime.now(UTC).astimezone().date() # Quarter-hour prices with all-in pricing (including VAT and surcharges) electricity = await client.get_electricity_prices( start_date=today, interval=Interval.QUARTER, price_type=PriceType.ALL_IN, ) # Hourly prices with market pricing (excluding VAT) electricity_hourly = await client.get_electricity_prices( start_date=today, interval=Interval.HOUR, price_type=PriceType.MARKET, ) print(f"Current price: €{electricity.current_price:.4f}/kWh") print(f"Average price: €{electricity.average_price:.4f}/kWh") min_price, max_price = electricity.extreme_prices print(f"Min: €{min_price:.4f}, Max: €{max_price:.4f}") print(f"Current as % of max: {electricity.pct_of_max_price}%") print(f"Cheapest time: {electricity.lowest_price_time_range.astimezone()}") print(f"Most expensive time: {electricity.highest_price_time_range.astimezone()}") asyncio.run(main()) ``` -------------------------------- ### Run Pytest Test Suite Source: https://github.com/klaasnicolaas/python-energyzero/blob/main/README.md Executes the test suite using pytest. This command runs all defined tests to verify the project's functionality. ```bash poetry run pytest ``` -------------------------------- ### get_electricity_prices() Source: https://github.com/klaasnicolaas/python-energyzero/blob/main/README.md Retrieves electricity prices in EUR/kWh for a specified date range. ```APIDOC ## get_electricity_prices() ### Description Returns electricity prices in EUR/kWh. ### Parameters #### Query Parameters - **start_date** (date) - Required - Start of the period (local timezone). - **end_date** (date) - Required - End of the period (local timezone). - **interval** (Interval) - Optional - REST only: Interval.QUARTER or Interval.HOUR. Ignored by GraphQL. - **price_type** (PriceType) - Optional - Type of price to return (default ALL_IN). ``` -------------------------------- ### get_gas_prices() Source: https://github.com/klaasnicolaas/python-energyzero/blob/main/README.md Retrieves gas prices in EUR/m³ for a specified date range. ```APIDOC ## get_gas_prices() ### Description Returns gas prices in EUR/m³. ### Parameters #### Query Parameters - **start_date** (date) - Required - Start of the period (local timezone). - **end_date** (date) - Required - End of the period (local timezone). - **price_type** (PriceType) - Optional - Type of price to return (default ALL_IN). ``` -------------------------------- ### Run All Prek Checks and Tests Manually Source: https://github.com/klaasnicolaas/python-energyzero/blob/main/README.md Executes all prek checks and tests across all files in the project. This is useful for ensuring code quality and test coverage. ```bash poetry run prek run --all-files ``` -------------------------------- ### Set data granularity with Interval enum Source: https://context7.com/klaasnicolaas/python-energyzero/llms.txt Specifies time intervals for electricity prices; only applicable to the REST backend. ```python import asyncio from datetime import UTC, datetime from energyzero import EnergyZero, Interval async def main() -> None: async with EnergyZero() as client: today = datetime.now(UTC).astimezone().date() # QUARTER: 15-minute intervals (96 prices per day) quarter = await client.get_electricity_prices( start_date=today, interval=Interval.QUARTER, ) print(f"Quarter-hour intervals: {len(quarter.prices)} prices") # HOUR: Hourly intervals (24 prices per day) hourly = await client.get_electricity_prices( start_date=today, interval=Interval.HOUR, ) print(f"Hourly intervals: {len(hourly.prices)} prices") # DAY: Used internally for gas prices gas = await client.get_gas_prices(start_date=today) print(f"Daily gas prices: {len(gas.prices)} price") # Compare granularity print(f"\nQuarter-hour average: €{quarter.average_price:.4f}") print(f"Hourly average: €{hourly.average_price:.4f}") asyncio.run(main()) ``` -------------------------------- ### Update Pytest Snapshot Tests Source: https://github.com/klaasnicolaas/python-energyzero/blob/main/README.md Updates the snapshot tests used by syrupy. This command should be run when the expected output of tests has legitimately changed. ```bash poetry run pytest --snapshot-update ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.