Spaces:
Runtime error
Runtime error
Download app.py from amrose61/utility_expense_predictor: direct link, hf CLI and curl.
- Browser
- Download file 14.5 kB
-
https://huggingface.co/spaces/amrose61/utility_expense_predictor/resolve/main/app.py
- Command line
-
hf download hf://spaces/amrose61/utility_expense_predictor/app.py
-
curl -L -o app.py https://huggingface.co/spaces/amrose61/utility_expense_predictor/resolve/main/app.py
14.5 kB
| # -*- coding: utf-8 -*- | |
| """ | |
| Created on Sun Dec 11 15:09:37 2022 | |
| @author: amand | |
| """ | |
| import streamlit as st | |
| import numpy as np | |
| import pandas as pd | |
| import pickle as pkl | |
| from datetime import datetime, timedelta | |
| from dateutil import relativedelta | |
| import plotly.graph_objects as go | |
| from pandas.tseries.offsets import DateOffset | |
| import math | |
| #test | |
| with open("energy_pred_df.pkl", "rb") as file1: | |
| df = pkl.load(file1) | |
| with open("energy_model.pkl", "rb") as file2: | |
| emodel = pkl.load(file2) | |
| with open("gas_model.pkl", "rb") as file3: | |
| gmodel = pkl.load(file3) | |
| st.title("Electricity & Gas Utility Expense Forecast Tool") | |
| st.caption("This tool predicts electric and gas expense through the end of 2023 based on data from annual same store electricity and gas expenses from 2011 to 2021. The model performance is tested against actual expenses in 2022 through October.") | |
| with st.expander("Expand to read more about the process"): | |
| st.write(""" | |
| Initial assumptions when developing the data set for this exercise were that the majority of variance in expense is based on the number of apartment units and the CPI rate. | |
| I also believed that occupancy rates would impact the energy usage and expense although I discovered this had minimal to no impact. As you will see below, all forecasts are | |
| compared to this simpler approach (last year's expense per unit increased by CPI and applied to current units). | |
| """) | |
| st.write("In total my dataset included the following factors. (Not all were included in every model):") | |
| st.markdown("- Total unit count") | |
| st.markdown("- Energy-specific published CPI values") | |
| st.markdown("- Unit counts in 4 major markets (Minnesota, Texas, Florida, and Georgia)") | |
| st.markdown("- Average monthly temperatures in 4 major markets") | |
| st.markdown("- Weighted average monthly temperature based on unit count") | |
| st.markdown("- Monthly average daily spot price for natural gas") | |
| st.markdown("- Month as a categorical feature for seasonality") | |
| st.subheader("Please provide some assumptions to generate the forecast:") | |
| fh_years = 2023 -2022 | |
| fh_months = fh_years * 12+2 | |
| st.caption("The default for the below is to use the historical 5 year trend. Please make adjustments as necessary") | |
| units_est = st.slider(label = "All same store unit totals", min_value=18000, max_value=30000, step = 100, value = 20500) | |
| MN_est = st.slider(label = "Minnesota units annual growth rate", min_value=-5.00, max_value=10.00, step = 0.01, value = 2.80, format = "%d.00%%")/100 | |
| TX_est = st.slider(label = "Texas units annual growth rate", min_value=-5.00, max_value=10.00, step = 0.01, value = 2.30, format = "%d.00%%")/100 | |
| FL_est = st.slider(label = "Florida units annual growth rate", min_value=-5.00, max_value=10.00, step = 0.01, value = 1.90, format = "%d.00%%")/100 | |
| GA_est = st.slider(label = "Georgia units annual growth rate", min_value=-5.00, max_value=10.00, step = 0.01, value = 2.70, format = "%d.00%%")/100 | |
| annual_cpi = st.slider(label = "The expected CPI rate is energy specific.", min_value=-20.0, max_value=35.0, step = 0.5, value = 31.0, format = "%d.00%%")/100 | |
| base = df.index[-1] | |
| fcst_period = [base + relativedelta.relativedelta(months=i) for i in range(1,fh_months+1)] | |
| forecast = pd.DataFrame(columns =['Date', 'Unit_Count','CPI_Energy', | |
| 'Electricity_Expense', 'Gas_Expense', | |
| 'MN_units', 'TX_units', 'FL_units', 'GA_units', | |
| 'Other_units', 'MN_mon_avg_temp', 'TX_mon_avg_temp', | |
| 'FL_mon_avg_temp', 'GA_mon_avg_temp', 'Price', | |
| 'Year', 'Month','weighted_avg_temp']) | |
| forecast.set_index("Date", inplace=True) | |
| for t in fcst_period: | |
| if t.year == base.year: | |
| units = df.Unit_Count[-1] | |
| cpi = df.CPI_Energy.loc[t - DateOffset(years=1)] * (1+annual_cpi) | |
| electric = None | |
| Gas = None | |
| mn_unit = df.MN_units[-1] | |
| tx_unit = df.TX_units[-1] | |
| fl_unit = df.FL_units[-1] | |
| ga_unit = df.GA_units[-1] | |
| other_units = df.Other_units[-1] | |
| mn_temp = df.MN_mon_avg_temp.loc[t - DateOffset(years=1)] | |
| tx_temp = df.TX_mon_avg_temp.loc[t - DateOffset(years=1)] | |
| fl_temp = df.FL_mon_avg_temp.loc[t - DateOffset(years=1)] | |
| ga_temp = df.GA_mon_avg_temp.loc[t - DateOffset(years=1)] | |
| price = df.Price.loc[t - DateOffset(years=1)] | |
| year = t.year | |
| month = t.month | |
| w_temp = (mn_unit*mn_temp + tx_unit*tx_temp + fl_unit*fl_temp + ga_unit*ga_temp)/(mn_unit + tx_unit + fl_unit + ga_unit) | |
| lst = [units,cpi,electric,Gas,mn_unit,tx_unit,fl_unit,ga_unit,other_units,mn_temp,tx_temp,fl_temp,ga_temp,price,year,month,w_temp] | |
| forecast.loc[t] = lst | |
| else: | |
| units = units_est | |
| try: | |
| cpi = df.CPI_Energy.loc[t - DateOffset(years=1)] * (1+annual_cpi) | |
| except KeyError: | |
| cpi = forecast.CPI_Energy.loc[t - DateOffset(years=1)] * (1+annual_cpi) | |
| electric = None | |
| Gas = None | |
| mn_unit = forecast.MN_units.loc[datetime(2022,12,1)]*(1+MN_est) | |
| tx_unit = forecast.TX_units.loc[datetime(2022,12,1)]*(1+TX_est) | |
| fl_unit = forecast.FL_units.loc[datetime(2022,12,1)]*(1+FL_est) | |
| ga_unit = forecast.GA_units.loc[datetime(2022,12,1)]*(1+GA_est) | |
| other_units = units - mn_unit - tx_unit - fl_unit - ga_unit | |
| try: | |
| mn_temp = df.MN_mon_avg_temp.loc[t - DateOffset(years=1)] | |
| except KeyError: | |
| mn_temp = forecast.MN_mon_avg_temp.loc[t - DateOffset(years=1)] | |
| try: | |
| tx_temp = df.TX_mon_avg_temp.loc[t - DateOffset(years=1)] | |
| except KeyError: | |
| tx_temp = forecast.TX_mon_avg_temp.loc[t - DateOffset(years=1)] | |
| try: | |
| fl_temp = df.FL_mon_avg_temp.loc[t - DateOffset(years=1)] | |
| except KeyError: | |
| fl_temp = forecast.FL_mon_avg_temp.loc[t - DateOffset(years=1)] | |
| try: | |
| ga_temp = df.GA_mon_avg_temp.loc[t - DateOffset(years=1)] | |
| except KeyError: | |
| ga_temp = forecast.GA_mon_avg_temp.loc[t - DateOffset(years=1)] | |
| try: | |
| price = df.Price.loc[t - DateOffset(years=1)] * (1+annual_cpi) | |
| except KeyError: | |
| price = forecast.Price.loc[t - DateOffset(years=1)] * (1+annual_cpi) | |
| year = t.year | |
| month = t.month | |
| w_temp = (mn_unit*mn_temp + tx_unit*tx_temp + fl_unit*fl_temp + ga_unit*ga_temp)/(mn_unit + tx_unit + fl_unit + ga_unit) | |
| lst = [units,cpi,electric,Gas,mn_unit,tx_unit,fl_unit,ga_unit,other_units,mn_temp,tx_temp,fl_temp,ga_temp,price,year,month,w_temp] | |
| forecast.loc[t] = lst | |
| X = pd.get_dummies(forecast.Month) | |
| X.columns = ['Month_1','Month_2','Month_3','Month_4','Month_5','Month_6','Month_7','Month_8','Month_9','Month_10','Month_11','Month_12'] | |
| X = X.join(forecast[['Unit_Count', 'CPI_Energy','MN_units', 'TX_units', 'FL_units', 'GA_units', 'weighted_avg_temp']]) | |
| forecast['ml_forecast_e'] = emodel.predict(X) | |
| X = X.join(forecast.Price) | |
| forecast['ml_forecast_g'] = gmodel.predict(X) | |
| example = pd.concat([df,forecast]) | |
| units_df = df[['Unit_Count','MN_units','TX_units','FL_units','GA_units','Other_units']] | |
| units_df = pd.concat([units_df,forecast]) | |
| units_df['Year'] = pd.DatetimeIndex(units_df.index).year | |
| units_df = units_df.groupby('Year').agg( | |
| TotalUnits = pd.NamedAgg('Unit_Count','mean'), | |
| MNUnits = pd.NamedAgg('MN_units','mean'), | |
| TXUnits = pd.NamedAgg('TX_units','mean'), | |
| FLUnits = pd.NamedAgg('FL_units','mean'), | |
| GAUnits = pd.NamedAgg('GA_units','mean'), | |
| OtherUnits = pd.NamedAgg('Other_units','mean')) | |
| units_df = units_df.fillna(0) | |
| units_df = units_df.astype({'TotalUnits':'int', | |
| 'MNUnits':'int', | |
| 'TXUnits':'int', | |
| 'FLUnits':'int', | |
| 'GAUnits':'int', | |
| 'OtherUnits':'int',}) | |
| units_df.columns = ['Total Units', 'Minnesota Units', 'Texas Units', 'Florida Units', 'Georgia Units','All Other Units'] | |
| temp_df = df[['MN_mon_avg_temp', 'TX_mon_avg_temp','FL_mon_avg_temp', 'GA_mon_avg_temp', 'weighted_avg_temp']] | |
| temp_df = pd.concat([temp_df, forecast[['MN_mon_avg_temp', 'TX_mon_avg_temp','FL_mon_avg_temp', 'GA_mon_avg_temp', 'weighted_avg_temp']]]) | |
| st.subheader("Same Store Unit Growth 2011-2023") | |
| units_chart = go.Figure() | |
| units_chart.add_trace(go.Scatter(x=df.index, y=df.Unit_Count, name='Actual',mode='lines')) | |
| units_chart.add_trace(go.Scatter(x=forecast.index, y=forecast.Unit_Count, name = 'Forecast', mode='lines', | |
| line = dict(color = 'royalblue', dash = 'dash'))) | |
| st.plotly_chart(units_chart, theme="streamlit") | |
| st.dataframe(data = units_df.T) | |
| st.subheader("Monthly Average Temperatures in 4 Major Markets with Forecast (°C)") | |
| temp_chart = go.Figure() | |
| temp_chart.add_trace(go.Scatter(x=temp_df.index, y=temp_df.weighted_avg_temp, name='Weighted-Average',mode='lines',line = dict(color = 'gray'))) | |
| temp_chart.add_trace(go.Scatter(x=temp_df.index, y=temp_df.MN_mon_avg_temp, name='MSP',mode='lines',line = dict(color = 'steelblue'))) | |
| temp_chart.add_trace(go.Scatter(x=temp_df.index, y=temp_df.TX_mon_avg_temp, name='DAL',mode='lines',line = dict(color = 'red'))) | |
| temp_chart.add_trace(go.Scatter(x=temp_df.index, y=temp_df.GA_mon_avg_temp, name='ATL',mode='lines',line = dict(color = 'green'))) | |
| temp_chart.add_trace(go.Scatter(x=temp_df.index, y=temp_df.FL_mon_avg_temp, name='FL',mode='lines',line = dict(color = 'yellow'))) | |
| st.plotly_chart(temp_chart, theme="streamlit") | |
| temp_df.columns = ['MSP monthly avg temp','Dallas monthly avg temp','Florida monthly avg temp','ATL monthly avg temp','Weighted Average'] | |
| #st.dataframe(data = temp_df.T) | |
| st.subheader("Net Electric Expense with Forecast") | |
| electric_df = example[['Electricity_Expense','CPI_Energy','Unit_Count','ml_forecast_e']] | |
| electric_df['next_year'] = electric_df.index - DateOffset(years=-1) | |
| s1 = electric_df.groupby('next_year').agg({'Electricity_Expense':'max', 'CPI_Energy':'max', 'Unit_Count':'max', 'ml_forecast_e':'max'}) | |
| s1.columns = ['LY_expense','LY_cpi','LY_units','LY_mlF'] | |
| new_df = electric_df.join(s1, how ='outer') | |
| new_df['simple_fcst'] = new_df.LY_expense/new_df.LY_units * (new_df.CPI_Energy/new_df.LY_cpi) * new_df.Unit_Count | |
| new_df['simp_per_error'] = abs((new_df.simple_fcst-new_df.Electricity_Expense)/new_df.Electricity_Expense) | |
| new_df['simp_sq_error'] = (new_df.simple_fcst-new_df.Electricity_Expense) **2 | |
| new_df['ml_per_error'] = abs((new_df.ml_forecast_e-new_df.Electricity_Expense)/new_df.Electricity_Expense) | |
| new_df['ml_sq_error'] = (new_df.ml_forecast_e-new_df.Electricity_Expense) **2 | |
| new_df['Year'] = pd.DatetimeIndex(new_df.index).year | |
| elec_chart = go.Figure() | |
| elec_chart.add_trace(go.Scatter(x=new_df.index[:-12], y=new_df.Electricity_Expense[:-12], name='Actual',mode='lines',line = dict(color = 'black', dash = 'solid'))) | |
| elec_chart.add_trace(go.Scatter(x=new_df.index[:-12], y=new_df.simple_fcst[:-12], name = 'Simple Forecast', mode='lines', line = dict(color = 'gray', dash = 'dash'))) | |
| elec_chart.add_trace(go.Scatter(x=new_df.index[:-12], y=new_df.ml_forecast_e[:-12], name = 'ML Forecast', mode='lines', line = dict(color = 'red', dash = 'dash'))) | |
| st.plotly_chart(elec_chart, theme="streamlit") | |
| with st.expander("Expand to read more about the process"): | |
| st.write(""" | |
| After trying to fit this data with a time series model like ARIMA, I had a difficult time finding stationarity in the data. I ended up with a | |
| gradient boost regressor. The data excluded from this model include the gas expense, all other units count | |
| """) | |
| new_df = new_df[(new_df.index >= datetime(2022,1, 1)) & (new_df.index < datetime(2022,10, 1))] | |
| new_df = new_df[['Electricity_Expense','simple_fcst','simp_per_error','simp_sq_error','ml_forecast_e', 'ml_per_error','ml_sq_error']] | |
| elec_df = new_df[1:-1] | |
| elec_df.simp_sq_error = elec_df.simp_sq_error.apply(lambda x: math.sqrt(x)) | |
| elec_df.ml_sq_error = elec_df.ml_sq_error.apply(lambda x: math.sqrt(x)) | |
| elec_df.columns = ['Actual Electric Expense', 'Simple Forecast', 'Simple Forecast - MAPE', 'Simple Forecast - RMSE', 'Machine Learning Forecast', 'ML Forecast - MAPE', 'ML Forecast - RMSE'] | |
| st.dataframe(data = elec_df.T) | |
| st.subheader("Net Gas Expense with Forecast") | |
| gas_df = df[['Gas_Expense','Price','weighted_avg_temp','ml_forecast_g','Unit_Count']] | |
| gas_df = pd.concat([gas_df,forecast[['Gas_Expense','Price','weighted_avg_temp','ml_forecast_g','Unit_Count']]]) | |
| gas_df['next_year'] = gas_df.index - DateOffset(years=-1) | |
| s1 = gas_df.groupby('next_year').agg({'Gas_Expense':'max', 'Price':'max', 'weighted_avg_temp':'max', 'ml_forecast_g':'max', 'Unit_Count':'max'}) | |
| s1.columns = ['LY_expense','LY_price','LY_temp','LY_mlF','LY_units'] | |
| new_gas = gas_df.join(s1, how ='outer') | |
| new_gas['simple_fcst'] = new_gas.LY_expense/new_gas.LY_units * (new_gas.Price/new_gas.LY_price) * new_gas.Unit_Count | |
| new_gas['simp_per_error'] = abs((new_gas.simple_fcst-new_gas.Gas_Expense)/new_gas.Gas_Expense) | |
| new_gas['simp_sq_error'] = (new_gas.simple_fcst-new_gas.Gas_Expense) **2 | |
| new_gas['ml_per_error'] = abs((new_gas.ml_forecast_g-new_gas.Gas_Expense)/new_gas.Gas_Expense) | |
| new_gas['ml_sq_error'] = (new_gas.ml_forecast_g-new_gas.Gas_Expense) **2 | |
| new_gas['Year'] = pd.DatetimeIndex(new_gas.index).year | |
| gas_chart = go.Figure() | |
| gas_chart.add_trace(go.Scatter(x=new_gas.index[:-12], y=new_gas.Gas_Expense[:-12], name='Actual',mode='lines', line = dict(color = 'black', dash = 'solid'))) | |
| gas_chart.add_trace(go.Scatter(x=new_gas.index[:-12], y=new_gas.simple_fcst[:-12], name = 'Simple Forecast', mode='lines', line = dict(color = 'gray', dash = 'dash'))) | |
| gas_chart.add_trace(go.Scatter(x=new_gas.index[:-12], y=new_gas.ml_forecast_g[:-12], name = 'ML Forecast', mode='lines', line = dict(color = 'red', dash = 'dash'))) | |
| st.plotly_chart(gas_chart, theme="streamlit") | |
| gas_df = new_gas[(new_gas.index >= datetime(2022,1, 1)) & (new_gas.index < datetime(2022,10, 1))] | |
| gas_df = gas_df[['Gas_Expense','simple_fcst','simp_per_error','simp_sq_error','ml_forecast_g', 'ml_per_error','ml_sq_error']] | |
| gas_df = gas_df[1:-1] | |
| gas_df.simp_sq_error = gas_df.simp_sq_error.apply(lambda x: math.sqrt(x)) | |
| gas_df.ml_sq_error = gas_df.ml_sq_error.apply(lambda x: math.sqrt(x)) | |
| gas_df.columns = ['Actual Gas Expense', 'Simple Forecast', 'Simple Forecast - MAPE', 'Simple Forecast - RMSE', 'Machine Learning Forecast', 'ML Forecast - MAPE', 'ML Forecast - RMSE'] | |
| st.dataframe(data = gas_df.T) | |