import os
from datetime import datetime, timedelta
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.ticker import MultipleLocator
from reportlab.lib.pagesizes import landscape, A4
from reportlab.pdfgen import canvas
from reportlab.lib.colors import HexColor
from PIL import Image # Importowane w draw_full_page_chart
# ==============================
# KONFIGURACJA I STAŁE
# ==============================
class Config:
"""Centralizacja ustawień konfiguracyjnych."""
EXCEL_PATH = r"T:\Departament Zarządzania Portfelem (HP)\BIURO ANALIZ RYNKOWYCH (HPA)\RAPORTY BIURA ANALIZ RYNKOWYCH\RAPORTY DOBOWE\RAPORT DZIENNY\RAPORT\test_nowe_raporty\Dane-ee.xlsm"
LOGO_PATH = r"T:\Departament Zarządzania Portfelem (HP)\BIURO ANALIZ RYNKOWYCH (HPA)\RAPORTY BIURA ANALIZ RYNKOWYCH\RAPORTY DOBOWE\RAPORT DZIENNY\RAPORT\test_nowe_raporty\logo_enei_rgb.png"
OUTPUT_DIR = r"T:\Departament Zarządzania Portfelem (HP)\BIURO ANALIZ RYNKOWYCH (HPA)\RAPORTY BIURA ANALIZ RYNKOWYCH\RAPORTY DOBOWE\RAPORT DZIENNY\RAPORT\test_nowe_raporty"
TODAY_STR = datetime.today().strftime("%Y-%m-%d")
PDF_FILENAME = f"Raport dobowy - rynek energii {TODAY_STR}.pdf"
PDF_PATH = os.path.join(OUTPUT_DIR, PDF_FILENAME)
# Parametry strony PDF
PAGE_SIZE = landscape(A4)
PAGE_WIDTH, PAGE_HEIGHT = PAGE_SIZE
LOGO_WIDTH, LOGO_HEIGHT = 120, 60
# Marginesy i layout
MARGIN_LEFT = 40
MARGIN_RIGHT = 40
MARGIN_TOP = 80
MARGIN_BOTTOM = 50
FOOTER_TEXT = "ENEA Trading Sp. z o.o./Departament Analiz i Zarzadzania Portfelem"
# Konfiguracja wykresów
CHART_CONFIGS = [
# Wykresy dla Y-26 (strona 3)
{
"sheet": "B_Y",
"title": "BASE Y-26 k=365",
"color": "#1E90FF",
"days": 365,
"output": "chart_base_y26_365.png",
"ltd_sheet": "B_Y",
"last_sheet": "B_Y",
"mw_sheet": "B_Y",
"units": {
"ltd": "PLN",
"last": "MW",
"mw": "PLN/MWh"
}
},
{
"sheet": "P_Y",
"title": "PEAK Y-26 k=365",
"color": "#FF7F0E",
"days": 365,
"output": "chart_peak_y26_365.png",
"ltd_sheet": "P_Y",
"last_sheet": "P_Y",
"mw_sheet": "P_Y",
"units": {
"ltd": "PLN",
"last": "MW",
"mw": "PLN/MWh"
}
},
{
"sheet": "B_Y",
"title": "BASE Y-26 k=30",
"color": "#1E90FF",
"days": 30,
"output": "chart_base_y26_30.png",
"ltd_sheet": "B_Y",
"last_sheet": "B_Y",
"mw_sheet": "B_Y",
"units": {
"ltd": "PLN",
"last": "MW",
"mw": "PLN/MWh"
}
},
{
"sheet": "P_Y",
"title": "PEAK Y-26 k=30",
"color": "#FF7F0E",
"days": 30,
"output": "chart_peak_y26_30.png",
"ltd_sheet": "P_Y",
"last_sheet": "P_Y",
"mw_sheet": "P_Y",
"units": {
"ltd": "PLN",
"last": "MW",
"mw": "PLN/MWh"
}
},
# Wykresy dla Y-27 (strona 4)
{
"sheet": "B_Y2",
"title": "BASE Y-27 k=365",
"color": "#1E90FF",
"days": 365,
"output": "chart_base_y27_365.png",
"ltd_sheet": "B_Y2",
"last_sheet": "B_Y2",
"mw_sheet": "B_Y2",
"units": {
"ltd": "PLN",
"last": "MW",
"mw": "PLN/MWh"
}
},
{
"sheet": "P_Y2",
"title": "PEAK Y-27 k=365",
"color": "#FF7F0E",
"days": 365,
"output": "chart_peak_y27_365.png",
"ltd_sheet": "P_Y2",
"last_sheet": "P_Y2",
"mw_sheet": "P_Y2",
"units": {
"ltd": "PLN",
"last": "MW",
"mw": "PLN/MWh"
}
},
{
"sheet": "B_Y2",
"title": "BASE Y-27 k=30",
"color": "#1E90FF",
"days": 30,
"output": "chart_base_y27_30.png",
"ltd_sheet": "B_Y2",
"last_sheet": "B_Y2",
"mw_sheet": "B_Y2",
"units": {
"ltd": "PLN",
"last": "MW",
"mw": "PLN/MWh"
}
},
{
"sheet": "P_Y2",
"title": "PEAK Y-27 k=30",
"color": "#FF7F0E",
"days": 30,
"output": "chart_peak_y27_30.png",
"ltd_sheet": "P_Y2",
"last_sheet": "P_Y2",
"mw_sheet": "P_Y2",
"units": {
"ltd": "PLN",
"last": "MW",
"mw": "PLN/MWh"
}
},
# Wykresy dla B_Q (strona 5)
{
"sheet": "B_Q",
"title": "BASE Q4-25 k=90",
"color": "#1E90FF",
"days": 90,
"output": "chart_base_q4_90.png",
"ltd_sheet": "B_Q",
"last_sheet": "B_Q",
"mw_sheet": "B_Q",
"units": {
"ltd": "PLN",
"last": "MW",
"mw": "PLN/MWh"
}
},
{
"sheet": "P_Q",
"title": "PEAK Q4-25 k=90",
"color": "#FF7F0E",
"days": 90,
"output": "chart_peak_q4_90.png",
"ltd_sheet": "P_Q",
"last_sheet": "P_Q",
"mw_sheet": "P_Q",
"units": {
"ltd": "PLN",
"last": "MW",
"mw": "PLN/MWh"
}
},
{
"sheet": "B_Q",
"title": "BASE Q4-25 k=10",
"color": "#1E90FF",
"days": 10,
"output": "chart_base_q4_10.png",
"ltd_sheet": "B_Q",
"last_sheet": "B_Q",
"mw_sheet": "B_Q",
"units": {
"ltd": "PLN",
"last": "MW",
"mw": "PLN/MWh"
}
},
{
"sheet": "P_Q",
"title": "PEAK Q4-25 k=10",
"color": "#FF7F0E",
"days": 10,
"output": "chart_peak_q4_10.png",
"ltd_sheet": "P_Q",
"last_sheet": "P_Q",
"mw_sheet": "P_Q",
"units": {
"ltd": "PLN",
"last": "MW",
"mw": "PLN/MWh"
}
},
# Wykresy dla B_M (strona 6)
{
"sheet": "B_M",
"title": "BASE M-08 k=15",
"color": "#1E90FF",
"days": 15,
"output": "chart_base_m08_15.png",
"ltd_sheet": "B_M",
"last_sheet": "B_M",
"mw_sheet": "B_M",
"units": {
"ltd": "PLN",
"last": "MW",
"mw": "PLN/MWh"
}
},
{
"sheet": "P_M",
"title": "PEAK M-08 k=10",
"color": "#FF7F0E",
"days": 10,
"output": "chart_peak_m08_10.png",
"ltd_sheet": "P_M",
"last_sheet": "P_M",
"mw_sheet": "P_M",
"units": {
"ltd": "PLN",
"last": "MW",
"mw": "PLN/MWh"
}
},
{
"sheet": "B_M",
"title": "BASE M-08 k=10",
"color": "#1E90FF",
"days": 10,
"output": "chart_base_m08_10.png",
"ltd_sheet": "B_M",
"last_sheet": "B_M",
"mw_sheet": "B_M",
"units": {
"ltd": "PLN",
"last": "MW",
"mw": "PLN/MWh"
}
},
{
"sheet": "P_M",
"title": "PEAK M-08 k=10",
"color": "#FF7F0E",
"days": 10,
"output": "chart_peak_m08_10_2.png",
"ltd_sheet": "P_M",
"last_sheet": "P_M",
"mw_sheet": "P_M",
"units": {
"ltd": "PLN",
"last": "MW",
"mw": "PLN/MWh"
}
},
]
LARGE_CHART_CONFIG = {
"sheet": "indeksy",
"title": "Indeksy TGe",
"color": "#00008B",
"output": "large_trend_chart.png",
"ltd_sheet": "indeksy",
"last_sheet": "indeksy",
"days": 365, # Dodane, aby uniknąć błędu
}
# ==============================
# FUNKCJE POMOCNICZE
# ==============================
def setup_directories():
"""Utworzenie katalogów wyjściowych jeśli nie istnieją."""
os.makedirs(Config.OUTPUT_DIR, exist_ok=True)
def load_excel_data(sheet_name):
"""Wczytanie danych z Excela."""
if not os.path.exists(Config.EXCEL_PATH):
raise FileNotFoundError(f"Plik Excel nie znaleziony: {Config.EXCEL_PATH}")
try:
df = pd.read_excel(Config.EXCEL_PATH, sheet_name=sheet_name, engine='openpyxl')
df.iloc[:, 0] = pd.to_datetime(df.iloc[:, 0], errors='coerce')
return df.dropna(subset=[df.columns[0]])
except Exception as e:
raise RuntimeError(f"Błąd wczytywania arkusza {sheet_name}: {e}")
def create_chart(df, title, color, output_img, days, ltd_value, ltd_unit, last_value, last_unit, mw_value, mw_unit,
figsize=(8, 5)):
"""Generowanie wykresu na podstawie przygotowanych danych."""
start_date = datetime.today() - timedelta(days=days)
df_recent = df[df.iloc[:, 0] >= start_date].copy()
if df_recent.empty:
raise ValueError(f"Brak danych dla zakresu {days} dni w arkuszu")
dates = df_recent.iloc[:, 0]
prices = df_recent.iloc[:, 1]
volumes = df_recent.iloc[:, 2]
fig, ax1 = plt.subplots(figsize=figsize)
ax1.plot(dates, prices, color=color, linewidth=2.5, label='PLN/MWh')
ax1.set_ylabel('PLN/MWh', color=color, fontsize=12)
ax1.tick_params(axis='y', labelcolor=color, labelsize=12)
ax1.grid(True, which='major', axis='y', linestyle='--', alpha=0.7)
ax2 = ax1.twinx()
ax2.bar(dates, volumes, color='gray', alpha=0.6, label='Wolumen')
ax2.set_ylabel('MW', color='gray', fontsize=12)
ax2.tick_params(axis='y', labelcolor='gray', labelsize=12)
max_volume = volumes.max()
if days <= 30:
ax2.set_ylim(0, ((max_volume // 5) + 1) * 5)
ax2.yaxis.set_major_locator(MultipleLocator(5))
elif days > 300:
ax2.set_ylim(0, ((max_volume // 10) + 1) * 10)
ax2.yaxis.set_major_locator(MultipleLocator(10))
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
locator = (
mdates.MonthLocator(interval=1) if days > 364 else
mdates.WeekdayLocator(interval=1) if days > 89 else
mdates.DayLocator(interval=2) if days > 29 else
mdates.DayLocator(interval=1)
)
ax1.xaxis.set_major_locator(locator)
plt.setp(ax1.get_xticklabels(), rotation=45, ha='right', fontsize=10)
lines_1, labels_1 = ax1.get_legend_handles_labels()
lines_2, labels_2 = ax2.get_legend_handles_labels()
ax1.legend(
lines_1 + lines_2, labels_1 + labels_2,
loc='upper center', bbox_to_anchor=(0.5, -0.3),
ncol=2, fontsize=10, frameon=False
)
if days in [90, 365, 45, 15]:
legend_text = (
f"LtD: {ltd_value:.2f} {ltd_unit}\n"
f"Last: {last_value:.2f} {last_unit}\n"
f"MW: {mw_value:.0f} {mw_unit}"
)
ax1.text(
0.05, 0.95, legend_text, transform=ax1.transAxes, fontsize=10,
verticalalignment='top', bbox=dict(facecolor='white', alpha=0.7)
)
plt.title(title, fontsize=16, pad=20)
plt.tight_layout(rect=(0, 0, 1, 0.95))
full_path = os.path.join(Config.OUTPUT_DIR, output_img)
plt.savefig(full_path, bbox_inches='tight', dpi=300)
plt.close(fig)
return full_path
def create_line_chart(df, title, color, output_img, days, ltd_value, ltd_unit, last_value, last_unit, mw_value, mw_unit, figsize=(14,10)):
"""Generowanie wykresu liniowego (tylko linia, bez słupków)."""
start_date = datetime.today() - timedelta(days=days)
df_recent = df[df.iloc[:, 0] >= start_date].copy()
if df_recent.empty:
raise ValueError(f"Brak danych dla zakresu {days} dni")
dates = df_recent.iloc[:, 0]
prices = df_recent.iloc[:, 1] # Kolumna cen
fig, ax = plt.subplots(figsize=figsize)
ax.plot(dates, prices, color=color, linewidth=2.5, label='Cena (PLN/MWh)')
ax.set_ylabel('Cena (PLN/MWh)', color=color, fontsize=12)
ax.tick_params(axis='y', labelcolor=color)
ax.grid(True, linestyle='--', alpha=0.7)
ax.set_xlabel('Data')
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
locator = (
mdates.MonthLocator(interval=1) if days > 364 else
mdates.WeekdayLocator(interval=1) if days > 89 else
mdates.DayLocator(interval=2) if days > 29 else
mdates.DayLocator(interval=1)
)
ax.xaxis.set_major_locator(locator)
plt.setp(ax.get_xticklabels(), rotation=45, ha='right')
ax.legend(loc='upper left')
legend_text = (
f"LtD: {ltd_value:.2f} {ltd_unit}\n"
f"Last: {last_value:.2f} {last_unit}\n"
f"MW: {mw_value:.0f} {mw_unit}"
)
ax.text(0.05, 0.95, legend_text, transform=ax.transAxes, fontsize=10, verticalalignment='top', bbox=dict(facecolor='white', alpha=0.7))
plt.title(title, fontsize=16, pad=20)
plt.tight_layout()
full_path = os.path.join(Config.OUTPUT_DIR, output_img)
plt.savefig(full_path, bbox_inches='tight', dpi=300)
plt.close(fig)
return full_path
def draw_header(c):
"""Rysowanie logo w prawym górnym rogu."""
try:
if hasattr(Config, 'LOGO_PATH') and Config.LOGO_PATH:
c.drawImage(
Config.LOGO_PATH,
Config.PAGE_WIDTH - Config.LOGO_WIDTH - 20,
Config.PAGE_HEIGHT - Config.LOGO_HEIGHT - 20,
width=Config.LOGO_WIDTH,
height=Config.LOGO_HEIGHT,
mask='auto'
)
except Exception as e:
print(f"Ostrzeżenie: Nie udało się załadować logo: {e}")
def draw_footer(c, page_num):
"""Rysowanie stopki z informacjami i numerem strony."""
c.setFont("Helvetica", 10)
c.drawString(Config.MARGIN_LEFT, Config.MARGIN_BOTTOM - 10, Config.FOOTER_TEXT)
c.drawRightString(Config.PAGE_WIDTH - Config.MARGIN_RIGHT, Config.MARGIN_BOTTOM - 10, f"Strona {page_num}")
def draw_single_chart(c, chart_path, x, y, width, height):
"""Rysowanie pojedynczego wykresu w PDF."""
try:
c.drawImage(chart_path, x, y, width=width, height=height)
except Exception as e:
print(f"Błąd podczas rysowania wykresu: {e}")
c.rect(x, y, width, height, stroke=1, fill=0)
c.drawString(x + 10, y + height - 20, "Brak danych")
def draw_chart_grid(c, charts):
"""Rysowanie 4 wykresów w układzie 2x2."""
page_width = Config.PAGE_WIDTH
page_height = Config.PAGE_HEIGHT
margin_left = Config.MARGIN_LEFT
margin_right = Config.MARGIN_RIGHT
margin_top = Config.MARGIN_TOP
margin_bottom = Config.MARGIN_BOTTOM
title_height = 30
available_width = page_width - margin_left - margin_right
available_height = page_height - margin_top - margin_bottom - title_height
col_width = available_width / 2
row_height = available_height / 2
x_positions = [margin_left, margin_left + col_width]
y_positions = [
page_height - margin_top - title_height - row_height,
page_height - margin_top - title_height - 2 * row_height
]
for row in range(2):
for col in range(2):
idx = row * 2 + col
if idx < len(charts):
x = x_positions[col]
y = y_positions[row]
draw_single_chart(c, charts[idx], x, y, col_width, row_height)
def draw_full_page_chart(c, chart_path):
"""Rysowanie pojedynczego wykresu na całą stronę z zachowaniem proporcji."""
title_height = 10
top_margin_effective = Config.MARGIN_TOP + title_height
available_height = Config.PAGE_HEIGHT - top_margin_effective - Config.MARGIN_BOTTOM
available_width = Config.PAGE_WIDTH - Config.MARGIN_LEFT - Config.MARGIN_RIGHT
img = Image.open(chart_path)
img_width, img_height = img.size
aspect_ratio = img_width / img_height
if available_width / available_height > aspect_ratio:
height = available_height
width = height * aspect_ratio
else:
width = available_width
height = width / aspect_ratio
x = Config.MARGIN_LEFT + (available_width - width) / 2
y = Config.MARGIN_BOTTOM + (available_height - height) / 2
draw_single_chart(c, chart_path, x, y, width, height)
# ==============================
# GŁÓWNA LOGIKA GENEROWANIA PDF
# ==============================
def generate_pdf(chart_paths, large_chart_path):
"""Tworzenie pełnego raportu PDF."""
c = canvas.Canvas(Config.PDF_PATH, pagesize=Config.PAGE_SIZE)
draw_header(c)
c.setFillColor(HexColor("#000000"))
c.setFont("Helvetica-Bold", 36)
c.drawCentredString(Config.PAGE_WIDTH / 2, Config.PAGE_HEIGHT - 250, "Raport dobowy - Rynek energii")
c.setFont("Helvetica-Oblique", 20)
c.drawCentredString(Config.PAGE_WIDTH / 2, Config.PAGE_HEIGHT - 450, f"{Config.TODAY_STR}")
draw_footer(c, 1)
c.showPage()
draw_header(c)
draw_footer(c, 2)
c.showPage()
draw_header(c)
c.setFont("Helvetica-Bold", 16)
c.drawString(Config.MARGIN_LEFT, Config.PAGE_HEIGHT - Config.MARGIN_TOP,
"Notowania cen energii elektrycznej dla produktów rocznych na 2026 r.")
draw_chart_grid(c, [
chart_paths[0], chart_paths[2], chart_paths[1], chart_paths[3]
])
draw_footer(c, 3)
c.showPage()
draw_header(c)
c.setFont("Helvetica-Bold", 16)
c.drawString(Config.MARGIN_LEFT, Config.PAGE_HEIGHT - Config.MARGIN_TOP,
"Notowania cen energii elektrycznej dla produktów rocznych na 2027 r.")
draw_chart_grid(c, [
chart_paths[4], chart_paths[6], chart_paths[5], chart_paths[7]
])
draw_footer(c, 4)
c.showPage()
draw_header(c)
c.setFont("Helvetica-Bold", 16)
c.drawString(Config.MARGIN_LEFT, Config.PAGE_HEIGHT - Config.MARGIN_TOP,
"Notowania cen energii elektrycznej dla produktów kwartalnych")
draw_chart_grid(c, [
chart_paths[8], chart_paths[10], chart_paths[9], chart_paths[11]
])
draw_footer(c, 5)
c.showPage()
draw_header(c)
c.setFont("Helvetica-Bold", 16)
c.drawString(Config.MARGIN_LEFT, Config.PAGE_HEIGHT - Config.MARGIN_TOP,
"Notowania cen energii elektrycznej dla produktów miesięcznych")
draw_chart_grid(c, [
chart_paths[12], chart_paths[14], chart_paths[13], chart_paths[15]
])
draw_footer(c, 6)
c.showPage()
draw_header(c)
c.setFont("Helvetica-Bold", 16)
title_y = Config.PAGE_HEIGHT - Config.MARGIN_TOP - 30
c.drawString(Config.MARGIN_LEFT, title_y, Config.LARGE_CHART_CONFIG["title"])
draw_full_page_chart(c, large_chart_path)
draw_footer(c, 7)
c.showPage()
c.save()
print(f"PDF zapisany: {Config.PDF_PATH}")
# ==============================
# URUCHOMIENIE SKRYPTU
# ==============================
def main():
try:
setup_directories()
data_cache = {}
ltd_values = {}
last_values = {}
mw_values = {}
chart_paths = []
for config in Config.CHART_CONFIGS:
sheet = config["sheet"]
if sheet not in data_cache:
data_cache[sheet] = load_excel_data(sheet)
for sheet_type in ["ltd_sheet", "last_sheet", "mw_sheet"]:
sheet_name = config[sheet_type]
if sheet_name not in ltd_values:
df = load_excel_data(sheet_name)
ltd_values[sheet_name] = df.iloc[0, 3]
last_values[sheet_name] = df.iloc[0, 4]
mw_values[sheet_name] = int(df.iloc[0, 5])
chart_path = create_chart(
df=data_cache[sheet],
title=config["title"],
color=config["color"],
output_img=config["output"],
days=config["days"],
ltd_value=ltd_values[config["ltd_sheet"]],
ltd_unit=config["units"]["ltd"],
last_value=last_values[config["last_sheet"]],
last_unit=config["units"]["last"],
mw_value=mw_values[config["mw_sheet"]],
mw_unit=config["units"]["mw"]
)
chart_paths.append(chart_path)
large_config = Config.LARGE_CHART_CONFIG.copy()
sheet = large_config["sheet"]
if sheet not in data_cache:
data_cache[sheet] = load_excel_data(sheet)
for sheet_type in ["ltd_sheet", "last_sheet", "mw_sheet"]:
sheet_name = large_config[sheet_type]
if sheet_name not in ltd_values:
df = load_excel_data(sheet_name)
ltd_values[sheet_name] = df.iloc[0, 3]
last_values[sheet_name] = df.iloc[0, 4]
mw_values[sheet_name] = int(df.iloc[0, 5])
large_config["df"] = data_cache[sheet]
large_config["ltd_value"] = ltd_values[large_config["ltd_sheet"]]
large_config["last_value"] = last_values[large_config["last_sheet"]]
large_config["mw_value"] = mw_values[large_config["mw_sheet"]]
large_chart_path = create_line_chart(
df=large_config["df"],
title=large_config["title"],
color=large_config["color"],
output_img=large_config["output"],
days=large_config["days"],
ltd_value=large_config["ltd_value"],
ltd_unit="PLN", # Zakładam na podstawie innych, dostosuj jeśli potrzebne
last_value=large_config["last_value"],
last_unit="MW",
mw_value=large_config["mw_value"],
mw_unit="PLN/MWh"
)
generate_pdf(chart_paths, large_chart_path)
print("Proces zakończony pomyślnie.")
except Exception as e:
print(f"Błąd: {str(e)}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
main()