Extended support for Tibber electricity prices in Home Assistant
Find a file
Julian Pawlowski 9640b041e0 refactor(periods): move all period logic to coordinator and refactor period_utils
Moved filter logic and all period attribute calculations from binary_sensor.py
to coordinator.py and period_utils.py, following Home Assistant best practices
for data flow architecture.

ARCHITECTURE CHANGES:

Binary Sensor Simplification (~225 lines removed):
- Removed _build_periods_summary, _add_price_diff_for_period (calculation logic)
- Removed _get_period_intervals_from_price_info (107 lines, interval reconstruction)
- Removed _should_show_periods, _check_volatility_filter, _check_level_filter
- Removed _build_empty_periods_result (filtering result builder)
- Removed _get_price_hours_attributes (24 lines, dead code)
- Removed datetime import (unused after cleanup)
- New: _build_final_attributes_simple (~20 lines, timestamp-only)
- Result: Pure display-only logic, reads pre-calculated data from coordinator

Coordinator Enhancement (+160 lines):
- Added _should_show_periods(): UND-Verknüpfung of volatility and level filters
- Added _check_volatility_filter(): Checks min_volatility threshold
- Added _check_level_filter(): Checks min/max level bounds
- Enhanced _calculate_periods_for_price_info(): Applies filters before period calculation
- Returns empty periods when filters don't match (instead of calculating unnecessarily)
- Passes volatility thresholds (moderate/high/very_high) to PeriodConfig

Period Utils Refactoring (+110 lines):
- Extended PeriodConfig with threshold_volatility_moderate/high/very_high
- Added PeriodData NamedTuple: Groups timing data (start, end, length, position)
- Added PeriodStatistics NamedTuple: Groups calculated stats (prices, volatility, ratings)
- Added ThresholdConfig NamedTuple: Groups all thresholds + reverse_sort flag
- New _calculate_period_price_statistics(): Extracts price_avg/min/max/spread calculation
- New _build_period_summary_dict(): Builds final dict with correct attribute ordering
- Enhanced _extract_period_summaries(): Now calculates ALL attributes (no longer lightweight):
  * price_avg, price_min, price_max, price_spread (in minor units: ct/øre)
  * volatility (low/moderate/high/very_high based on absolute thresholds)
  * rating_difference_% (average of interval differences)
  * period_price_diff_from_daily_min/max (period avg vs daily reference)
  * aggregated level and rating_level
  * period_interval_count (renamed from interval_count for clarity)
- Removed interval_starts array (redundant - start/end/count sufficient)
- Function signature refactored from 9→4 parameters using NamedTuples

Code Organization (HA Best Practice):
- Moved calculate_volatility_level() from const.py to price_utils.py
- Rule: const.py should contain only constants, no functions
- Removed duplicate VOLATILITY_THRESHOLD_* constants from const.py
- Updated imports in sensor.py, services.py, period_utils.py

DATA FLOW:

Before:
API → Coordinator (basic enrichment) → Binary Sensor (calculate everything on each access)

After:
API → Coordinator (enrichment + filtering + period calculation with ALL attributes) →
      Cached Data → Binary Sensor (display + timestamp only)

ATTRIBUTE STRUCTURE:

Period summaries now contain (following copilot-instructions.md ordering):
1. Time: start, end, duration_minutes
2. Decision: level, rating_level, rating_difference_%
3. Prices: price_avg, price_min, price_max, price_spread, volatility
4. Differences: period_price_diff_from_daily_min/max (conditional)
5. Details: period_interval_count, period_position
6. Meta: periods_total, periods_remaining

BREAKING CHANGES: None
- Period data structure enhanced but backwards compatible
- Binary sensor API unchanged (state + attributes)

Impact: Binary sensors now display pre-calculated data from coordinator instead
of calculating on every access. Reduces complexity, improves performance, and
centralizes business logic following Home Assistant coordinator pattern. All
period filtering (volatility + level) now happens in coordinator before caching.
2025-11-09 23:46:48 +00:00
.copilot add copilot instructions 2025-04-23 17:46:12 +00:00
.devcontainer chore(devcontainer): consolidate VS Code settings and remove deprecated options 2025-11-09 16:01:54 +00:00
.github feat(translations): update language style and tone for user instructions across multiple languages 2025-11-09 19:27:42 +00:00
config update dev environment 2025-11-03 15:54:01 +00:00
custom_components/tibber_prices refactor(periods): move all period logic to coordinator and refactor period_utils 2025-11-09 23:46:48 +00:00
docs docs: restructure documentation and add AI development disclosure 2025-11-09 14:25:27 +00:00
images fix: Update README to display the correct logo image 2025-11-06 16:27:28 +00:00
scripts feat(release): enhance generate-release-notes with AI optimization and auto-update 2025-11-09 17:51:15 +00:00
.editorconfig refactoring devcontainer 2025-04-23 18:27:46 +00:00
.gitattributes Initial commit 2025-04-18 14:32:54 +02:00
.gitignore update dev environment 2025-11-03 15:54:01 +00:00
.markdownlint.json chore(markdownlint): add initial configuration file 2025-11-09 16:02:19 +00:00
.pre-commit-config.yaml add lots of new sensors 2025-11-03 20:55:28 +00:00
.prettierignore refactoring devcontainer 2025-04-23 18:27:46 +00:00
AGENTS.md add symlinks for agents 2025-11-03 17:45:25 +00:00
CLAUDE.md add symlinks for agents 2025-11-03 17:45:25 +00:00
cliff.toml feat(release): add automated release notes generation system 2025-11-09 14:25:15 +00:00
CONTRIBUTING.md docs: restructure documentation and add AI development disclosure 2025-11-09 14:25:27 +00:00
hacs.json fix: Update HACS version and add country list in hacs.json 2025-11-07 14:34:14 +00:00
LICENSE Rename component 2025-04-18 12:51:32 +00:00
pyproject.toml refactor: Update integration version handling in TibberPrices components 2025-11-07 23:43:39 +00:00
README.md docs: update installation instructions and add configuration steps for HACS integration 2025-11-09 18:37:18 +00:00
requirements.txt update requirements 2025-11-06 11:42:47 +00:00

Tibber Price Information & Ratings

GitHub Release GitHub Activity License

hacs Project Maintenance BuyMeCoffee

A Home Assistant integration that provides advanced price information and ratings from Tibber. This integration fetches quarter-hourly electricity prices, enriches them with statistical analysis, and provides smart indicators to help you optimize your energy consumption and save money.

Tibber Price Information & Ratings

📖 Documentation

Features

  • Quarter-Hourly Price Data: Access detailed 15-minute interval pricing (192 data points across yesterday/today/tomorrow)
  • Current and Next Interval Prices: Get real-time price data in both major currency (€, kr) and minor units (ct, øre)
  • Multi-Currency Support: Automatic detection and formatting for EUR, NOK, SEK, DKK, USD, and GBP
  • Price Level Indicators: Know when you're in a VERY_CHEAP, CHEAP, NORMAL, EXPENSIVE, or VERY_EXPENSIVE period
  • Statistical Sensors: Track lowest, highest, and average prices for the day
  • Price Ratings: Quarter-hourly ratings comparing current prices to 24-hour trailing averages
  • Smart Indicators: Binary sensors to detect peak hours and best price hours for automations
  • Intelligent Caching: Minimizes API calls while ensuring data freshness across Home Assistant restarts
  • Custom Services: API endpoints for advanced integrations (ApexCharts support included)
  • Diagnostic Sensors: Monitor data freshness and availability
  • Reliable API Usage: Uses only official Tibber priceInfo and priceInfoRange endpoints - no legacy APIs. Price ratings and statistics are calculated locally for maximum reliability and future-proofing.

🚀 Quick Start

Step 1: Install the Integration

Prerequisites: This integration requires HACS (Home Assistant Community Store) to be installed.

Click the button below to open the integration directly in HACS:

Open your Home Assistant instance and open a repository inside the Home Assistant Community Store.

Then:

  1. Click "Download" to install the integration
  2. Restart Home Assistant (required after installation)

Note: The My Home Assistant redirect will first take you to a landing page. Click the button there to open your Home Assistant instance. If the repository is not yet in the HACS default store, HACS will ask if you want to add it as a custom repository.

Step 2: Add and Configure the Integration

Important: You must have installed the integration first (see Step 1) and restarted Home Assistant!

Option 1: One-Click Setup (Quick)

Click the button below to open the configuration dialog:

Open your Home Assistant instance and start setting up a new integration.

This will guide you through:

  1. Enter your Tibber API token (get one here)
  2. Select your Tibber home
  3. Configure price thresholds (optional)

Option 2: Manual Configuration

  1. Go to SettingsDevices & Services
  2. Click "+ Add Integration"
  3. Search for "Tibber Price Information & Ratings"
  4. Follow the configuration steps (same as Option 1)

Step 3: Start Using!

  • 30+ sensors are now available (key sensors enabled by default)
  • Configure additional sensors in SettingsDevices & ServicesTibber Price Information & RatingsEntities
  • Use sensors in automations, dashboards, and scripts

📖 Full Installation Guide →

📊 Available Entities

The integration provides 30+ sensors across different categories. Key sensors are enabled by default, while advanced sensors can be enabled as needed.

Rich Sensor Attributes: All sensors include extensive attributes with timestamps, context data, and detailed explanations. Enable Extended Descriptions in the integration options to add long_description and usage_tips attributes to every sensor, providing in-context documentation directly in Home Assistant's UI.

Core Price Sensors (Enabled by Default)

Entity Description
Current Electricity Price Current 15-minute interval price
Next Interval Price Price for the next 15-minute interval
Current Hour Average Price Average of current hour's 4 intervals
Next Hour Average Price Average of next hour's 4 intervals
Current Price Level API classification (VERY_CHEAP to VERY_EXPENSIVE)
Next Interval Price Level Price level for next interval
Current Hour Price Level Price level for current hour average
Next Hour Price Level Price level for next hour average

Statistical Sensors (Enabled by Default)

Entity Description
Today's Lowest Price Minimum price for today
Today's Highest Price Maximum price for today
Today's Average Price Mean price across today's intervals
Tomorrow's Lowest Price Minimum price for tomorrow (when available)
Tomorrow's Highest Price Maximum price for tomorrow (when available)
Tomorrow's Average Price Mean price for tomorrow (when available)
Leading 24h Average Price Average of next 24 hours from now
Leading 24h Minimum Price Lowest price in next 24 hours
Leading 24h Maximum Price Highest price in next 24 hours

Price Rating Sensors (Enabled by Default)

Entity Description
Current Price Rating % difference from 24h trailing average (current interval)
Next Interval Price Rating % difference from 24h trailing average (next interval)
Current Hour Price Rating % difference for current hour average
Next Hour Price Rating % difference for next hour average

How ratings work: Compares each interval to the average of the previous 96 intervals (24 hours). Positive values mean prices are above average, negative means below average.

Binary Sensors (Enabled by Default)

Entity Description
Peak Price Interval ON when current interval is in the highest 20% of day's prices
Best Price Interval ON when current interval is in the lowest 20% of day's prices
Tibber API Connection Connection status to Tibber API
Tomorrow's Data Available Whether tomorrow's price data is available

Diagnostic Sensors (Enabled by Default)

Entity Description
Data Expiration Timestamp when current data expires
Price Forecast Formatted list of upcoming price intervals

Additional Sensors (Disabled by Default)

The following sensors are available but disabled by default. Enable them in Settings > Devices & Services > Tibber Price Information & Ratings > Entities:

  • Previous Interval Price & Previous Interval Price Level: Historical data for the last 15-minute interval
  • Previous Interval Price Rating: Rating for the previous interval
  • Trailing 24h Average Price: Average of the past 24 hours from now
  • Trailing 24h Minimum/Maximum Price: Min/max in the past 24 hours

Note

: All monetary sensors use minor currency units (ct/kWh, øre/kWh, ¢/kWh, p/kWh) automatically based on your Tibber account's currency. Supported: EUR, NOK, SEK, DKK, USD, GBP.

Automation Examples

Run Appliances During Cheap Hours

Use the binary_sensor.tibber_best_price_interval to automatically start appliances during the cheapest 15-minute periods:

automation:
    - alias: "Run Dishwasher During Cheap Hours"
      trigger:
          - platform: state
            entity_id: binary_sensor.tibber_best_price_interval
            to: "on"
      condition:
          - condition: time
            after: "21:00:00"
            before: "06:00:00"
      action:
          - service: switch.turn_on
            target:
                entity_id: switch.dishwasher

Notify on Extremely High Prices

Get notified when prices reach the VERY_EXPENSIVE level:

automation:
    - alias: "Notify on Very Expensive Electricity"
      trigger:
          - platform: state
            entity_id: sensor.tibber_current_price_level
            to: "VERY_EXPENSIVE"
      action:
          - service: notify.mobile_app
            data:
                title: "⚠️ High Electricity Prices"
                message: "Current electricity price is in the VERY EXPENSIVE range. Consider reducing consumption."

Temperature Control Based on Price Ratings

Adjust heating/cooling when current prices are significantly above the 24h average:

automation:
    - alias: "Reduce Heating During High Price Ratings"
      trigger:
          - platform: numeric_state
            entity_id: sensor.tibber_current_price_rating
            above: 20  # More than 20% above 24h average
      action:
          - service: climate.set_temperature
            target:
                entity_id: climate.living_room
            data:
                temperature: 19  # Lower target temperature

Smart EV Charging Based on Tomorrow's Prices

Start charging when tomorrow's prices drop below today's average:

automation:
    - alias: "Smart EV Charging"
      trigger:
          - platform: state
            entity_id: binary_sensor.tibber_best_price_interval
            to: "on"
      condition:
          - condition: numeric_state
            entity_id: sensor.tibber_current_price_rating
            below: -15  # At least 15% below average
          - condition: numeric_state
            entity_id: sensor.ev_battery_level
            below: 80
      action:
          - service: switch.turn_on
            target:
                entity_id: switch.ev_charger

Troubleshooting

No data appearing

  1. Check your API token is valid at developer.tibber.com
  2. Verify you have an active Tibber subscription
  3. Check the Home Assistant logs for detailed error messages (Settings > System > Logs)
  4. Restart the integration: Settings > Devices & Services > Tibber Price Information & Ratings > ⋮ > Reload

Missing tomorrow's price data

  • Tomorrow's price data typically becomes available between 13:00 and 15:00 each day (Nordic time)
  • The integration automatically checks more frequently during this window
  • Check binary_sensor.tibber_tomorrows_data_available to see if data is available
  • If data is unavailable after 15:00, verify it's available in the Tibber app first

Prices not updating at quarter-hour boundaries

  • Entities automatically refresh at 00/15/30/45-minute marks without waiting for API polls
  • Check sensor.tibber_data_expiration to verify data freshness
  • The integration caches data intelligently and survives Home Assistant restarts

Currency or units showing incorrectly

  • Currency is automatically detected from your Tibber account
  • The integration supports EUR, NOK, SEK, DKK, USD, and GBP with appropriate minor units
  • Enable/disable major vs. minor unit sensors in Settings > Devices & Services > Tibber Price Information & Ratings > Entities

Advanced Features

Sensor Attributes

Every sensor includes rich attributes beyond just the state value. These attributes provide context, timestamps, and additional data useful for automations and templates.

Standard attributes available on most sensors:

  • timestamp - ISO 8601 timestamp for the data point
  • description - Brief explanation of what the sensor represents
  • level_id and level_value - For price level sensors (e.g., VERY_CHEAP = -2)

Extended descriptions (enable in integration options):

  • long_description - Detailed explanation of the sensor's purpose
  • usage_tips - Practical suggestions for using the sensor in automations

Example - Current Price sensor attributes:

timestamp: "2025-11-03T14:15:00+01:00"
description: "The current electricity price per kWh"
long_description: "Shows the current price per kWh from your Tibber subscription"
usage_tips: "Use this to track prices or to create automations that run when electricity is cheap"

Example template using attributes:

template:
  - sensor:
      - name: "Price Status"
        state: >
          {% set price = states('sensor.tibber_current_electricity_price') | float %}
          {% set timestamp = state_attr('sensor.tibber_current_electricity_price', 'timestamp') %}
          Price at {{ timestamp }}: {{ price }} ct/kWh          

📖 View all sensors and attributes →

Custom Services

The integration provides custom services for advanced use cases:

  • tibber_prices.get_price - Fetch price data for specific days/times
  • tibber_prices.get_apexcharts_data - Get formatted data for ApexCharts cards
  • tibber_prices.get_apexcharts_yaml - Generate complete ApexCharts configurations
  • tibber_prices.refresh_user_data - Manually refresh account information

📖 Service documentation and examples →

ApexCharts Integration

The integration includes built-in support for creating beautiful price visualization cards. Use the get_apexcharts_yaml service to generate card configurations automatically.

📖 ApexCharts examples →

🤝 Contributing

Contributions are welcome! Please read the Contributing Guidelines and Developer Guide before submitting pull requests.

For Contributors

🤖 Development Note

This integration is developed with extensive AI assistance (GitHub Copilot, Claude, and other AI tools). While AI enables rapid development and helps implement complex features, it's possible that some edge cases or subtle bugs may exist that haven't been discovered yet. If you encounter any issues, please open an issue - we'll work on fixing them (with AI help, of course! 😊).

The integration is actively maintained and benefits from AI's ability to quickly understand and implement Home Assistant patterns, maintain consistency across the codebase, and handle complex data transformations. Quality is ensured through automated linting (Ruff), Home Assistant's type checking, and real-world testing.

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.