Skip to content

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
def 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.
    """

    if eptr is None:
        eptr = EPTR2(dotenv_path=kwargs.get("dotenv_path", ".env"))

    ## Transient handshake/read timeouts are exactly what retries exist for;
    ## without them a single slow response fails the whole composite.
    retry_kwargs = {
        "retry_attempts": kwargs.get("max_lives", DEFAULT_COMPOSITE_RETRIES),
        "retry_backoff": kwargs.get("retry_backoff", DEFAULT_COMPOSITE_BACKOFF),
        "retry_backoff_max": kwargs.get("retry_backoff_max", DEFAULT_COMPOSITE_BACKOFF),
        "retry_jitter": 0.0,
    }


    if verbose:
        logger.info("Loading load plan...")

    lp_df = eptr.call(
        "load-plan",
        start_date=start_date,
        end_date=end_date,
        request_kwargs={"timeout": DEFAULT_COMPOSITE_TIMEOUT},
        **retry_kwargs,
    )

    df = lp_df[["date", "lep"]].rename(columns={"lep": "load_plan", "date": "dt"})

    if verbose:
        logger.info("Loading UECM...")

    uecm_df: pd.DataFrame = eptr.call(
        "uecm", start_date=start_date, end_date=end_date, request_kwargs={"timeout": DEFAULT_COMPOSITE_TIMEOUT}, **retry_kwargs
    )

    if not uecm_df.empty:
        uecm_df = uecm_df[["period", "swv"]].rename(
            columns={"period": "dt", "swv": "uecm"}
        )

        df = df.merge(
            uecm_df,
            on="dt",
            how="outer",
        )

    if verbose:
        logger.info("Loading real time consumption...")

    rt_cons = eptr.call(
        "rt-cons",
        start_date=start_date,
        end_date=end_date,
        request_kwargs={"timeout": DEFAULT_COMPOSITE_TIMEOUT},
        **retry_kwargs,
    )

    df = df.merge(
        rt_cons[["date", "consumption"]].rename(
            columns={"date": "dt", "consumption": "rt_cons"}
        ),
        on="dt",
        how="outer",
    )

    if not uecm_df.empty:
        df["consumption"] = df.apply(
            lambda x: x["rt_cons"] if pd.isnull(x["uecm"]) else x["uecm"], axis=1
        )
    else:
        df["consumption"] = df["rt_cons"].copy()

    if include_contract_symbol:
        try:
            df["contract"] = df["dt"].apply(lambda x: iso_to_contract(x))
        except Exception as e:
            logger.warning("Contract information could not be added. Error: %s", e)

    return df

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
def 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)
    """

    if eptr is None:
        eptr = EPTR2(dotenv_path=kwargs.get("dotenv_path", ".env"))

    retry_kwargs = {
        "retry_attempts": kwargs.get("max_lives", DEFAULT_COMPOSITE_RETRIES),
        "retry_backoff": kwargs.get("retry_backoff", DEFAULT_COMPOSITE_BACKOFF),
        "retry_backoff_max": kwargs.get("retry_backoff_max", DEFAULT_COMPOSITE_BACKOFF),
        "retry_jitter": 0.0,
    }

    if verbose:
        logger.info("Getting MCP, SMP and imbalance price data...")

    ## One row per hour: EPİAŞ returned every hour of 2026-11-01 twice
    price_df = eptr.call(
        "mcp-smp-imb",
        start_date=start_date,
        end_date=end_date,
        request_kwargs={"timeout": timeout},
        drop_duplicates=True,
        **retry_kwargs,
    )

    price_df.drop(columns=["time"], inplace=True)

    price_df.rename(
        columns={
            "ptf": "mcp",
            "smf": "smp",
            "positiveImbalance": "pos_imb_price",
            "negativeImbalance": "neg_imb_price",
            "systemStatus": "system_direction",
        },
        inplace=True,
    )

    price_df["sd_sign"] = price_df["system_direction"].apply(
        lambda x: -1 if x == "Enerji Açığı" else 1 if x == "Enerji Fazlası" else 0
    )

    price_df["pos_imb_cost"] = price_df["mcp"] - price_df["pos_imb_price"]
    price_df["neg_imb_cost"] = price_df["neg_imb_price"] - price_df["mcp"]

    if include_wap:
        if verbose:
            logger.info("Getting WAP data...")

        wap_df = eptr.call(
            "wap",
            start_date=start_date,
            end_date=end_date,
            request_kwargs={"timeout": timeout},
            **retry_kwargs,
        )
        wap_df.drop(columns=["hour"], inplace=True)

        price_df = price_df.merge(wap_df, on="date", how="outer")

    if include_contract_symbol or add_kupst_cost:
        try:
            price_df["contract"] = price_df["date"].apply(lambda x: iso_to_contract(x))
        except Exception as e:
            logger.warning("Contract information could not be added. Error: %s", e)

    if add_kupst_cost:
        if verbose:
            logger.info("Calculating unit KUPST cost...")

        added_params = {
            k: v
            for k, v in kwargs.items()
            if k
            in [
                "kupst_multiplier",
                "kupst_floor_price",
                "include_maintenance_penalty",
            ]
        }
        ## KUPST multipliers depend on the KUPST category (e.g. 'wind',
        ## 'plant_w_battery') from 2026-11-01. Default is 'other'.
        if kwargs.get("kupst_category") is not None:
            added_params["category"] = kwargs["kupst_category"]

        price_df["kupst_cost"] = price_df.apply(
            lambda x: calculate_unit_kupst_cost_by_contract(
                contract=x["contract"],
                mcp=x["mcp"],
                smp=x["smp"],
                **added_params,
            ),
            axis=1,
        )

        if not include_contract_symbol:
            price_df.drop(columns=["contract"], inplace=True)

    ### Column ordering
    columns_order = [
        "date",
        "contract",
        "pos_imb_vol",
        "neg_imb_vol",
        "pos_imb_mwh",
        "neg_imb_mwh",
        "mcp",
        "wap",
        "smp",
        "pos_imb_price",
        "neg_imb_price",
        "system_direction",
        "sd_sign",
        "pos_imb_cost",
        "neg_imb_cost",
        "kupst_cost",
    ]

    if add_unit_prefix_to_cost_colnames:
        cost_cols_mapping = {
            "pos_imb_cost": "unit_pos_imb_cost",
            "neg_imb_cost": "unit_neg_imb_cost",
            "kupst_cost": "unit_kupst_cost",
        }
        price_df.rename(columns=cost_cols_mapping, inplace=True)
        for old_col, new_col in cost_cols_mapping.items():
            if old_col in columns_order:
                columns_order.remove(old_col)
                columns_order.append(new_col)

    columns_order = [col for col in columns_order if col in price_df.columns]

    price_df = price_df[columns_order]

    return price_df

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
def 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
    """

    if eptr is None:
        eptr = EPTR2(dotenv_path=kwargs.get("dotenv_path", ".env"))

    max_trials = kwargs.get("max_trials", DEFAULT_COMPOSITE_RETRIES)
    timeout = kwargs.get("timeout", DEFAULT_COMPOSITE_TIMEOUT)
    sleep_interval = kwargs.get("sleep_interval", DEFAULT_COMPOSITE_BACKOFF)
    retry_kwargs = {
        "retry_attempts": max_trials,
        "retry_backoff": sleep_interval,
        "retry_backoff_max": sleep_interval,
        "retry_jitter": 0.0,
    }

    ## A missing plant id means "no plant filter", not "skip this source":
    ## rt-gen and uevm both return system-wide totals without one. Only skip
    ## the other source when exactly one plant is requested, so plant-level and
    ## system-wide figures are never merged into the same frame. Explicit
    ## skip_rt / skip_uevm always win.
    if rt_pp_id is None and uevm_pp_id is not None:
        skip_rt = True
    if uevm_pp_id is None and rt_pp_id is not None:
        skip_uevm = True

    #### SANITY CHECKS ####
    if skip_rt and skip_uevm:
        raise ValueError("Both skip_rt and skip_uevm cannot be True.")

    #### REAL TIME GENERATION PHASE ####
    if skip_rt:
        rt_included = False
        rt_gen_df = pd.DataFrame()

    else:
        rt_included = True
        if verbose:
            logger.info("Loading real time production data...")

        rt_gen_df: pd.DataFrame = eptr.call(
            "rt-gen",
            start_date=start_date,
            end_date=end_date,
            pp_id=rt_pp_id,
            request_kwargs={"timeout": timeout},
            **retry_kwargs,
        )

        if rt_gen_df.empty:
            raise ValueError("No data (production) is available for this date range.")

        try:
            rt_gen_df.drop("hour", axis=1, inplace=True)
        except Exception as e:
            if verbose:
                logger.info("%s", e)

        rt_gen_df.columns = [
            x + "_rt" if x not in ["date"] else x for x in rt_gen_df.columns
        ]

    #### UEVM PHASE ####
    if skip_uevm:
        uevm_included = False
        uevm_df = pd.DataFrame()

    else:
        uevm_included = True
        if verbose:
            logger.info("Loading UEVM data...")

        uevm_df: pd.DataFrame = eptr.call(
            "uevm",
            start_date=start_date,
            end_date=end_date,
            pp_id=uevm_pp_id,
            request_kwargs={"timeout": timeout},
            **retry_kwargs,
        )

        try:
            uevm_df.drop("hour", axis=1, inplace=True)
        except Exception as e:
            within_settlement = check_date_for_settlement(x=end_date)
            if not within_settlement:
                logger.warning("The end date may not be within the settlement period.")
            if verbose:
                logger.info("%s", e)

        uevm_df.columns = [
            x + "_uevm" if x not in ["date"] else x for x in uevm_df.columns
        ]

    if uevm_included and rt_included:
        if verbose:
            logger.info("Merging data...")

        if uevm_df.empty:
            merged_df = rt_gen_df.copy()
        else:
            merged_df = rt_gen_df.merge(uevm_df, how="left", on=["date"])
    elif uevm_included:
        merged_df = uevm_df.copy()
    elif rt_included:
        merged_df = rt_gen_df.copy()

    if include_contract_symbol:
        try:
            merged_df["contract"] = merged_df["date"].apply(
                lambda x: iso_to_contract(x)
            )
        except Exception as e:
            logger.warning("Contract information could not be added. Error: %s", e)

    merged_df = merged_df.rename(columns={"date": "dt"})

    return merged_df

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
def 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: pd.DataFrame | None = None,
    export_to_csv: bool = True,
    export_dir: str = "data",
    check_existing: bool = True,
    verbose: bool = True,
    **kwargs,
) -> pd.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}_{end_date}.csv: org_{org_id}_positions (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_{org_id}_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.

    Args:
        start_date: Start date in 'YYYY-MM-DD' format
        end_date: End date in 'YYYY-MM-DD' format (inclusive), before today
        org_id: Organization ID
        eptr: EPTR2 object. Created from .env if not provided.
        include_pnl: Add mcp, idm_wap and dabi_idm_pnl (fetches MCP and WAP with get_hourly_price_and_cost_data).
        include_tad: Add idm_mad and day_trade_tad (fetches the IDM trade log). Independent of include_pnl.
        idm_log_df: 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.
        export_to_csv: Write the raw data and the result to export_dir as CSV files (see above). Default True.
        export_dir: Directory of the CSV files, created if missing.
        check_existing: Read the raw data from existing CSV files of the same period in export_dir instead of fetching it.
        verbose: Log each step and each IDM log chunk with row counts and elapsed time (to stderr)

    Returns:
        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.
    """
    today = get_today_utc3()
    if end_date >= today:
        raise ValueError(
            f"end_date must be before today ({today}, Europe/Istanbul): data of the current day is not final. Got end_date={end_date}."
        )

    t_start = time.time()

    def log_step(message, *args):
        if verbose:
            logger.info("[%5.1fs] " + message, time.time() - t_start, *args)

    if export_to_csv:
        os.makedirs(export_dir, exist_ok=True)

    ## Files read with check_existing are not written again
    loaded = set()

    def csv_path(name):
        return os.path.join(export_dir, f"{name}_{start_date}_{end_date}.csv")

    def load_existing(name):
        path = csv_path(name)
        if not (check_existing and os.path.exists(path)):
            return None
        log_step("Reading %s from %s", name, path)
        loaded.add(name)
        return pd.read_csv(path, dtype={"contract": str, "contractName": str})

    def export(df, name):
        if export_to_csv and name not in loaded:
            df.to_csv(csv_path(name), index=False)
            log_step("Wrote %d rows to %s", len(df), csv_path(name))

    if idm_log_df is not None:
        include_tad = True

    if eptr is None:
        eptr = EPTR2(dotenv_path=kwargs.get("dotenv_path", ".env"))

    retry_kwargs = {
        "retry_attempts": kwargs.get("lives", DEFAULT_COMPOSITE_RETRIES),
        "retry_backoff": kwargs.get("retry_backoff", DEFAULT_COMPOSITE_BACKOFF),
        "retry_backoff_max": kwargs.get(
            "retry_backoff_max", kwargs.get("retry_backoff", DEFAULT_COMPOSITE_BACKOFF)
        ),
        "retry_jitter": kwargs.get("retry_jitter", 0.0),
    }

    log_step(
        "Getting GÖP, İA and GİP matchings of organization %s for %s to %s...",
        org_id,
        start_date,
        end_date,
    )
    pos_name = f"org_{org_id}_positions"
    pos_df = load_existing(pos_name)
    if pos_df is None:
        pos_df = get_dabi_idm_data(
            start_date=start_date,
            end_date=end_date,
            eptr=eptr,
            org_id=org_id,
            verbose=verbose,
            **kwargs,
        )
    log_step("Got matchings for %d hour(s).", len(pos_df))
    export(pos_df, pos_name)

    ## All hourly contracts of the period, so that missing rows of any source do not drop contracts
    df = pd.DataFrame(
        {
            "contract": get_hourly_contract_range_list(
                start_date=start_date, end_date=end_date
            )
        }
    )
    pos_cols = ["contract", "date"] + [
        c for c in QUANTITY_COLUMNS if c in pos_df.columns
    ]
    df = df.merge(pos_df[pos_cols], on="contract", how="left")
    for col in QUANTITY_COLUMNS:
        if col not in df.columns:
            df[col] = 0.0
        df[col] = df[col].fillna(0.0)

    if include_pnl:
        price_df = load_existing("prices")
        if price_df is None:
            log_step("Getting MCP, SMP and intraday WAP...")
            price_df = get_hourly_price_and_cost_data(
                start_date=start_date,
                end_date=end_date,
                eptr=eptr,
                include_wap=True,
                add_kupst_cost=False,
                include_contract_symbol=True,
                timeout=DEFAULT_COMPOSITE_TIMEOUT,
                max_lives=retry_kwargs["retry_attempts"],
                retry_backoff=retry_kwargs["retry_backoff"],
                retry_backoff_max=retry_kwargs["retry_backoff_max"],
            )
        export(price_df, "prices")

        ## Missing prices stay NaN so that PnL is not silently zeroed
        df = df.merge(
            price_df[["contract", "mcp", "wap"]].rename(columns={"wap": "idm_wap"}),
            on="contract",
            how="left",
        )

        if df["idm_wap"].isna().any():
            logger.warning(
                "IDM WAP is missing for %d contract(s), their intraday PnL is NaN.",
                int(df["idm_wap"].isna().sum()),
            )

    if include_tad:
        log_step("Getting IDM contract statistics (MAD) from the market wide trade log...")
        ## idm_log_longer fetches wide ranges in chunks of days_interval (+1) days
        log_kwargs = (
            {"days_interval": kwargs["idm_log_days_interval"]}
            if "idm_log_days_interval" in kwargs
            else {}
        )
        stats_df = get_idm_contract_stats(
            start_date=start_date,
            end_date=end_date,
            eptr=eptr,
            idm_log_df=idm_log_df,
            export_to_csv=export_to_csv,
            export_dir=export_dir,
            check_existing=check_existing,
            verbose=verbose,
            **log_kwargs,
        )
        log_step("Got statistics of %d contract(s).", len(stats_df))
        df = df.merge(stats_df[["contract", "idm_mad"]], on="contract", how="left")

    df = calculate_org_activity(df)
    df["org_id"] = org_id
    export(df, f"org_{org_id}_activity")
    log_step("Done.")

    return df

calculate_org_activity

calculate_org_activity(df: DataFrame) -> DataFrame

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
def get_idm_contract_stats(
    start_date: str,
    end_date: str,
    eptr: EPTR2 | None = None,
    idm_log_df: pd.DataFrame | None = None,
    export_to_csv: bool = True,
    export_dir: str = "data",
    check_existing: bool = True,
    verbose: bool = False,
    **kwargs: Any,
) -> pd.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_{start_date}_{end_date}.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 must be before today (Europe/Istanbul): the log of the current day is not final, so neither are the statistics or the files.

    Args:
        start_date: Start date in 'YYYY-MM-DD' format
        end_date: End date in 'YYYY-MM-DD' format (inclusive), before today
        eptr: EPTR2 object. Created from .env if needed.
        idm_log_df: Previously fetched trade log covering the period (idm_log_longer output). Used instead of the files and the API, and not written to files.
        export_to_csv: Write the log and the statistics to export_dir (files that were read are not written again).
        export_dir: Directory of the CSV files, created if missing.
        check_existing: Read existing files of the same period before fetching.
        verbose: Log each step.
        **kwargs: Passed to idm_log_longer (e.g. days_interval, timeout).

    Returns:
        pd.DataFrame: One row per hourly contract with the columns above.
    """
    today = get_today_utc3()
    if end_date >= today:
        raise ValueError(
            f"end_date must be before today ({today}, Europe/Istanbul): the trade log of the current day is not final. Got end_date={end_date}."
        )

    def csv_path(name):
        return os.path.join(export_dir, f"{name}_{start_date}_{end_date}.csv")

    stats_path, log_path = csv_path("idm_contract_stats"), csv_path("idm_log")

    ## A trade log passed in by the caller is used as is and never cached: it
    ## may cover a different or partial period
    caller_log = idm_log_df is not None

    if not caller_log and check_existing and os.path.exists(stats_path):
        stats_df = pd.read_csv(stats_path, dtype={"contract": str})
        if not all(c in stats_df.columns for c in IDM_CONTRACT_STATS_COLUMNS):
            ## e.g. files of eptr2 1.4.0, whose idm_tad column was the MAD
            logger.warning(
                "%s does not have the current columns, recalculating it.", stats_path
            )
        elif _missing_days(stats_df["contract"], start_date, end_date):
            logger.warning("%s does not cover every day of the period, recalculating it.", stats_path)
        else:
            if verbose:
                logger.info("Read IDM contract statistics from %s", stats_path)
            return stats_df[IDM_CONTRACT_STATS_COLUMNS]

    log_loaded = False
    if not caller_log and check_existing and os.path.exists(log_path):
        log_df = pd.read_csv(log_path, dtype={"contractName": str})
        if _missing_days(log_df["contractName"], start_date, end_date):
            logger.warning("%s does not cover every day of the period, fetching the log again.", log_path)
        else:
            if verbose:
                logger.info("Reading the IDM trade log from %s", log_path)
            idm_log_df = log_df
            log_loaded = True

    if idm_log_df is None:
        if verbose:
            logger.info(
                "Getting the IDM trade log for %s to %s (market wide, about 20k trades a day)...",
                start_date,
                end_date,
            )
        idm_log_df = idm_log_longer(
            start_date=start_date,
            end_date=end_date,
            eptr=eptr,
            contract_wise=True,
            verbose=verbose,
            **kwargs,
        )

    stats_df = calculate_idm_contract_stats(idm_log_df)

    missing = _missing_days(stats_df["contract"], start_date, end_date)
    if missing and not caller_log:
        logger.warning(
            "The IDM trade log has no hourly contracts for %d day(s) of the period (%s ...); "
            "the files are not written, so the next run fetches it again.",
            len(missing),
            ", ".join(missing[:3]),
        )

    if export_to_csv and not caller_log and not missing:
        os.makedirs(export_dir, exist_ok=True)
        if not log_loaded:
            idm_log_df.to_csv(log_path, index=False)
        stats_df.to_csv(stats_path, index=False)
        if verbose:
            logger.info("Wrote %s and %s", log_path, stats_path)

    return stats_df

calculate_idm_contract_stats

calculate_idm_contract_stats(log_df: DataFrame) -> DataFrame

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:

Loading load plan...
Loading UECM...
Loading real time consumption...

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
)

See Also