Пример #1
0
 def getprices(self, kwargs):  # Get daily prices
     prices_spot = elspot.Prices()
     now = datetime.datetime.now(pytz.utc)
     datatoday = prices_spot.hourly(end_date=self.date(), areas=['FI'])
     priceslist = []
     for i in datatoday['areas']['FI']['values']:
         priceslist.append(round(i['value'] / 10 * 1.24 + 3.9 + 2.79372, 3))
     priceslistsorted = sorted(priceslist)
     self.set_state("sensor.spot_cost_today", state=priceslistsorted)
     priceslisttomorrow = []
     try:
         datatomorrow = prices_spot.hourly(
             end_date=(self.date() + datetime.timedelta(days=1)),
             areas=['FI'])
         for i in datatomorrow['areas']['FI']['values']:
             priceslisttomorrow.append(
                 round(i['value'] / 10 * 1.24 + 3.9 + 2.79372, 3))
         priceslisttomorrowsorted = sorted(priceslisttomorrow)
         self.set_state("sensor.spot_cost_future",
                        state=priceslisttomorrowsorted)
     except KeyError:
         if datetime.datetime.today(
         ).hour > 10:  # only check again during afternoon, Today() is in UTC time
             self.run_in(
                 self.getprices,
                 300)  # If there is no prices yet check again in 5 minutes
     if priceslisttomorrow[0] == float('inf'):
         if datetime.datetime.today(
         ).hour > 10:  # only check again during afternoon, Today() is in UTC time
             self.run_in(
                 self.getprices,
                 300)  # If there is no prices yet check again in 5 minutes
Пример #2
0
def get_spot_price():
    prices_spot = elspot.Prices(currency="NOK")
    prices_area = prices_spot.hourly(areas=["Oslo"])

    prices = []
    for item in prices_area["areas"]["Oslo"]["values"]:
        # print(item["end"].strftime("%d.%m.%Y-%H"))
        prices.append(item["value"])

    return prices
Пример #3
0
 def updatecurrentprice(
         self, kwargs):  #Get current price once an hour and update it
     prices_spot = elspot.Prices()
     now = datetime.datetime.now(pytz.utc)
     datatoday = prices_spot.hourly(end_date=self.date(), areas=['FI'])
     for rate in datatoday['areas']['FI']['values']:
         if rate['start'] <= now < rate['end']:
             self.set_state("sensor.spot_cost",
                            state=round(
                                rate['value'] / 10 * 1.24 + 3.9 + 2.79372,
                                3))
             self.set_state("sensor.spot_sell",
                            state=round(rate['value'] / 10, 3))
Пример #4
0
    def _prepare_values2(self, dateend) -> list:
        data = elspot.Prices().hourly(end_date=dateend, areas=[self.area])
        priceslisttemp = []
        for item in data['areas'][self.area]['values']:
            if float(item["value"]) != float('inf'):

                i = {
                    "start": (item["start"]).astimezone(self.tz).isoformat(),
                    "end": (item["end"]).astimezone(self.tz).isoformat(),
                    "value":
                    round(item["value"] / 10 * self.vat + self.extracost, 3),
                }
                priceslisttemp.append(i)
        return priceslisttemp
Пример #5
0
def get_spot_price(end_date=None):
    """
    Uses the python-package nordpool to get spotprices for Oslo area in NOK.
    Returns a df with date and price
    """
    prices_spot = elspot.Prices(currency="NOK")
    prices_area = prices_spot.hourly(end_date=end_date, areas=["Oslo"])
    dates = []
    prices = []
    for item in prices_area["areas"]["Oslo"]["values"]:
        dates.append(item["end"])
        prices.append(item["value"])

    return pd.DataFrame(data={"time": dates, "price": prices})
Пример #6
0
    def manual_check(region, currency, vat):

        ts = tz.gettz(tzs[region])
        utc = datetime.utcnow()

        # Convert time zone
        lt = utc.astimezone(ts)
        dt_today = lt.date()
        dt_yesterday = lt + timedelta(days=-1)

        spot = elspot.Prices(currency)
        yesterday = spot.hourly(end_date=dt_yesterday)
        today = spot.hourly(end_date=dt_today)
        tomorrow = spot.hourly(end_date=dt_today + timedelta(days=1))

        results = [yesterday, today, tomorrow]

        data = join_result_for_correct_time(results)
        values = []
        for key, value in data["areas"].items():
            values = []
            if key == region or region is None:
                for v in data["areas"][key]["values"]:
                    zone = tzs.get(key)
                    if zone is None:
                        continue
                    zone = tz.gettz(zone)

                    i = {
                        "value": v["value"],
                        "start": v["start"].astimezone(zone),
                        "end": v["end"].astimezone(zone),
                    }
                    values.append(i)

            if len(values):
                print("Report for region %s" % key)
            for vvv in sorted(values, key=itemgetter("start")):
                print("from %s to %s price %s" %
                      (vvv["start"], vvv["end"], vvv["value"]))
            if len(values):
                print("total hours %s" % len(values))
Пример #7
0
 def initialize(self):
     self.run_daily(
         self.getprices,
         "13:32:01")  #New prices are published to Nordpool around 13:30 EET
     self.run_daily(
         self.getprices, "01:00:01"
     )  #Update tommorrow to today after nordpool changes to next day
     hourly_start = datetime.datetime.today().hour + 1
     self.run_hourly(self.updatecurrentprice,
                     datetime.time(hourly_start, 0,
                                   1))  #Update prices every even hour
     prices_spot = elspot.Prices()
     datatoday = prices_spot.hourly(end_date=self.date(), areas=['FI'])
     now = datetime.datetime.now(pytz.utc)
     for rate in datatoday['areas']['FI']['values']:
         if rate['start'] <= now < rate['end']:
             self.set_state(
                 "sensor.spot_cost",
                 state=round(rate['value'] / 10 * 1.24 + 3.9 + 2.79372,
                             3))  #Added VAT, transfer and electricity tax
             self.set_state("sensor.spot_sell",
                            state=round(rate['value'] / 10,
                                        3))  #Raw price for selling
     datatomorrow = prices_spot.hourly(areas=['FI'])
     priceslist = []
     for i in datatoday['areas']['FI']['values']:
         priceslist.append(round(i['value'] / 10 * 1.24 + 3.9 + 2.79372, 3))
     priceslistsorted = sorted(priceslist)
     self.set_state("sensor.spot_cost_today", state=priceslistsorted)
     priceslisttomorrow = []
     for i in datatomorrow['areas']['FI']['values']:
         priceslisttomorrow.append(
             round(i['value'] / 10 * 1.24 + 3.9 + 2.79372, 3))
     priceslisttomorrowsorted = sorted(priceslisttomorrow)
     self.set_state("sensor.spot_cost_future",
                    state=priceslisttomorrowsorted)
Пример #8
0
            return 'automatic'                 # Defaults to automatic if neither local or remote control are active
        else:
            raise RuntimeError('An error occurred with control signal inputs')
            



        
        
        
        
# IMPORTING PRICE DATA ETC.


# Initialize class for fetching Elspot prices
prices_spot = elspot.Prices()


def get_prices(period='hourly'): # Imports electricity price in Trondheim for the past month
    

    # Allows the user to chose whether to access hourly or daily price data
    if period == 'hourly':
        def get_trd_prices():
            try:
                hourly = prices_spot.hourly(areas=['Tr.heim'])
                return hourly
            except ConnectionError:
                warnings.warn('Was unable to connect to www.nordpoolgroup.com')
                return 0
        
Пример #9
0
#!/usr/bin/env python

# Import library for fetching Elspot data
from nordpool import elspot
from pprint import pprint

# Initialize class for fetching Elspot prices
prices = elspot.Prices()
# Fetch hourly prices for Finland and print the resulting dictionary
pprint(prices.hourly(areas=['FI']))
Пример #10
0
# https://repl.it/repls/WildImpishMass
from dateutil import tz
from nordpool import elspot

_LOGGER = logging.getLogger(__name__)

to_helsinki = tz.gettz("Europe/Helsinki")
utc = datetime.utcnow()

# Convert time zone
hel = utc.astimezone(to_helsinki)
dt_today = hel.date()
dt_yesterday = hel + timedelta(days=-1)
print("Requsting data for %s - %s" % (dt_yesterday.date(), dt_today))

spot = elspot.Prices("EUR")
yesterday = spot.hourly(end_date=dt_yesterday)
today = spot.hourly(end_date=dt_today)

results = [yesterday, today]

tzs = {
    "DK1": "Europe/Copenhagen",
    "DK2": "Europe/Copenhagen",
    "FI": "Europe/Helsinki",
    "EE": "Europe/Tallinn",
    "LT": "Europe/Vilnius",
    "LV": "Europe/Riga",
    "Oslo": "Europe/Oslo",
    "Kr.sand": "Europe/Oslo",
    "Bergen": "Europe/Oslo",
Пример #11
0
    def update(self, force=False):
        """Update any required info."""
        from nordpool import elspot

        if self._last_update_tomorrow_date is None:
            if pendulum.now("Europe/Stockholm") > pendulum.now(
                    "Europe/Stockholm").at(13, randint(0, 5)):
                self._last_update_tomorrow_date = pendulum.tomorrow(
                    "Europe/Stockholm").at(13)
            else:
                self._last_update_tomorrow_date = pendulum.today(
                    "Europe/Stockholm").at(13)

        if self._last_tick is None:
            self._last_tick = pendulum.now()

        if force:
            for currency in self.currency:
                spot = elspot.Prices(currency)
                today = spot.hourly(end_date=pendulum.now())
                self._data[currency]['today'] = today["areas"]

                tomorrow = spot.hourly()
                if tomorrow:
                    self._data[currency]['tomorrow'] = tomorrow["areas"]

            return

        for currency in self.currency:
            # Add any missing power prices for today in the currency we track
            if self._data.get(currency, {}).get('today') is None:
                spot = elspot.Prices(currency)
                today = spot.hourly(end_date=pendulum.now())
                if today:

                    self._data[currency]["today"] = today["areas"]

            # Add missing prices for tomorrow.
            if self._data.get(currency, {}).get('tomorrow') is None:
                if pendulum.now("Europe/Stockholm") > pendulum.now(
                        "Europe/Stockholm").at(13, randint(0, 5)):
                    self._last_update_tomorrow_date = pendulum.tomorrow(
                        "Europe/Stockholm").at(13)
                    spot = elspot.Prices(currency)
                    tomorrow = spot.hourly()
                    if tomorrow:
                        self._data[currency]["tomorrow"] = tomorrow["areas"]
                else:
                    _LOGGER.info("New api data for tomorrow isnt posted yet")

        # Check if there is any "new tomorrows data"
        if (self._last_tick.in_timezone("Europe/Stockholm") >
                self._last_update_tomorrow_date):
            self._last_update_tomorrow_date = pendulum.tomorrow(
                "Europe/Stockholm").at(13, randint(0, 5))
            for currency in self.currency:
                spot = elspot.Prices(currency)
                tomorrow = spot.hourly(pendulum.now().add(days=1))
                if tomorrow:
                    _LOGGER.info(
                        "New data was posted updating tomorrow prices in NordpoolData %s",
                        currency)
                    self._data[currency]["tomorrow"] = tomorrow["areas"]

        if is_new(self._last_tick, typ="day"):
            for currency in self.currency:
                spot = elspot.Prices(currency)
                today = spot.hourly(end_date=pendulum.now())
                if today:
                    self._data[currency]["today"] = today["areas"]
                # We could swap, but ill rather do a extrac api call.
                # self._data[currency]["today"] = self._data[currency]["tomorrow"]

        self._last_tick = pendulum.now()
Пример #12
0
    def update(self, force=False):
        """Update any required info."""
        from nordpool import elspot

        at_1300 = dt_utils.now().replace(hour=13,
                                         minute=randint(0, 5),
                                         second=0)

        if self._last_update_tomorrow_date is None:
            if stock(dt_utils.now()) > stock(at_1300):
                self._last_update_tomorrow_date = stock(at_1300 +
                                                        timedelta(hours=24))
            else:
                self._last_update_tomorrow_date = stock(at_1300)

        if self._last_tick is None:
            self._last_tick = dt_utils.now()

        if force:
            for currency in self.currency:
                spot = elspot.Prices(currency)
                today = spot.hourly(
                    end_date=dt_utils.now().strftime("%Y-%m-%dT%H:%M:%S.%f%z"))
                self._data[currency]['today'] = today["areas"]

                tomorrow = spot.hourly()
                if tomorrow:
                    self._data[currency]['tomorrow'] = tomorrow["areas"]

            return

        for currency in self.currency:
            # Add any missing power prices for today in the currency we track
            if self._data.get(currency, {}).get('today') is None:
                spot = elspot.Prices(currency)
                today = spot.hourly(
                    end_date=dt_utils.now().strftime("%Y-%m-%dT%H:%M:%S.%f%z"))
                if today:

                    self._data[currency]["today"] = today["areas"]

            # Add missing prices for tomorrow.
            if self._data.get(currency, {}).get('tomorrow') is None:
                if stock(dt_utils.now()) > stock(at_1300):
                    self._last_update_tomorrow_date = stock(at_1300)
                    spot = elspot.Prices(currency)
                    tomorrow = spot.hourly()
                    if tomorrow:
                        self._tomorrow_valid = True
                        self._data[currency]["tomorrow"] = tomorrow["areas"]
                else:
                    self._tomorrow_valid = False
                    _LOGGER.info("New api data for tomorrow isnt posted yet")

        # Check if there is any "new tomorrows data"
        if (stock(self._last_tick) > self._last_update_tomorrow_date):
            self._last_update_tomorrow_date = stock(at_1300 +
                                                    timedelta(hours=24))
            for currency in self.currency:
                spot = elspot.Prices(currency)
                tomorrow = spot.hourly(dt_utils.now() + timedelta(hours=24))
                if tomorrow:
                    _LOGGER.info(
                        "New data was posted updating tomorrow prices in NordpoolData %s",
                        currency)
                    self._tomorrow_valid = True
                    self._data[currency]["tomorrow"] = tomorrow["areas"]

        if is_new(self._last_tick, typ="day"):
            self._tomorrow_valid = False
            for currency in self.currency:
                spot = elspot.Prices(currency)
                today = spot.hourly(
                    end_date=dt_utils.now().strftime("%Y-%m-%dT%H:%M:%S.%f%z"))
                if today:
                    self._data[currency]["today"] = today["areas"]
                # We could swap, but ill rather do a extrac api call.
                # self._data[currency]["today"] = self._data[currency]["tomorrow"]

        self._last_tick = dt_utils.now()