kollis's picture
Create app.py
74e0921
raw
history blame
5.12 kB
import gradio as gr
import pandas as pd
import yfinance as yf
from datetime import timedelta,datetime
import pytz
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
from IPython.display import display
import functions
nifty_list = ["ADANIENT","ADANIPORTS","APOLLOHOSP","ASIANPAINT","AXISBANK","BAJAJ-AUTO","BAJFINANCE","BAJAJFINSV","BPCL","BHARTIARTL","BRITANNIA","CIPLA","COALINDIA","DIVISLAB","DRREDDY","EICHERMOT","GRASIM","HCLTECH","HDFCBANK","HDFCLIFE","HEROMOTOCO","HINDALCO","HINDUNILVR","ICICIBANK","ITC","INDUSINDBK","INFY","JSWSTEEL","KOTAKBANK","LTIM","LT","M&M","MARUTI","NTPC","NESTLEIND","ONGC","POWERGRID","RELIANCE","SBILIFE","SBIN","SUNPHARMA","TCS","TATACONSUM","TATAMOTORS","TATASTEEL","TECHM","TITAN","UPL","ULTRACEMCO","WIPRO","%5ENSEI"]
class Stocks:
def __init__(self, symbol):
self.symbol = symbol
self.data = self.fetch_data()
def fetch_data(self):
try:
# Construct the ticker symbol based on the first letter
ticker_symbol = self.symbol if self.symbol[0] == '%' else f"{self.symbol}.ns"
# Fetch historical data based on the constructed ticker symbol
data = yf.Ticker(ticker_symbol).history(period="10y", auto_adjust=True)
return data
except Exception as e:
print(f"Error fetching data for {self.symbol}: {e}")
return None
def currentdateavailability(self, curDate):
if curDate in self.data.index:
return curDate
else:
# Convert curDate to datetime and subtract one day
curDate_dt = datetime.strptime(curDate, "%Y-%m-%d")
newcDate_dt = curDate_dt - timedelta(days=1)
# Convert newcDate to string and call the method again
newcDate_str = newcDate_dt.strftime("%Y-%m-%d")
return self.currentdateavailability(newcDate_str)
def CurPrice(self, curDate=None):
curDate = self.currentdateavailability(curDate)
return self.data.loc[curDate, 'Close'] if curDate is not None else self.data.iloc[-1]['Close']
def NDayRet(self, N, curDate):
curDate = self.currentdateavailability(curDate)
NDate = self.data.index[self.data.index.get_loc(curDate) - N]
return self.data.loc[curDate, 'Close'] - self.data.loc[NDate, 'Close']
def DailyRet(self, curDate):
curDate = self.currentdateavailability(curDate)
return self.data.loc[curDate, 'Close'] - self.data.loc[curDate, 'Open']
def Last30daysPrice(self, curDate=None):
if curDate is not None:
curDate = self.currentdateavailability(curDate)
curDate_index = self.data.index.get_loc(curDate)
return self.data.iloc[curDate_index - 30:curDate_index]['Close'].values
else:
return self.data.iloc[-30:]['Close'].values
# This below function returns last 30 calender days close prices i.e. 30 days including holidays so less than 30 days close values are returned. Above fuction gives last 30 trading day close prices.
# def Last30daysPrice(self, curDate=None):
# curDate = self.currentdateavailability(curDate)
# if curDate is not None:
# # Calculate date 30 days ago
# curDate_dt = datetime.strptime(curDate, "%Y-%m-%d")
# days_ago_30 = curDate_dt - timedelta(days=30)
# thirty_days_ago_date = days_ago_30.strftime("%Y-%m-%d")
# # Ensure the availability of 30 days ago date
# thirty_days_ago_date = self.currentdateavailability(thirty_days_ago_date)
# # Get the index of curDate and 30 days ago date in the data
# curDate_index = self.data.index.get_loc(curDate)
# thirty_days_ago_index = self.data.index.get_loc(thirty_days_ago_date)
# # Return close values from 30 days ago to curDate in an array
# return self.data.iloc[thirty_days_ago_index:curDate_index + 1]['Close'].values
# else:
# return self.data.iloc[-30:]['Close'].values
stocks_dict = {symbol: Stocks(symbol) for symbol in nifty_list}
nifty_stocks = {symbol: stocks_dict[symbol] for symbol in nifty_list[:-1]}
nifty50 = {"nifty50": stocks_dict[nifty_list[-1]]}
title = "Portfolio tracking Nifty50 Stocks"
description = """
This App Demo is made for an Assignment. This Demo takes Initial Equity, Start Date, End Date, Time Window as inputs
"""
iface = gr.Interface(
fn=final_function,
inputs=[
gr.Textbox(label="Equity"),
gr.Textbox(label="Start Date"),
gr.Textbox(label="End Date"),
gr.Textbox(label="N-day Window")
],
outputs=[
gr.Image(type="pil"),
gr.Textbox(label="Strategy CAGR (%)"),
gr.Textbox(label="Strategy Volatility (%)"),
gr.Textbox(label="Strategy Sharpe Ratio"),
gr.Textbox(label="Benchmark CAGR (%)"),
gr.Textbox(label="Benchmark Volatility (%)"),
gr.Textbox(label="Benchmark Sharpe Ratio")
],
title=title,
description=description,
)
if __name__ == "__main__":
iface.launch()