48 Stunden Predcition & Optimierung

Ein paar Zeitfunktionen korrigiert (24h / 48h)
Strompreis Cache stündlich leeren
Strompreis bei nur 24h Daten, wird verdoppelt (Prognose fehlt noch)
This commit is contained in:
Bla Bla
2024-05-08 09:58:41 +02:00
parent 5a4a8c63d2
commit 2605460a99
6 changed files with 79 additions and 46 deletions

View File

@@ -14,20 +14,34 @@ utc_time = utc_time.replace(tzinfo=pytz.utc)
local_time = utc_time.astimezone(pytz.timezone('Europe/Berlin'))
print(local_time)
def repeat_to_shape(array, target_shape):
# Prüfen , ob das Array in die Zielgröße passt
if len(target_shape) != array.ndim:
raise ValueError("Array and target shape must have the same number of dimensions")
# die Anzahl der Wiederholungen pro Dimension
repeats = tuple(target_shape[i] // array.shape[i] for i in range(array.ndim))
# np.tile, um das Array zu erweitern
expanded_array = np.tile(array, repeats)
return expanded_array
class HourlyElectricityPriceForecast:
def __init__(self, source, cache_dir='cache', abgaben=0.00019):
def __init__(self, source, cache_dir='cache', abgaben=0.000, prediction_hours=24): #228
self.cache_dir = cache_dir
if not os.path.exists(self.cache_dir):
os.makedirs(self.cache_dir)
self.cache_time_file = os.path.join(self.cache_dir, 'cache_timestamp.txt')
self.prices = self.load_data(source)
self.abgaben = abgaben
self.prediction_hours = prediction_hours
def load_data(self, source):
cache_filename = self.get_cache_filename(source)
if source.startswith('http'):
cache_filename = self.get_cache_filename(source)
if os.path.exists(cache_filename):
if os.path.exists(cache_filename) and not self.is_cache_expired():
print("Lade Daten aus dem Cache...")
with open(cache_filename, 'r') as file:
data = json.load(file)
@@ -38,6 +52,7 @@ class HourlyElectricityPriceForecast:
data = response.json()
with open(cache_filename, 'w') as file:
json.dump(data, file)
self.update_cache_timestamp()
else:
raise Exception(f"Fehler beim Abrufen der Daten: {response.status_code}")
else:
@@ -49,6 +64,18 @@ class HourlyElectricityPriceForecast:
hash_object = hashlib.sha256(url.encode())
hex_dig = hash_object.hexdigest()
return os.path.join(self.cache_dir, f"cache_{hex_dig}.json")
def is_cache_expired(self):
if not os.path.exists(self.cache_time_file):
return True
with open(self.cache_time_file, 'r') as file:
timestamp_str = file.read()
last_cache_time = datetime.strptime(timestamp_str, '%Y-%m-%d %H:%M:%S')
return datetime.now() - last_cache_time > timedelta(hours=1)
def update_cache_timestamp(self):
with open(self.cache_time_file, 'w') as file:
file.write(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
@@ -68,13 +95,17 @@ class HourlyElectricityPriceForecast:
# Extrahieren aller Preise für das spezifizierte Datum
date_prices = [entry["marketpriceEurocentPerKWh"]+self.abgaben for entry in self.prices if date_str in entry['end']]
print("getPRice:",len(date_prices))
# Hinzufügen des letzten Preises des vorherigen Tages am Anfang der Liste
date_prices.insert(0, last_price_of_previous_day)
if len(date_prices) == 23:
date_prices.insert(0, last_price_of_previous_day)
return np.array(date_prices)/(1000.0*100.0) + self.abgaben
def get_price_for_daterange(self, start_date_str, end_date_str):
print(start_date_str)
print(end_date_str)
"""Gibt alle Preise zwischen dem Start- und Enddatum zurück."""
start_date_utc = datetime.strptime(start_date_str, "%Y-%m-%d").replace(tzinfo=pytz.utc)
end_date_utc = datetime.strptime(end_date_str, "%Y-%m-%d").replace(tzinfo=pytz.utc)
@@ -84,13 +115,16 @@ class HourlyElectricityPriceForecast:
price_list = []
while start_date <= end_date:
while start_date < end_date:
date_str = start_date.strftime("%Y-%m-%d")
daily_prices = self.get_price_for_date(date_str)
#print(len(self.get_price_for_date(date_str)))
print(date_str," ",daily_prices)
print(len(self.get_price_for_date(date_str)))
if daily_prices.size ==24:
price_list.extend(daily_prices)
start_date += timedelta(days=1)
return np.array(price_list)
price_list = repeat_to_shape(np.array(price_list),(self.prediction_hours,))
return price_list