Skip to content

Instantly share code, notes, and snippets.

@aigarius
Created October 24, 2023 20:49
Show Gist options
  • Save aigarius/7e247cff03ef3b4b6d268c4758046e5a to your computer and use it in GitHub Desktop.
Save aigarius/7e247cff03ef3b4b6d268c4758046e5a to your computer and use it in GitHub Desktop.
Predict future balance of an asset account considering outstanding salary income, bills and credit card balances/resets
import requests
from datetime import datetime
import appdaemon.plugins.hass.hassapi as hass
app_token = "<FIREFLY_PERSONAL_ACCESS_TOKEN>"
firefly_url = "<FIREFLY_URL>"
main_account_name = "Main account"
salary_amount = 4000
salary_date = 28
class UpdateFuture(hass.Hass):
def initialize(self):
# Run once per hour
self.run_every(self.update_future, "now", 60*60)
def update_future(self, kwargs):
ent = self.get_entity("sensor.firefly3_main_account_future")
if not ent.exists():
ent.add(
state=0.0,
attributes={
"native_value": 0.0,
"native_unit_of_measurement": "EUR",
"state_class": "measurement",
"device_class": "monetary",
"current_balance_date": datetime.now(),
"future_target_date": datetime.now(),
})
(value, balance_date, future_date) = self._calculate_future()
ent.set_state(
state=value,
attributes={
"native_value": value,
"current_balance_date": balance_date,
"future_target_date": future_date,
})
def _calculate_future(self):
r = requests.get(
firefly_url + "/api/v1/accounts?type=asset",
headers={
"Authorization": "Bearer " + app_token,
"Accept": "application/vnd.api+json",
"Content-Type": "application/json",
})
data = r.json()
for account in data["data"]:
if not "attributes" in account or "name" not in account["attributes"]:
continue
if account["attributes"]["name"] != "Sparkasse giro":
continue
return (
account["attributes"]["current_balance"],
datetime.fromisoformat(account["attributes"]["current_balance_date"]),
prediction_date,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment