first commit1

This commit is contained in:
ajay
2023-05-09 14:18:41 +05:30
commit 01f3d0939a
20 changed files with 596 additions and 0 deletions

View File

16
SolarCalculator/asgi.py Normal file
View File

@@ -0,0 +1,16 @@
"""
ASGI config for SolarCalculator project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'SolarCalculator.settings')
application = get_asgi_application()

19
SolarCalculator/forms.py Normal file
View File

@@ -0,0 +1,19 @@
from django import forms
from material import *
class SolarForm(forms.Form):
name = forms.CharField(required=True, label="Name", initial='Mr.ABC')
kw_installed = forms.FloatField(required=True, label="KW Installed", min_value=0, max_value=1e100, initial=4.81)
initial_cost = forms.IntegerField(required=True, label="Initial Cost of Installation", initial=415000)
amc = forms.IntegerField(required=True, label="Annual Recurring Cost", initial=9000)
units1 = forms.IntegerField(required=True, label="Units Consumed (Jan-Feb)", initial=1200)
units2 = forms.IntegerField(required=True, label="Units Consumed (Mar-Apr)", initial=1600)
units3 = forms.IntegerField(required=True, label="Units Consumed (May-Jun)", initial=1800)
units4 = forms.IntegerField(required=True, label="Units Consumed (Jul-Aug)", initial=1400)
units5 = forms.IntegerField(required=True, label="Units Consumed (Sep-Oct)", initial=1600)
units6 = forms.IntegerField(required=True, label="Units Consumed (Nov-Dec)", initial=1000)
layout = Layout(
Row('name', 'kw_installed', 'initial_cost', 'amc'),
Row('units1', 'units2', 'units3', 'units4', 'units5', 'units6'),
)

132
SolarCalculator/settings.py Normal file
View File

@@ -0,0 +1,132 @@
"""
Django settings for SolarCalculator project.
Generated by 'django-admin startproject' using Django 4.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-w&c9bz6fof7-amo)&tvl%9mcz_hl744sos5pv-q0#ua&kaspt_'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Installed Apps
'material',
'material.frontend',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'SolarCalculator.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates']
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'SolarCalculator.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
# STATIC_ROOT = "/var/www/solarcalc.duckdns.org/static/"
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO','https')
CSRF_TRUSTED_ORIGINS=[
'https://solarcalc.duckdns.org',
]

23
SolarCalculator/urls.py Normal file
View File

@@ -0,0 +1,23 @@
"""SolarCalculator URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.SolarCalculatorView, name='SolarCalculator'),
]

150
SolarCalculator/views.py Normal file
View File

@@ -0,0 +1,150 @@
# Create your views here.
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render, reverse
from django.template import loader
import pandas as pd
import numpy as np
from .forms import *
import io
import numpy_financial as npf
def PrC(units_consumed):
cutoff = 500
price_data1 = pd.DataFrame(np.array([[100, 0], [200, 2.25], [400, 4.5],
[500, 6]]),
columns=['Unit_Ceiling', 'Rate'])
price_data2 = pd.DataFrame(np.array([[100, 0], [400, 4.5], [500, 6],
[600, 8], [800, 9], [1000, 10],
[np.inf, 11]]),
columns=['Unit_Ceiling', 'Rate'])
if units_consumed < 0:
return 0
elif units_consumed > cutoff:
DB = price_data2
else:
DB = price_data1
DB['prev_slab'] = DB['Unit_Ceiling'].shift(1).fillna(0)
DB['cutoff'] = units_consumed - DB['prev_slab']
DB = DB.loc[DB['cutoff'] > 0, :].drop(['cutoff'], axis=1).reset_index(drop=True)
DB.at[DB.index[-1], 'Unit_Ceiling'] = units_consumed
bill = np.sum((DB['Unit_Ceiling'] - DB['prev_slab']) * DB['Rate'])
return bill
def SolarCalculatorView(request):
if request.method == 'GET':
form = SolarForm()
return render(request, 'Input.html', {
'form': form,
'Title': 'TNEB Solar Returns Calculator'
})
else:
# A POST request: Handle Form Upload
form = SolarForm(request.POST) # Bind data from request.POST into a PostForm
name = request.POST.get('name', '')
kw_installed = float(request.POST.get('kw_installed', ''))
initial_cost = int(request.POST.get('initial_cost', ''))
amc = int(request.POST.get('amc', ''))
units1 = int(request.POST.get('units1', ''))
units2 = int(request.POST.get('units2', ''))
units3 = int(request.POST.get('units3', ''))
units4 = int(request.POST.get('units4', ''))
units5 = int(request.POST.get('units5', ''))
units6 = int(request.POST.get('units6', ''))
# Savings Calculator
SolarSavings = pd.DataFrame([units1 + units2 + units3 + units4 + units5 + units6]
, columns=['Units Consumed'])
SolarSavings['Solar Units Generated'] = kw_installed * (4 * 6 + 3.5 * 4 + 3 * 2) * 30
SolarSavings['Bill Without Solar'] = PrC(units1) + PrC(units2) + PrC(units3) + PrC(units4) + PrC(units5) + PrC(
units6)
SolarSavings['Gross Bill With Solar'] = PrC(units1 - kw_installed * 3.5 * 60) + \
PrC(units2 - kw_installed * 4 * 60) + \
PrC(units3 - kw_installed * 4 * 60) + \
PrC(units4 - kw_installed * 4 * 60) + \
PrC(units5 - kw_installed * 3.5 * 60) + \
PrC(units6 - kw_installed * 3 * 60)
SolarSavings['Network Charges'] = SolarSavings['Solar Units Generated'] * .6 * .85
SolarSavings['Net Bill With Solar'] = SolarSavings['Gross Bill With Solar'] + SolarSavings['Network Charges']
SolarSavings['Annual Savings'] = SolarSavings['Bill Without Solar'] - SolarSavings['Net Bill With Solar']
# Cashflow at Inflation 4%, 6%, 8%
Cashflow = pd.DataFrame(list(range(1, 26)), columns=['Year'])
Cashflow['Investment & Charges'] = amc*1.0
# Initial Charges
Cashflow.loc[-1] = [0, initial_cost]
Cashflow.index = Cashflow.index + 1 # shifting index
Cashflow.sort_index(inplace=True)
Cashflow['Annual Savings'] = SolarSavings['Annual Savings'][0]
Cashflow.loc[0, 'Annual Savings'] = 0
Cashflow['Net Cashflow'] = Cashflow['Annual Savings'] - Cashflow['Investment & Charges']
Cashflow['4% Inflation'] = Cashflow['Annual Savings']*(1.04 ** Cashflow['Year']) - \
Cashflow['Investment & Charges']*(1.04 ** Cashflow['Year'])
Cashflow['6% Inflation'] = Cashflow['Annual Savings']*(1.06 ** Cashflow['Year']) - \
Cashflow['Investment & Charges']*(1.06 ** Cashflow['Year'])
Cashflow['8% Inflation'] = Cashflow['Annual Savings']*(1.08 ** Cashflow['Year']) - \
Cashflow['Investment & Charges']*(1.08 ** Cashflow['Year'])
P4Inf = pd.DataFrame(['4% Inflation'], columns=['Scenario'])
P4Inf['25 Year Return'] = "{0:.2%}".format(round(npf.irr(Cashflow['4% Inflation']), 4))
P4Inf['20 Year Return'] = "{0:.2%}".format(round(npf.irr(Cashflow['4% Inflation'][:21]), 4))
P4Inf['15 Year Return'] = "{0:.2%}".format(round(npf.irr(Cashflow['4% Inflation'][:16]), 4))
P4Inf['10 Year Return'] = "{0:.2%}".format(round(npf.irr(Cashflow['4% Inflation'][:11]), 4))
P4Inf['Payback Period'] = '{0} years'.format(len(np.cumsum(Cashflow['4% Inflation']
[np.cumsum(Cashflow['4% Inflation']) < 0])))
P4Inf['NPV @ 7% FD'] = "{:,.0f}".format(round(npf.npv(.07, Cashflow['4% Inflation']), 4))
P6Inf = pd.DataFrame(['6% Inflation'], columns=['Scenario'])
P6Inf['25 Year Return'] = "{0:.2%}".format(round(npf.irr(Cashflow['6% Inflation']), 4))
P6Inf['20 Year Return'] = "{0:.2%}".format(round(npf.irr(Cashflow['6% Inflation'][:21]), 4))
P6Inf['15 Year Return'] = "{0:.2%}".format(round(npf.irr(Cashflow['6% Inflation'][:16]), 4))
P6Inf['10 Year Return'] = "{0:.2%}".format(round(npf.irr(Cashflow['6% Inflation'][:11]), 4))
P6Inf['Payback Period'] = '{0} years'.format(len(np.cumsum(Cashflow['6% Inflation']
[np.cumsum(Cashflow['6% Inflation']) < 0])))
P6Inf['NPV @ 7% FD'] = "{:,.0f}".format(round(npf.npv(.07, Cashflow['6% Inflation']), 4))
P8Inf = pd.DataFrame(['8% Inflation'], columns=['Scenario'])
P8Inf['25 Year Return'] = "{0:.2%}".format(round(npf.irr(Cashflow['8% Inflation']), 4))
P8Inf['20 Year Return'] = "{0:.2%}".format(round(npf.irr(Cashflow['8% Inflation'][:21]), 4))
P8Inf['15 Year Return'] = "{0:.2%}".format(round(npf.irr(Cashflow['8% Inflation'][:16]), 4))
P8Inf['10 Year Return'] = "{0:.2%}".format(round(npf.irr(Cashflow['8% Inflation'][:11]), 4))
P8Inf['Payback Period'] = '{0} years'.format(len(np.cumsum(Cashflow['8% Inflation']
[np.cumsum(Cashflow['8% Inflation']) < 0])))
P8Inf['NPV @ 7% FD'] = "{:,.0f}".format(round(npf.npv(.07, Cashflow['8% Inflation']), 4))
Metric = pd.concat([P4Inf, P6Inf, P8Inf], axis=0, ignore_index=True)
# , '20 YEAR IRR', '15 YEAR IRR', '10 YEAR IRR', 'Payback Period',
# 'Discounted Payback'
# round(np.irr(Cashflow['Net Cashflow']), 2)
pd.options.display.float_format = '{:,.0f}'.format
buf = io.StringIO()
Metric.to_html(buf, escape=False, index=False, classes='" id = "table0')
Metric_HTML = buf.getvalue()
buf = io.StringIO()
Cashflow.to_html(buf, escape=False, index=False, classes='" id = "table1')
Cashflow_HTML = buf.getvalue()
buf = io.StringIO()
SolarSavings.to_html(buf, escape=False, index=False, classes='" id = "table2')
SolarSavings_HTML = buf.getvalue()
# IRR at 25, 20, 15, 10 Years
# Discounted Payback Period & Payback Period
return render(request, 'Output.html', {
'form': form,
'Title': f'Analysis of Investment in Solar Installation for {name}',
'DF_0': Metric_HTML,
'DF_1': Cashflow_HTML,
'DF_2': SolarSavings_HTML,
})

16
SolarCalculator/wsgi.py Normal file
View File

@@ -0,0 +1,16 @@
"""
WSGI config for SolarCalculator project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'SolarCalculator.settings')
application = get_wsgi_application()