Composite Functions¶
The eptr2.composite module provides pre-built functions that combine multiple API calls for common analysis tasks.
Overview¶
Composite functions simplify data retrieval by:
- Combining multiple related API calls
- Merging and transforming data
- Handling missing data gracefully
- Providing consistent output formats
Import¶
from eptr2.composite import (
get_hourly_consumption_and_forecast_data,
get_hourly_price_and_cost_data,
get_hourly_production_data,
get_hourly_production_plan_data,
get_imbalance_data,
)
Function Reference¶
Consumption Functions¶
get_hourly_consumption_and_forecast_data
¶
get_hourly_consumption_and_forecast_data(start_date: str, end_date: str, eptr: EPTR2 | None = None, verbose: bool = False, include_contract_symbol: bool = True, **kwargs)
This composite function gets load plan, UECM (settlement consumption), real time and consumption data. If end date is after the last settlement data, UECM is filled with real time consumption under consumption column.
Source code in src/eptr2/composite/consumption.py
Price Functions¶
get_hourly_price_and_cost_data
¶
get_hourly_price_and_cost_data(start_date: str, end_date: str, eptr: EPTR2 | None = None, include_wap: bool = True, add_kupst_cost: bool = True, verbose: bool = False, include_contract_symbol: bool = True, timeout: int = 10, add_unit_prefix_to_cost_colnames: bool = False, **kwargs)
This composite function gets price and imbalance (kupst included) cost data. Imbalance cost data consists of MCP (PTF), SMP (SMF), system direction (Enerji Açığı - up regulated, Energy Fazlası - down regulated, Dengede - Balanced), positive imbalance cost and negative imbalance cost.
Resulting columns are: - date: Datetime in ISO format and +03:00 timezone - mcp: Market Clearing Price (MCP/PTF) in TL (Turkish Lira) - smp: System Marginal Price (SMP/SMF) in TL (Turkish Lira) - wap: Weighted Average Price (WAP) in TL (Turkish Lira) - system_direction: System direction (Enerji Açığı - up regulated, Energy Fazlası - down regulated, Dengede - Balanced) - sd_sign: System direction sign (1 for Enerji Fazlası, -1 for Enerji Açığı, 0 for Dengede) - pos_imb_price: Positive imbalance price in TL (Turkish Lira) - neg_imb_price: Negative imbalance price in TL (Turkish Lira) (negative value) - pos_imb_cost: Positive imbalance cost in TL (Turkish Lira) (ptf - pos_imb_price) - neg_imb_cost: Negative imbalance cost in TL (Turkish Lira) (neg_imb_price - ptf)
Source code in src/eptr2/composite/price_and_cost.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 | |
Production Functions¶
get_hourly_production_data
¶
get_hourly_production_data(start_date: str, end_date: str, eptr: EPTR2 | None = None, rt_pp_id: str | int | None = None, uevm_pp_id: str | int | None = None, verbose: bool = False, include_contract_symbol: bool = True, skip_uevm: bool = False, skip_rt: bool = False, **kwargs)
This composite function gets production data (Gerçek Zamanlı Üretim, UEVM) and merges them.
It is also possible to enter pp_id to get the production data for a specific production plan. Example ID values are given below.
rt_pp_id=641, ## ATATÜRK HES uevm_pp_id=142, ## ATATÜRK HES
Source code in src/eptr2/composite/production.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | |
Organization Activity Functions¶
get_org_estimated_activity
¶
get_org_estimated_activity(start_date: str, end_date: str, org_id: str | int, eptr: EPTR2 | None = None, include_pnl: bool = False, include_tad: bool = False, idm_log_df: DataFrame | None = None, export_to_csv: bool = True, export_dir: str = 'data', check_existing: bool = True, verbose: bool = True, **kwargs) -> DataFrame
Estimates an organization's (company's) trading activity for the given period (start_date and end_date inclusive) on an hourly contract basis.
The activity comes from the organization's own matched quantities only: day ahead (GÖP), bilateral (İA) and intraday (GİP) matchings by organization id (get_dabi_idm_data, a few seconds per week). See calculate_org_activity for the decomposition (day ahead open / intraday close, day trade, dabi_net and dabi_idm_net net positions).
With include_pnl=True a fictitious PnL of day ahead open / intraday close trades is added from MCP and the published intraday WAP (get_hourly_price_and_cost_data, fast).
With include_tad=True the MAD (mean absolute deviation, TL/MWh) of each contract (idm_mad) and day_trade_tad = day_trade * idm_mad, the TAD (total absolute deviation, TL) of the day trade volume, are added. These are volatility metrics, not PnL. MAD comes from get_idm_contract_stats, calculated from the market wide intraday trade log (idm_log_longer), which is large (about 20k trades a day), so this is much slower. The log is fetched in multi-day chunks by idm_log_longer; pass idm_log_days_interval to change the chunk length (days_interval of idm_log_longer).
By default (export_to_csv=True, check_existing=True) the raw data and the result are written to export_dir as CSV files named {name}{start_date}}.csv: org_{org_idpositions (get_dabi_idm_data output), prices (get_hourly_price_and_cost_data output: MCP, SMP, WAP and imbalance prices per hour), idm_log (the market wide trade log), idm_contract_stats (per contract WAP, MAD, trade count and volume from the log) and org_activity (the returned frame). Only the data of the requested steps is written. With check_existing=True, files of the same name (same period) are read from export_dir instead of being fetched, so the market wide files (prices, idm_log, idm_contract_stats) are recycled for other organizations of the same period and nothing is fetched twice. Pass export_to_csv=False to write nothing. CSV is used because the trade log can exceed the Excel row limit.
end_date must be before today (Europe/Istanbul): data of the current day is not final, so neither the result nor the exported files would be.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start_date
|
str
|
Start date in 'YYYY-MM-DD' format |
required |
end_date
|
str
|
End date in 'YYYY-MM-DD' format (inclusive), before today |
required |
org_id
|
str | int
|
Organization ID |
required |
eptr
|
EPTR2 | None
|
EPTR2 object. Created from .env if not provided. |
None
|
include_pnl
|
bool
|
Add mcp, idm_wap and dabi_idm_pnl (fetches MCP and WAP with get_hourly_price_and_cost_data). |
False
|
include_tad
|
bool
|
Add idm_mad and day_trade_tad (fetches the IDM trade log). Independent of include_pnl. |
False
|
idm_log_df
|
DataFrame | None
|
Previously fetched IDM trade log covering the period (e.g. idm_log_longer output). The log is market wide, so it can be reused for several organizations to avoid fetching it again. Implies include_tad=True. |
None
|
export_to_csv
|
bool
|
Write the raw data and the result to export_dir as CSV files (see above). Default True. |
True
|
export_dir
|
str
|
Directory of the CSV files, created if missing. |
'data'
|
check_existing
|
bool
|
Read the raw data from existing CSV files of the same period in export_dir instead of fetching it. |
True
|
verbose
|
bool
|
Log each step and each IDM log chunk with row counts and elapsed time (to stderr) |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: One row per hourly contract with quantity and decomposition columns, and the price, PnL, MAD and TAD columns that were requested. Prices (mcp, idm_wap, idm_mad) are left NaN if they could not be retrieved, they are not filled with 0. |
Source code in src/eptr2/composite/org_activity.py
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 | |
calculate_org_activity
¶
Decomposes an organization's hourly positions into day ahead / intraday trades, day trades and net positions and, if prices are given, adds a fictitious (estimated) PnL.
Required columns: da_long, da_short, idm_long, idm_short. Optional columns: bi_long, bi_short (taken as 0 if missing); mcp and idm_wap (add dabi_idm_pnl); idm_mad (adds day_trade_tad).
Added columns (all quantities in MWh, positive is buy / long): da_net: da_long - da_short bi_net: bi_long - bi_short dabi_net: da_net + bi_net. Day ahead (GÖP + İA) net position. idm_net: idm_long - idm_short dabi_idm_net: dabi_net + idm_net. Net quantity that shall either be consumed (positive, net buyer) or generated (negative, net seller). Subtract bi_net for the organized market (GÖP + GİP) only part. day_trade: min(idm_long, idm_short). Intraday quantity bought and sold back within the intraday market. dabi_idm_close: Day ahead (GÖP + İA) position closed (reversed) in the intraday market. min(|dabi_net|, |idm_net|) if dabi_net and idm_net have opposite signs, otherwise 0. Always non-negative, direction follows dabi_net. dabi_idm_pnl: Fictitious PnL of day ahead open / intraday close trades. dabi_idm_close * sign(dabi_net) * (idm_wap - mcp). Buying day ahead and selling in IDM gains when idm_wap > mcp, the reverse for selling day ahead. Bilateral quantities are valued at mcp as well. day_trade_tad: Only with idm_mad. day_trade * idm_mad (TL): the TAD (total absolute deviation) of the day trade volume, the price room around WAP it was traded in. A volatility metric, not a PnL. It is one sided by definition (not 2 * day_trade * idm_mad for a buy and a sell around WAP).
The PnL is an estimate: actual trade prices of the organization are not public, so intraday trades are assumed to be at idm_wap. If a price is missing, the related PnL is NaN.
Intraday Statistics Functions¶
get_idm_contract_stats
¶
get_idm_contract_stats(start_date: str, end_date: str, eptr: EPTR2 | None = None, idm_log_df: DataFrame | None = None, export_to_csv: bool = True, export_dir: str = 'data', check_existing: bool = True, verbose: bool = False, **kwargs: Any) -> DataFrame
Market wide intraday (GİP) statistics per hourly contract for the given period (start_date and end_date inclusive), from the IDM trade log: idm_wap, idm_mad (MAD, mean absolute deviation, TL/MWh), idm_tad (TAD, total absolute deviation, TL), idm_trade_count and idm_volume_mwh. See calculate_idm_contract_stats.
The trade log is large (about 20k trades a day) and slow to fetch (roughly 30-70 s per week, depending on EPİAŞ), so by default the results are kept in files: idm_log_{start_date}{end_date}.csv (the log, idm_log_longer output) and idm_contract_stats.csv in export_dir. With check_existing=True (default) the statistics file is read if it exists, otherwise the log file, and only then is the log fetched. get_org_estimated_activity uses the same files. A log or statistics that misses days of the period (e.g. a failed request inside idm_log_longer) is not written, and such files are not read back.}_{end_date
end_date must be before today (Europe/Istanbul): the log of the current day is not final, so neither are the statistics or the files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start_date
|
str
|
Start date in 'YYYY-MM-DD' format |
required |
end_date
|
str
|
End date in 'YYYY-MM-DD' format (inclusive), before today |
required |
eptr
|
EPTR2 | None
|
EPTR2 object. Created from .env if needed. |
None
|
idm_log_df
|
DataFrame | None
|
Previously fetched trade log covering the period (idm_log_longer output). Used instead of the files and the API, and not written to files. |
None
|
export_to_csv
|
bool
|
Write the log and the statistics to export_dir (files that were read are not written again). |
True
|
export_dir
|
str
|
Directory of the CSV files, created if missing. |
'data'
|
check_existing
|
bool
|
Read existing files of the same period before fetching. |
True
|
verbose
|
bool
|
Log each step. |
False
|
**kwargs
|
Any
|
Passed to idm_log_longer (e.g. days_interval, timeout). |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: One row per hourly contract with the columns above. |
Source code in src/eptr2/composite/idm_log.py
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 | |
calculate_idm_contract_stats
¶
Calculates per contract intraday statistics from the IDM trade log (idm-log or idm_log_longer output).
Returns a DataFrame with columns
contract: Hourly contract name (PHyyMMddhh) idm_wap: Weighted average price of all trades in the contract idm_mad: MAD (mean absolute deviation, TL/MWh), a volatility metric. Quantity weighted average of |price - idm_wap| over all trades in the contract idm_tad: TAD (total absolute deviation, TL) of the contract: sum of |price - idm_wap| * quantity over all trades, i.e. idm_mad * idm_volume_mwh idm_trade_count: Number of trades idm_volume_mwh: Total traded quantity in MWh (log quantities are lots of 0.1 MWh)
Only hourly (PH) contracts are taken into account.
Quick Reference¶
get_hourly_consumption_and_forecast_data¶
Combines load plan, UECM, and real-time consumption data.
from eptr2.composite import get_hourly_consumption_and_forecast_data
df = get_hourly_consumption_and_forecast_data(
start_date="2024-07-01",
end_date="2024-07-31",
verbose=True
)
Returns:
| Column | Type | Description |
|---|---|---|
dt |
datetime | Timestamp |
load_plan |
float | Load plan forecast (MWh) |
uecm |
float | Settlement consumption (MWh) |
rt_cons |
float | Real-time consumption (MWh) |
consumption |
float | Best available consumption |
get_hourly_price_and_cost_data¶
Combines MCP, SMP, and imbalance price data.
from eptr2.composite import get_hourly_price_and_cost_data
df = get_hourly_price_and_cost_data(
start_date="2024-07-01",
end_date="2024-07-31"
)
Returns:
| Column | Type | Description |
|---|---|---|
dt |
datetime | Timestamp |
mcp |
float | Market Clearing Price (TL/MWh) |
smp |
float | System Marginal Price (TL/MWh) |
positive_imbalance |
float | Positive imbalance price |
negative_imbalance |
float | Negative imbalance price |
get_hourly_production_data¶
Retrieves hourly production data by source.
from eptr2.composite import get_hourly_production_data
df = get_hourly_production_data(
start_date="2024-07-01",
end_date="2024-07-31"
)
get_imbalance_data¶
Retrieves imbalance-related data for cost calculations.
from eptr2.composite import get_imbalance_data
df = get_imbalance_data(
start_date="2024-07-01",
end_date="2024-07-31"
)
Common Parameters¶
All composite functions share these parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
start_date |
str |
Required | Start date (YYYY-MM-DD) |
end_date |
str |
Required | End date (YYYY-MM-DD) |
eptr |
EPTR2 |
None |
EPTR2 instance (created if not provided) |
verbose |
bool |
False |
Print progress messages |
**kwargs |
- | - | Additional parameters |
Examples¶
Complete Analysis Pipeline¶
from eptr2 import EPTR2
from eptr2.composite import (
get_hourly_consumption_and_forecast_data,
get_hourly_price_and_cost_data
)
import pandas as pd
# Initialize once
eptr = EPTR2(use_dotenv=True, recycle_tgt=True)
# Get consumption data
consumption = get_hourly_consumption_and_forecast_data(
start_date="2024-07-01",
end_date="2024-07-31",
eptr=eptr,
verbose=True
)
# Get price data
prices = get_hourly_price_and_cost_data(
start_date="2024-07-01",
end_date="2024-07-31",
eptr=eptr
)
# Merge for analysis
analysis = pd.merge(consumption, prices, on='dt')
# Calculate costs
analysis['total_cost'] = analysis['consumption'] * analysis['mcp']
print(f"Total cost: {analysis['total_cost'].sum():,.2f} TL")
With Verbose Output¶
df = get_hourly_consumption_and_forecast_data(
start_date="2024-07-01",
end_date="2024-07-31",
verbose=True
)
Output:
Using Custom EPTR2 Instance¶
from eptr2 import EPTR2
from eptr2.composite import get_hourly_consumption_and_forecast_data
# Custom configuration
eptr = EPTR2(
use_dotenv=True,
recycle_tgt=True,
tgt_path="/custom/path"
)
df = get_hourly_consumption_and_forecast_data(
start_date="2024-07-01",
end_date="2024-07-31",
eptr=eptr
)