from fastapi import FastAPI, Request from fastapi.responses import HTMLResponse from fastapi.templating import Jinja2Templates app = FastAPI() templates = Jinja2Templates(directory="templates") @app.get("/", response_class=HTMLResponse) async def read_root(request: Request): return templates.TemplateResponse("hello.html", {"request": request}) # from fastapi import FastAPI, Request, HTTPException # from fastapi.middleware.cors import CORSMiddleware # import warnings # import yfinance as yf # import pandas as pd # import requests # warnings.simplefilter(action='ignore', category=FutureWarning) # warnings.filterwarnings('ignore') # df_logo = pd.read_csv("https://raw.githubusercontent.com/jarvisx17/nifty500/main/Nifty500.csv") # async def calculate_profit(ltp, share, entry): # tgt1 = entry + (0.02 * entry) # tgt2 = entry + (0.04 * entry) # if ltp > tgt2: # profit = round((share / 3 * (tgt1-entry)) + (share / 3 * (tgt2-entry)) + (share / 3 * (ltp-entry)), 2) # elif ltp > tgt1 and ltp < tgt2: # profit = round((share / 3 * (tgt1-entry)) + ((share / 3) * 2 * (ltp-entry)), 2) # elif ltp > tgt1: # profit = round(share * (ltp-entry), 2) # else: # profit = round(share * (ltp-entry), 2) # return profit # async def info(ticker): # data = df_logo[df_logo['Symbol'] == ticker] # logo = data.logo.values[0] # Industry = data.Industry.values[0] # return logo, Industry # async def calculate_percentage_loss(buying_price, ltp): # percentage_loss = ((ltp - buying_price) / buying_price) * 100 # return f"{percentage_loss:.2f}%" # async def latestprice(ticker): # ticker = ticker.split(".")[0] # url = f"https://stock-market-lo24myw5sq-el.a.run.app/currentprice?ticker={ticker}" # response = requests.get(url) # if response.status_code == 200: # data = response.json() # return data['ltp'] # else: # return "N/A" # async def process_dataframe(df): # def get_rsi(close, lookback): # ret = close.diff() # up = [] # down = [] # for i in range(len(ret)): # if ret[i] < 0: # up.append(0) # down.append(ret[i]) # else: # up.append(ret[i]) # down.append(0) # up_series = pd.Series(up) # down_series = pd.Series(down).abs() # up_ewm = up_series.ewm(com=lookback - 1, adjust=False).mean() # down_ewm = down_series.ewm(com=lookback - 1, adjust=False).mean() # rs = up_ewm / down_ewm # rsi = 100 - (100 / (1 + rs)) # rsi_df = pd.DataFrame(rsi).rename(columns={0: 'RSI'}).set_index(close.index) # rsi_df = rsi_df.dropna() # return rsi_df[3:] # df['RSI'] = get_rsi(df['Close'], 14) # df['SMA20'] = df['Close'].rolling(window=20).mean() # df.drop(['Adj Close'], axis=1, inplace=True) # df = df.dropna() # return df # async def fin_data(ticker, startdate): # ltp = await latestprice(ticker) # df=yf.download(ticker, period="36mo", progress=False) # df = await process_dataframe(df) # df.reset_index(inplace=True) # df['Prev_RSI'] = df['RSI'].shift(1).round(2) # df = df.dropna() # df.reset_index(drop=True, inplace=True) # df[['Open', 'High', 'Low', 'Close',"RSI","SMA20"]] = df[['Open', 'High', 'Low', 'Close',"RSI", "SMA20"]].round(2) # df = df[200:] # df['Target1'] = df['High'] + (df['High'] * 0.02) # df['Target1'] = df['Target1'].round(2) # df['Target2'] = df['High'] + (df['High'] * 0.04) # df['Target2'] = df['Target2'].round(2) # df['Target3'] = "will announced" # df['SL'] = df['Low'] # df['LTP'] = ltp # date_index = df.loc[df['Date'] == startdate].index[0] # df = df.loc[date_index-1:] # df['Date'] = pd.to_datetime(df['Date']) # df.reset_index(drop=True,inplace=True) # return df # async def eqt(ticker, startdate, share_qty = 90): # df = await fin_data(ticker, startdate) # logo, Industry = await info(ticker) # entry = False # trading = False # shares_held = 0 # buy_price = 0 # target1 = False # target2 = False # target3 = False # tgt1 = 0 # tgt2 = 0 # tgt3 = 0 # total_profit = 0 # profits = [] # stop_loss = 0 # capital_list = [] # data = {} # totalshares = share_qty # ltp = await latestprice(ticker) # for i in range(1, len(df)-1): # try: # if df.at[i, 'RSI'] > 60 and df.at[i - 1, 'RSI'] < 60 and df.at[i, 'High'] < df.at[i + 1, 'High'] and not entry and not trading: # buy_price = df.at[i, 'High'] # stop_loss = df.at[i, 'Low'] # capital = buy_price * share_qty # capital_list.append(capital) # shares_held = share_qty # entdate = df.at[i+1, 'Date'] # entry_info = {"Date": pd.to_datetime(df.at[i+1, 'Date']).strftime('%d-%m-%Y'), "Note": "Entry Successful", "SL": stop_loss} # entryStock_info = df.iloc[i: i+1].reset_index(drop=True).to_dict(orient='records')[0] # Entry info # entryStock_info['Date'] = str(pd.to_datetime(df.at[i, 'Date']).strftime('%d-%m-%Y')) # data['StockInfo'] = {} # data['StockInfo']['Stock'] = {} # data['StockInfo']['Stock']['Name'] = ticker # data['StockInfo']['Stock']['Industry'] = Industry # data['StockInfo']['Stock']['Logo'] = logo # data['StockInfo']['Stock']['Status'] = "Active" # data['StockInfo']['Stock']['Levels'] = "Entry" # data['StockInfo']['Stock']['Values'] = entryStock_info # buying_price = entryStock_info['High'] # ltp = entryStock_info['LTP'] # data['StockInfo']['Stock']['Values']['Share QTY'] = share_qty # data['StockInfo']['Stock']['Values']['Invested Amount'] = (share_qty * buy_price).round(2) # data['StockInfo']['Stock']['Values']['Percentage'] = await calculate_percentage_loss(buying_price, ltp) # data['StockInfo']['Stock']['Values']['Total P/L'] = await calculate_profit(ltp, totalshares, buy_price) # data['StockInfo']['Entry'] = entry_info # entry = True # trading = True # if trading and not target1: # if (df.at[i + 1, 'High'] - buy_price) >= 0.02 * buy_price: # stop_loss = buy_price # target1 = True # tgt1 = 0.02 * buy_price * (share_qty / 3) # shares_held -= (share_qty / 3) # total_profit = round(tgt1,2) # target1_info = {"Date" : pd.to_datetime(df.at[i+1, 'Date']).strftime('%d-%m-%Y'), "Profit" : round(tgt1,2), "Remaining Shares": shares_held,"Note" : "TGT1 Achieved Successfully", "SL" : stop_loss} # data['StockInfo']['TGT1'] = target1_info # data['StockInfo']['Stock']['Values']['SL'] = stop_loss # data['StockInfo']['Stock']['Levels'] = data['StockInfo']['Stock']['Levels'] + " TGT1" # data['StockInfo']['Stock']['Values']['Total P/L'] = await calculate_profit(ltp, totalshares, buy_price) # data['StockInfo']['Entry']['Trade Status'] = "Trading is ongoing...." # if trading and target1 and not target2: # if (df.at[i + 1, 'High'] - buy_price) >= 0.04 * buy_price: # target2 = True # tgt2 = 0.04 * buy_price * (share_qty / 3) # total_profit += round(tgt2,2) # shares_held -= (share_qty / 3) # data['StockInfo']['Stock']['Levels'] = data['StockInfo']['Stock']['Levels'] + " TGT2" # data['StockInfo']['Stock']['Values']['Total P/L'] = await calculate_profit(ltp, totalshares, buy_price) # target2_info = {"Date" : pd.to_datetime(df.at[i+1, 'Date']).strftime('%d-%m-%Y'), "Profit" : round(tgt2,2), "Remaining Shares": shares_held,"Note" : "TGT2 Achieved Successfully", "SL" : stop_loss} # data['StockInfo']['TGT2'] = target2_info # data['StockInfo']['Entry']['Trade Status'] = "Trading is ongoing...." # if trading and target2 and not target3: # if (df.at[i + 1, 'Open'] < df.at[i + 1, 'SMA20'] < df.at[i + 1, 'Close']) or (df.at[i + 1, 'Open'] > df.at[i + 1, 'SMA20'] > df.at[i + 1, 'Close']): # stop_loss = df.at[i + 1, 'Low'] # data['StockInfo']['Stock']['Values']['SL'] = stop_loss # if df.at[i + 2, 'Low'] < stop_loss: # target3 = True # tgt3 = stop_loss * (share_qty / 3) # shares_held -= (share_qty / 3) # total_profit += round(tgt3,2) # target3_info = {"Date" : pd.to_datetime(df.at[i+1, 'Date']).strftime('%d-%m-%Y'), "Profit" : round(tgt3,2), "Remaining Shares": shares_held,"Note" : "TGT3 Achieved Successfully", "SL" : stop_loss} # data['StockInfo']['Stock']['Values']['Target3'] = tgt3 # data['StockInfo']['TGT3'] = target3_info # data['StockInfo']['Stock']['Levels'] = data['StockInfo']['Stock']['Levels'] +" TGT3" # data['StockInfo']['Stock']['Values']['Total P/L'] = await calculate_profit(ltp, totalshares, buy_price) # data['StockInfo']['TotalProfit'] = {} # data['StockInfo']['TotalProfit']['Profit'] = total_profit # data['StockInfo']['Entry']['Trade Status'] = "Trade closed successfully...." # data['StockInfo']['TotalProfit']['Trade Status'] = "Trade closed successfully...." # break # if (df.at[i + 1, 'Low'] < stop_loss and trading and entdate != df.at[i + 1, 'Date']) or stop_loss > ltp: # profit_loss = (shares_held * stop_loss) - (shares_held * buy_price) # total_profit += profit_loss # profits.append(total_profit) # shares_held = 0 # if data['StockInfo']['Stock']['Values']['Target3'] == "will announced" : # data['StockInfo']['Stock']['Values']['Target3'] = "-" # data['StockInfo']['Stock']['Status'] = "Closed" # data['StockInfo']['Stock']['Levels'] = data['StockInfo']['Stock']['Levels'] +" SL" # stoploss_info = {"Date" : pd.to_datetime(df.at[i+1, 'Date']).strftime('%d-%m-%Y'), "Profit" : total_profit, "SL" : stop_loss, "Remaining Shares": shares_held,"Note" : "SL Hit Successfully"} # data['StockInfo']['SL'] = stoploss_info # data['StockInfo']['TotalProfit'] = {} # data['StockInfo']['TotalProfit']['Profit'] = round(total_profit, 2) # data['StockInfo']['Stock']['Values']['Total P/L'] = round(total_profit, 2) # data['StockInfo']['Entry']['Trade Status'] = "Trade closed successfully...." # data['StockInfo']['TotalProfit']['Trade Status'] = "Trade closed successfully...." # buy_price = 0 # entry = False # trading = False # target1 = target2 = target3 = False # tgt1 = tgt2 = tgt3 = 0 # total_profit = 0 # break # except IndexError: # continue # if capital_list and profits: # return data # else: # if data: # return data # else: # data['StockInfo'] = {} # data['StockInfo']['Stock'] = {} # data['StockInfo']['Stock']['Name'] = ticker # data['StockInfo']['Stock']['Industry'] = Industry # data['StockInfo']['Stock']['Logo'] = logo # data['StockInfo']['Stock']['Status'] = "Waiting for entry" # entryStock_info = df.iloc[1: 2].reset_index(drop=True).to_dict(orient='records')[0] # Entry info # entryStock_info['Date'] = str(pd.to_datetime(df.at[1, 'Date']).strftime('%d-%m-%Y')) # data['StockInfo']['Stock']['Values'] = entryStock_info # data['StockInfo']['Stock']['Values']['Target3'] = "-" # data['StockInfo']['Info'] = "Don't buy stock right now...." # return data # app = FastAPI() # origins = ["*"] # app.add_middleware( # CORSMiddleware, # allow_origins=origins, # allow_credentials=True, # allow_methods=["*"], # allow_headers=["*"], # ) # @app.get('/') # def index(): # return {"message": "welcome to Investify"} # # @app.post('/process_stock_details') # # async def process_stock_details(request: Request): # # data = await request.json() # # processed_data = { # # 'symbol': data['symbol'], # # 'date': data['date'], # # 'share': data['share'] # # } # # return processed_data # @app.get('/data') # async def get_data(ticker: str, date: str, qty: int): # try: # response = await eqt(ticker, date, qty) # return response # except: # return {"Timeout" : "Error"} # # @app.post('/data') # # async def post_data(request: Request): # # data = await request.json() # # ticker = data.get('ticker') # # date = data.get('date') # # share_qty = data.get('qty') # # response = data_manager.get_equity_data(ticker, date, share_qty) # # return response # # if __name__ == "__main__": # # import uvicorn # # uvicorn.run(app, host="0.0.0.0", port=8000)