Skip to content

Utilities

The eptr2.util module provides utility functions for common operations.

Time Utilities

eptr2.util.time

Utility functions for time and date handling.

from eptr2.util.time import iso_to_contract

iso_to_contract

Converts ISO datetime to contract symbol format.

from eptr2.util.time import iso_to_contract

contract = iso_to_contract("2024-07-29T10:00:00+03:00")
print(contract)  # e.g., "PH24072910"

Cost Utilities

eptr2.util.costs

Imbalance and KÜPST (production plan deviation) prices and costs. Start with the two main functions: they resolve every regulation parameter (floor and ceiling prices, V, B, margins, KÜPST tolerance and multiplier by category) for each hour from its delivery date, so a range spanning regulation changes is priced hour by hour. EPİAŞ's published imbalance prices are used where available; they are calculated only for hours without them. Hours without SMP (such as the rest of the current day) are skipped with a warning.

from eptr2.util.costs import calculate_imbalance_prices, calculate_imbalance_costs

## Hourly prices, unit costs and every parameter used (fetches mcp-smp-imb)
prices_df = calculate_imbalance_prices("2026-10-01", "2026-10-07", eptr=eptr)

## Imbalance and KÜPST costs of actual vs forecast rows
costs_df = calculate_imbalance_costs(
    data=[
        {"date": "2026-11-01T10:00:00+03:00", "actual": 80, "forecast": 100},
        {"date": "2026-11-01T11:00:00+03:00", "actual": 95, "forecast": 90},
    ],
    category="Rüzgar",  # any naming convention, see normalize_kupst_category
    eptr=eptr,
)

## Offline or scenario prices: pass them instead of fetching
calculate_imbalance_prices(
    prices=[{"date": "2026-11-01T00:00:00+03:00", "mcp": 120, "smp": 130,
             "system_direction": -1}],
    kupst_category="wind",
)

The dated regulation table is get_time_regulation_params_map(); each row names its period (26_01 from 2026-01-01, 26_02 from 2026-11-01, 27_01 from 2027-01-01, when consumption units get KÜPST). KÜPST coefficients follow EPDK Decision 14029 (RG 29/12/2025, No. 33122) for 26_01 and Decision 14907 (RG 19/10/2026, No. 33405) for 26_02; V = 100 from 2026-11-01 is Decision 14911 (same issue).

calculate_imbalance_costs measures the costs against the plan passed as forecast. KUDÜP approximates the settled values: settlement uses BUDÜP = KUDÜP + YAL − YAT + SRDM + SFHM, and since plant-level YAL/YAT are not published, they are taken as 0. KGÜP v1 gives a what-if: the costs had the day-ahead plan not changed.

calculate_imbalance_prices

calculate_imbalance_prices(start_date: str | datetime | None = None, end_date: str | datetime | None = None, prices: DataFrame | list[dict] | None = None, eptr: EPTR2 | None = None, kupst_category: str = 'other', include_maintenance_penalty: bool = False, return_df: bool = True, include_calculated: bool = False, **kwargs: float) -> DataFrame | list[dict]

Hourly imbalance prices, unit costs and every regulation parameter used to calculate them, resolved automatically from each hour's delivery date.

For each hour the regulation period, price floor and ceiling, V, B, low, high and ceiling margins and the KUPST tolerance, multiplier and floor price are looked up (see get_time_regulation_params_map and contract_to_floor_ceil_prices), so a range spanning regulation changes is priced correctly hour by hour.

Market prices come from prices if given, otherwise they are fetched from EPİAŞ (mcp-smp-imb) for the range. Where the published imbalance prices are available (always for fetched hours, or 'positiveImbalance' / 'negativeImbalance' in prices) they are used as pos_imb_price and neg_imb_price, and the unit costs follow from them. Otherwise the prices are calculated from MCP, SMP, system direction and the resolved parameters, e.g. for scenarios or offline use.

Hours without SMP and published prices cannot be priced and are skipped with a warning. EPİAŞ returns every hour of the current day, those after the latest published hour without SMP, so a range ending today returns its published hours only. If no hour has SMP, ValueError is raised. For future hours pass prices with an SMP scenario.

Parameters:

Name Type Description Default
start_date str | datetime | None

Start of the range: 'YYYY-MM-DD', ISO datetime, contract code or datetime. Required unless prices is given.

None
end_date str | datetime | None

End of the range (inclusive). A date means its last hour.

None
prices DataFrame | list[dict] | None

Hourly prices as a DataFrame or list of dicts with 'date' (or 'contract'), 'mcp' (or 'ptf') and 'smp' (or 'smf'), and optionally 'system_direction' (-1/0/1, or EPİAŞ 'systemStatus' labels such as 'Enerji Açığı'). The raw mcp-smp-imb response is accepted as is. Rows outside start_date/end_date are dropped.

None
eptr EPTR2 | None

EPTR2 client for fetching. Created from .env if needed.

None
kupst_category str

KUPST category or source name for the KUPST columns (see normalize_kupst_category).

'other'
include_maintenance_penalty bool

Use the KUPST maintenance multiplier.

False
return_df bool

Return a pandas DataFrame if pandas is installed, otherwise (or if False) a list of dicts.

True
include_calculated bool

Also return calculated_pos_imb_price and calculated_neg_imb_price, to check the resolved parameters against the published prices.

False
**kwargs float

Explicit parameter overrides that win over the resolved ones: floor_price, ceil_price, V, B, low_margin, high_margin, ceil_margin, kupst_multiplier, kupst_floor_price.

{}

Returns:

Type Description
DataFrame | list[dict]

One row per hour with: date, contract, regulation_period, mcp, smp,

DataFrame | list[dict]

system_direction, floor_price, ceil_price, V, B, low_margin,

DataFrame | list[dict]

high_margin, ceil_margin (None before 2026, whose formula does not use

DataFrame | list[dict]

them), pos_imb_price, neg_imb_price, imb_price_source ('published' or

DataFrame | list[dict]

'calculated'), unit_pos_imb_cost, unit_neg_imb_cost, kupst_category,

DataFrame | list[dict]

kupst_tolerance, kupst_multiplier, kupst_floor_price, unit_kupst_cost

DataFrame | list[dict]

and, with include_calculated, calculated_pos_imb_price and

DataFrame | list[dict]

calculated_neg_imb_price. KUPST is not published per hour, so its unit

DataFrame | list[dict]

cost is always calculated.

Notes

When MCP equals SMP the system direction cannot be inferred from prices. Fetched data carries the published prices and direction; for given prices without published prices or a direction such hours are priced as balanced and a warning is raised.

Examples:

>>> calculate_imbalance_prices("2026-10-01", "2026-10-07", eptr=eptr)
>>> calculate_imbalance_prices(prices=[
...     {"date": "2026-11-01T00:00:00+03:00", "mcp": 120, "smp": 130,
...      "system_direction": -1}], kupst_category="Rüzgar")

calculate_imbalance_costs

calculate_imbalance_costs(data: DataFrame | list[dict] | None = None, actual: float | None = None, forecast: float | None = None, date: str | datetime | None = None, category: str = 'other', is_producer: bool = True, prices: DataFrame | list[dict] | None = None, eptr: EPTR2 | None = None, include_maintenance_penalty: bool = False, return_df: bool = True, **kwargs: float) -> DataFrame | list[dict]

Imbalance and KUPST costs of actual vs forecast quantities, with every price and regulation parameter pulled automatically.

The hours of data define the range; calculate_imbalance_prices supplies the hourly prices, unit costs and parameters (fetched from EPİAŞ unless prices is given). Published imbalance prices are used where available, calculated ones otherwise (see imb_price_source). KUPST tolerance and multiplier follow each row's category and date.

forecast is the plan the costs are measured against, so the choice of plan sets the question being answered:

  • KUDÜP approximates the settled values. Settlement measures KÜPSM against BUDÜP = KUDÜP + YAL - YAT + SRDM + SFHM (EPDK Decisions 14029 and 14907, Article 1). Plant-level YAL/YAT are not available from the Transparency Platform, so they are taken as 0 and BUDÜP = KUDÜP.
  • KGÜP v1 (the day-ahead plan) answers "what if the day-ahead plan had not changed": the costs had the plant not updated its plan intraday.

Parameters:

Name Type Description Default
data DataFrame | list[dict] | None

Hourly quantities as a DataFrame or list of dicts with 'date' (or 'contract'), 'actual' and 'forecast' in MWh. Optional per row columns 'category' (or 'source') and 'is_producer' override the function arguments, so a portfolio can mix plant types.

None
actual float | None

Actual quantity (MWh) of a single hour instead of data.

None
forecast float | None

Forecast quantity (MWh) of that hour.

None
date str | datetime | None

Date, datetime or contract of that hour.

None
category str

KUPST category or source name in any common convention (e.g. 'wind', 'Rüzgar', 'GES', 'Müstakil depolama'), see normalize_kupst_category.

'other'
is_producer bool

Production (True) or consumption (False) unit. KUPST applies to producers, and to consumption units from 2027-01-01: 'consumption_art17' (withdrawal units of DUY Art. 17(2) (a)-(ç), tolerance 0.75) or 'consumption_other' (0.30), see kupst_applies. A consumption category makes the row a consumer; a consumer with any other category is 'consumption_other'.

True
prices DataFrame | list[dict] | None

Hourly prices passed to calculate_imbalance_prices. Fetched from EPİAŞ if None.

None
eptr EPTR2 | None

EPTR2 client for fetching.

None
include_maintenance_penalty bool

Use the KUPST maintenance multiplier.

False
return_df bool

Return a pandas DataFrame if pandas is installed.

True
**kwargs float

Parameter overrides passed to calculate_imbalance_prices.

{}

Returns:

Type Description
DataFrame | list[dict]

One row per input row with the input columns and contract, category,

DataFrame | list[dict]

is_producer, mcp, smp, system_direction, pos_imb_price, neg_imb_price,

DataFrame | list[dict]

imb_price_source, imb_qty (positive surplus, negative deficit), unit_imb_cost, imb_cost,

DataFrame | list[dict]

kupst_tolerance, kupsm, unit_kupst_cost, kupst_cost (0 where KUPST

DataFrame | list[dict]

does not apply) and total_cost, in TL.

Notes

Imbalance is the raw deviation of the unit; balancing group (DSG) tolerance and netting are not applied.

Rules of the KÜPST decisions (14029, 14907) that are not modelled: from 2026-11-01 the deviation is |(UEVM - UEÇM) - BUDÜP|, i.e. net of the unit's withdrawals, so pass net quantities for units that both inject and withdraw; unlicensed plants are assessed on generation only (14907 Art. 1(3)); distribution-connected unlicensed plants are assessed per participant, so pass the participant's aggregate; and 14907 does not apply to the transmission-connected plants of Art. 5(1)(ç), (d), (e) of the unlicensed generation regulation (14907 Art. 5).

Examples:

>>> calculate_imbalance_costs(
...     actual=80, forecast=100, date="2026-11-01T10:00:00+03:00",
...     category="Rüzgar", eptr=eptr)

normalize_kupst_category

normalize_kupst_category(name: str | None, strict: bool = False) -> str

Map a source or category name in any common naming convention to one of KUPST_CATEGORIES.

Matching ignores case, Turkish characters and separators: Turkish characters are folded to ASCII (ı/İ -> i, ş -> s, ğ -> g, ü -> u, ö -> o, ç -> c), so 'Rüzgar', 'ruzgar' and 'RUZGAR' are the same. 'RES', 'wind', 'Güneş', 'GES', 'PV', 'Depolamalı üretim tesisi', 'wind + battery', 'Müstakil depolama', 'BESS', 'İletime bağlı lisanssız', 'Dağıtıma bağlı lisanssız', 'unlicensed', 'HES', 'doğalgaz' all resolve.

Rules, in order: an exact category name or alias; unlicensed (distribution if a distribution keyword is present, transmission otherwise); consumption (consumption_art17 with '17' in the name, consumption_other otherwise); battery (plant_w_battery if it is a generation plant with storage, battery if it is standalone storage); wind; solar; other renewables (hydro, geothermal, biomass, ...); other sources.

other_renewable exists because EPDK Decisions 14029 and 14907 set the maintenance fault threshold for renewable sources (30) and other sources (25), while hydro, geothermal and biomass share the tolerance of other sources. Renewable follows Law 5346 Art. 3.

Storage cases differ in the EPDK decisions (14029 and 14907): a plant with storage ("depolamalı elektrik üretim tesisi") is plant_w_battery (tolerance 0.05, multiplier 0.10); standalone storage ("müstakil depolama") is battery (its own row from 2026-11-01, 'other' before); a generation plant with an integrated storage unit ("bütünleşik depolama ünitesi") uses its main source's tolerance (Article 3(3)), so pass the main source (e.g. 'wind') for it. Names such as 'RES+BESS' cannot tell the last two apart and resolve to plant_w_battery.

Parameters:

Name Type Description Default
name str | None

Source or category name. None gives 'other'.

required
strict bool

If True, raise ValueError for names that match no rule instead of returning 'other'.

False

Returns:

Name Type Description
str str

One of KUPST_CATEGORIES.

get_regulation_params

get_regulation_params(regulation_period: str = 'current', contract: str | None = None) -> dict | None

Regulation parameter row for a contract or a regulation period.

Parameters:

Name Type Description Default
regulation_period str

'current' (the newest row, also when it starts in the future), a period label such as '26_01' or '26_02', or 'pre_2026'. Ignored if contract is given.

'current'
contract str | None

Contract code 'PHYYMMDDhh'; its delivery hour picks the row.

None

Returns:

Type Description
dict | None

dict or None: the row (see get_time_regulation_params_map), or None for

dict | None

pre-2026, which is not parameterized by the map.

Mapping Utilities

eptr2.mapping

Utilities for API endpoint mapping and discovery.

from eptr2.mapping import (
    get_path_map,
    alias_to_path,
    get_alias_map,
)

get_path_map

Returns the complete mapping of API endpoint paths.

from eptr2.mapping import get_path_map

# Get all path keys
paths = get_path_map(just_call_keys=True)
print(len(paths))  # 236

alias_to_path

Converts an alias to its canonical path.

from eptr2.mapping import alias_to_path

path = alias_to_path("ptf")
print(path)  # "mcp"

get_alias_map

Returns dictionary of all aliases.

from eptr2.mapping import get_alias_map

aliases = get_alias_map()
# {'ptf': 'mcp', 'smf': 'smp', ...}

eptr2.mapping.help

Help and documentation utilities.

from eptr2.mapping.help import get_help_d

get_help_d

Get documentation for an API endpoint.

from eptr2.mapping.help import get_help_d

# Get help for specific call
help_info = get_help_d("mcp")
print(help_info['category'])     # "GÖP"
print(help_info['title']['en'])  # "Market Clearing Price"
print(help_info['desc']['en'])   # Description
print(help_info['url'])          # Official docs URL

# Get all help entries
all_help = get_help_d()

Returns:

Key Type Description
category str Market category (GÖP, GİP, etc.)
title dict Titles in tr and en
desc dict Descriptions in tr and en
url str Link to official documentation

Processing Utilities

eptr2.processing.preprocess

Preprocessing utilities for API parameters.

from eptr2.processing.preprocess import preprocess_parameter

These utilities are primarily used internally by the EPTR2 class.

Examples

Finding API Endpoints

from eptr2.mapping import get_path_map, alias_to_path

# List all endpoints
all_endpoints = get_path_map(just_call_keys=True)

# Find price-related endpoints
price_endpoints = [e for e in all_endpoints if 'price' in e.lower()]
print(price_endpoints)

# Check if alias exists
canonical = alias_to_path("ptf")
print(f"'ptf' maps to '{canonical}'")

Getting API Documentation

from eptr2.mapping.help import get_help_d

# Get documentation for consumption endpoint
help_info = get_help_d("rt-consumption")

print(f"Category: {help_info['category']}")
print(f"Title (TR): {help_info['title']['tr']}")
print(f"Title (EN): {help_info['title']['en']}")
print(f"Description: {help_info['desc']['en']}")

Working with Contract Symbols

from eptr2.util.time import iso_to_contract

# Convert timestamps to contract symbols
timestamps = [
    "2024-07-29T00:00:00+03:00",
    "2024-07-29T12:00:00+03:00",
    "2024-07-29T23:00:00+03:00",
]

for ts in timestamps:
    contract = iso_to_contract(ts)
    print(f"{ts} -> {contract}")

See Also