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

8
.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

6
.idea/GitLink.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="uk.co.ben_gibson.git.link.SettingsState">
<option name="host" value="e0f86390-1091-4871-8aeb-f534fbc99cf0" />
</component>
</project>

30
.idea/SolarCalculator.iml generated Normal file
View File

@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="FacetManager">
<facet type="django" name="Django">
<configuration>
<option name="rootFolder" value="$MODULE_DIR$" />
<option name="settingsModule" value="SolarCalculator/settings.py" />
<option name="manageScript" value="$MODULE_DIR$/manage.py" />
<option name="environment" value="&lt;map/&gt;" />
<option name="doNotUseTestRunner" value="false" />
<option name="trackFilePattern" value="migrations" />
</configuration>
</facet>
</component>
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="jdk" jdkName="Python 3.10 (SolarCalculator) (2)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="TemplatesService">
<option name="TEMPLATE_CONFIGURATION" value="Django" />
<option name="TEMPLATE_FOLDERS">
<list>
<option value="$MODULE_DIR$/templates" />
</list>
</option>
</component>
</module>

View File

@@ -0,0 +1,35 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="DuplicatedCode" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="JSHint" enabled="true" level="ERROR" enabled_by_default="true" />
<inspection_tool class="PyBroadExceptionInspection" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
<inspection_tool class="PyMethodMayBeStaticInspection" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
<inspection_tool class="PyPep8Inspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<option name="ignoredErrors">
<list>
<option value="E266" />
<option value="W605" />
<option value="E722" />
</list>
</option>
</inspection_tool>
<inspection_tool class="PyPep8NamingInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<option name="ignoredErrors">
<list>
<option value="N806" />
<option value="N803" />
<option value="N802" />
</list>
</option>
</inspection_tool>
<inspection_tool class="SpellCheckingInspection" enabled="false" level="TYPO" enabled_by_default="false">
<option name="processCode" value="true" />
<option name="processLiterals" value="true" />
<option name="processComments" value="true" />
</inspection_tool>
<inspection_tool class="SqlCurrentSchemaInspection" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="SqlResolveInspection" enabled="false" level="ERROR" enabled_by_default="false" />
</profile>
</component>

View File

@@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

4
.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.10 (SolarCalculator) (2)" project-jdk-type="Python SDK" />
</project>

8
.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/SolarCalculator.iml" filepath="$PROJECT_DIR$/.idea/SolarCalculator.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

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()

BIN
db.sqlite3 Normal file

Binary file not shown.

22
manage.py Executable file
View File

@@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'SolarCalculator.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()

10
requirements.txt Normal file
View File

@@ -0,0 +1,10 @@
asgiref==3.5.2
Django==4.1.2
django-material==1.11.3
numpy==1.23.4
numpy-financial==1.0.0
pandas==1.5.0
python-dateutil==2.8.2
pytz==2022.5
six==1.16.0
sqlparse==0.4.3

38
templates/Input.html Normal file
View File

@@ -0,0 +1,38 @@
<!DOCTYPE html>
<html>
{% load static %}
{% load material_form %}
<head>
{% include 'material/includes/material_css.html' %}
{% include 'material/includes/material_js.html' %}
</head>
<style>
@media print {
.noprint {
display: none;
}
}
</style>
<body>
<div style="margin-left:3%;margin-top:1%">
<h5>{{ Title }}</h5>
<div class="noprint">
<form action='' method='post'>{% csrf_token %}
{% form form=form %}{% endform %}
<input type='submit' value='Submit'/>
</form>
</div>
<br>
<div class="column-list"></div>
<div class="Summary">
{{ DF_1|safe }}
</div>
</div>
</body>
</html>

67
templates/Output.html Normal file
View File

@@ -0,0 +1,67 @@
<!DOCTYPE html>
<html>
{% load static %}
{% load material_form %}
<head>
{% include 'material/includes/material_css.html' %}
{% include 'material/includes/material_js.html' %}
</head>
<style>
@media print {
.noprint {
display: none;
}
}
table td, table th {
border: 1px solid;
padding-right: 20px;
padding-bottom: 0px;
padding-top: 0px;
text-align: right;
}
.table0 td, table th{text-align: center}
</style>
<body>
<div style="margin-left:1%;margin-top:1%;margin-right:1%">
<h5 align="center"><u>{{ Title }}</u></h5>
<div class="noprint">
<form action='' method='post'>{% csrf_token %}
{% form form=form %}{% endform %}
<input type='submit' value='Submit'/>
</form>
</div>
<br>
<div class="column-list"></div>
<div class="Metric">
{{ DF_0|safe }}
</div>
<br>
<div class="Summary">
{{ DF_2|safe }}
</div>
<br>
<div class="Summary">
{{ DF_1|safe }}
</div>
<h5 style="font-size: 11px">
The above is a financial simulation of reality which may turn out to be different based on a number of factors
including but not restricted to policy changes, unit generaton variations, revision in tariff and net metering guidelines etc.
Network charges is assumed to be charged at 60% of generated units at Rs.0.85/unit.
Solar power is assumed to be generated at 4KWH/KW of installation between Mar and Aug, 3.5 KW between Sep-Oct & Jan-Feb and 3 KW during Nov-Dec.
Tariff used is as per TNEB guidelines as at Oct 18, 2022.
</h5>
</div>
</body>
</html>