Skip to main content

Solar production and power consumption forecasting package.

Project description

☀️ KPower Forecast 📈

PyPI version Python versions CI License: AGPL-3.0 Code style: black

Production-grade solar production and power consumption forecasting.

Built with Facebook Prophet and powered by Open-Meteo. KPower Forecast provides a high-level API for training and predicting energy metrics with physics-informed corrections.


✨ Key Features

  • 🔋 Dual Mode: Specialized logic for both Solar Production and Energy Consumption.
  • 🌓 Night Masking: Physics-informed clamping using solar elevation to eliminate "ghost production" at night.
  • 🌡️ Weather Integration: Automatic fetching and resampling of temperature, cloud cover, and radiation.
  • 🌦️ Adaptive Weather Correction: Learns location/model-specific weather bias as forecast history accumulates.
  • Optional Curtailment Limits: Clips delivered solar forecasts to inverter or export limits when configured.
  • 🤖 Prophet Optimized: Pre-configured regressors for maximum accuracy.
  • 💾 Smart Persistence: Automatic serialization of models to skip retraining when possible.
  • ❄️ Heat Pump Mode: Optional temperature correlation for energy consumption models.

🚀 Quick Start

Installation

# Core package
pip install kpower-forecast

# With CLI support (recommended for interactive use)
pip install "kpower-forecast[cli]"

# With the local Nixtla hybrid ML forecasting backend
pip install "kpower-forecast[ml]"

# With NeuralForecast / AI forecasting support
pip install "kpower-forecast[ai]"

🖥️ CLI Usage

KPower Forecast comes with a powerful CLI for interactive forecasting and visualization.

# Forecast solar production using Home Assistant CSV export
# Supports different data categories: instant_energy, cumulative_energy, power
# Supports different units: kWh, Wh, kW, W
# Optional delivered-energy curtailment limits can be supplied in kW
kpower-forecast solar rooftop-1 46.05 14.50 -i history.csv --category power --unit W --inverter-limit 10 --export-limit 7 --horizon 7

# Forecast power consumption
kpower-forecast consumption main-meter 46.05 14.50 -i history.csv --category cumulative_energy --unit kWh --horizon 3 --heatpump

CLI Features:

  • Automatic HA Parsing: Heuristic detection of last_changed and state columns.
  • Smart Data Normalization: Handles meter readings (cumulative), power (kW/W), and instant energy.
  • Heat Pump Mode: Enable --heatpump to correlate consumption with outdoor temperature.
  • Inconsistent Intervals: Robustly handles measurements with non-uniform time gaps.
  • Rich Tables: Beautiful daily summary tables in your terminal.
  • Terminal Graphs: Instant visualization of forecasts and confidence intervals via plotext.

☀️ Solar Production Forecast (API)

from kpower_forecast import KPowerForecast
from kpower_forecast.core import DataCategory, MeasurementUnit
import pandas as pd

# 1. Initialize for your location with specific data types
kp = KPowerForecast(
    model_id="rooftop_solar",
    latitude=46.0569,
    longitude=14.5058,
    forecast_type="solar",
    data_category=DataCategory.POWER,
    unit=MeasurementUnit.W,
    inverter_ac_limit_kw=10.0,
    grid_export_limit_kw=7.0,
)

# 2. Train with your history
# history_df = pd.DataFrame({'ds': [...], 'y': [...]})
# kp.train(history_df)

# 3. Predict the next 7 days
forecast = kp.predict(days=7)
print(forecast[['ds', 'yhat']].head())

🏠 Energy Consumption Forecast

kp_cons = KPowerForecast(
    model_id="house_meter",
    latitude=46.0569,
    longitude=14.5058,
    forecast_type="consumption",
    heat_pump_mode=True # Accounts for heating/cooling loads
)

🧠 Optional ML Forecasting Add-on

The core KPowerForecast API remains optimized for lightweight Prophet-based forecasting. For local classical ML workflows, install the ml extra and use KPowerMLForecast from the optional namespace:

from kpower_forecast.ml import KPowerMLForecast, MLBackendType, MLForecastType

kp_ml = KPowerMLForecast(
    model_id="house_meter_ml",
    latitude=46.0569,
    longitude=14.5058,
    forecast_type=MLForecastType.CONSUMPTION,
    backend=MLBackendType.NIXTLA_HYBRID,
)

# history_df = pd.DataFrame({'ds': [...], 'y': [...]})
# kp_ml.train(history_df, force=True)
forecast = kp_ml.predict(days=3)
print(forecast[["ds", "yhat", "yhat_lower_90", "yhat_upper_90"]].head())

The ML add-on uses Nixtla-compatible backends behind a small project-owned backend interface. NIXTLA_HYBRID combines a statsforecast structural baseline with an mlforecast/LightGBM residual learner and is suitable for local CPU-only controller deployments. NEURALFORECAST is also wired as a selectable Nixtla backend for users who install kpower-forecast[ai] and provide NeuralForecast model objects in backend_params. Future foundation-model adapters can plug into the same backend contract without changing the public API.

For PV forecasts, inverter_ac_limit_kw and grid_export_limit_kw cap the predicted interval energy to account for inverter clipping and static export curtailment. predict(dynamic_export_limits=...) also accepts a dataframe with ds plus export_limit_kw, grid_export_limit_kw, curtailment_limit_kw, or limit_kw for time-varying export controls.


🛠️ Advanced Configuration

Parameter Type Default Description
model_id str required Unique ID for model persistence
latitude float required Location Latitude
longitude float required Location Longitude
interval_minutes `int" 15 Data resolution (15 or 60)
storage_path str "./data" Directory for saved models
heat_pump_mode bool False Enable temperature regressor for consumption
adaptive_weather_correction bool True Learn weather correction from archived forecasts, with historical weather fallback
inverter_ac_limit_kw float | None None Optional inverter AC output limit in kW
grid_export_limit_kw float | None None Optional grid export limit in kW

Adaptive weather correction is conservative on new sites. Initial training works without historical forecast snapshots by falling back to archive weather, then improves as generated forecasts are archived and later matched with actual production.


🔢 Versioning

This project follows a custom Date-Based Versioning scheme: YYYY.MM.Patch (e.g., 2026.2.1)

  • YYYY: Year of release.
  • MM: Month of release (no leading zero, 1-12).
  • Patch: Incremental counter for releases within the same month.

Enforcement

  • CI Validation: Every Pull Request is checked against scripts/validate_version.py to ensure adherence.
  • Consistency: Both pyproject.toml and src/kpower_forecast/__init__.py must match exactly.

🧪 Development & Testing

We use uv for lightning-fast dependency management.

# Clone and setup
git clone https://github.com/akorenc/kpower-forecast
cd kpower-forecast
uv sync --all-extras

# Run tests
uv run pytest

# Linting
uv run ruff check .

📄 License

Distributed under the GNU Affero General Public License v3.0. See LICENSE for more information.


Made with ❤️ for a greener future.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

kpower_forecast-2026.5.4.tar.gz (206.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

kpower_forecast-2026.5.4-py3-none-any.whl (56.7 kB view details)

Uploaded Python 3

File details

Details for the file kpower_forecast-2026.5.4.tar.gz.

File metadata

  • Download URL: kpower_forecast-2026.5.4.tar.gz
  • Upload date:
  • Size: 206.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.14 {"installer":{"name":"uv","version":"0.11.14","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for kpower_forecast-2026.5.4.tar.gz
Algorithm Hash digest
SHA256 a69253100344ae9bb2c64382ba6e835c20e82c486ecb1b97b77773ef4d98a820
MD5 1e9afc3fc529c515062cd040e3b5a3d1
BLAKE2b-256 e92c4a76ae46328c14ef5b8d3da10cb1db664e015abd7f300bae44e585a52570

See more details on using hashes here.

File details

Details for the file kpower_forecast-2026.5.4-py3-none-any.whl.

File metadata

  • Download URL: kpower_forecast-2026.5.4-py3-none-any.whl
  • Upload date:
  • Size: 56.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.14 {"installer":{"name":"uv","version":"0.11.14","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for kpower_forecast-2026.5.4-py3-none-any.whl
Algorithm Hash digest
SHA256 877b0ea87a7cd9fdfb97b5e4b221be733b4a6efa61ed6f15ec4c45918cdd7702
MD5 9e952a9c72e79f40bc24561ccc7d5fa2
BLAKE2b-256 dc7e6297c47d4389d4a1c22d4c9bfd607cef52d6c38c87d2275a3eaf42b8409f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page