jarvisx17 commited on
Commit
0c5d56c
·
1 Parent(s): e4b8b8e

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +1 -250
main.py CHANGED
@@ -2,253 +2,8 @@ from fastapi.responses import HTMLResponse
2
  from fastapi.templating import Jinja2Templates
3
  from fastapi import FastAPI, Request, HTTPException
4
  from fastapi.middleware.cors import CORSMiddleware
 
5
  import warnings
6
- import yfinance as yf
7
- import pandas as pd
8
- import requests
9
-
10
- warnings.simplefilter(action='ignore', category=FutureWarning)
11
- warnings.filterwarnings('ignore')
12
-
13
- df_logo = pd.read_csv("https://raw.githubusercontent.com/jarvisx17/nifty500/main/Nifty500.csv")
14
-
15
- async def calculate_profit(ltp, share, entry):
16
- tgt1 = entry + (0.02 * entry)
17
- tgt2 = entry + (0.04 * entry)
18
- if ltp > tgt2:
19
- profit = round((share / 3 * (tgt1-entry)) + (share / 3 * (tgt2-entry)) + (share / 3 * (ltp-entry)), 2)
20
- elif ltp > tgt1 and ltp < tgt2:
21
- profit = round((share / 3 * (tgt1-entry)) + ((share / 3) * 2 * (ltp-entry)), 2)
22
- elif ltp > tgt1:
23
- profit = round(share * (ltp-entry), 2)
24
- else:
25
- profit = round(share * (ltp-entry), 2)
26
- return profit
27
-
28
- async def info(ticker):
29
- data = df_logo[df_logo['Symbol'] == ticker]
30
- logo = data.logo.values[0]
31
- Industry = data.Industry.values[0]
32
- return logo, Industry
33
-
34
- async def calculate_percentage_loss(buying_price, ltp):
35
- percentage_loss = ((ltp - buying_price) / buying_price) * 100
36
- return f"{percentage_loss:.2f}%"
37
-
38
- async def latestprice(ticker):
39
- ticker = ticker.split(".")[0]
40
- url = f"https://stock-market-lo24myw5sq-el.a.run.app/currentprice?ticker={ticker}"
41
- response = requests.get(url)
42
- if response.status_code == 200:
43
- data = response.json()
44
- return data['ltp']
45
- else:
46
- return "N/A"
47
-
48
- async def process_dataframe(df):
49
-
50
- def get_rsi(close, lookback):
51
- ret = close.diff()
52
- up = []
53
- down = []
54
- for i in range(len(ret)):
55
- if ret[i] < 0:
56
- up.append(0)
57
- down.append(ret[i])
58
- else:
59
- up.append(ret[i])
60
- down.append(0)
61
- up_series = pd.Series(up)
62
- down_series = pd.Series(down).abs()
63
- up_ewm = up_series.ewm(com=lookback - 1, adjust=False).mean()
64
- down_ewm = down_series.ewm(com=lookback - 1, adjust=False).mean()
65
- rs = up_ewm / down_ewm
66
- rsi = 100 - (100 / (1 + rs))
67
- rsi_df = pd.DataFrame(rsi).rename(columns={0: 'RSI'}).set_index(close.index)
68
- rsi_df = rsi_df.dropna()
69
- return rsi_df[3:]
70
-
71
- df['RSI'] = get_rsi(df['Close'], 14)
72
- df['SMA20'] = df['Close'].rolling(window=20).mean()
73
- df.drop(['Adj Close'], axis=1, inplace=True)
74
- df = df.dropna()
75
-
76
- return df
77
-
78
- async def fin_data(ticker, startdate):
79
-
80
- ltp = await latestprice(ticker)
81
- df=yf.download(ticker, period="36mo", progress=False)
82
- df = await process_dataframe(df)
83
- df.reset_index(inplace=True)
84
- df['Prev_RSI'] = df['RSI'].shift(1).round(2)
85
- df = df.dropna()
86
- df.reset_index(drop=True, inplace=True)
87
- df[['Open', 'High', 'Low', 'Close',"RSI","SMA20"]] = df[['Open', 'High', 'Low', 'Close',"RSI", "SMA20"]].round(2)
88
- df = df[200:]
89
- df['Target1'] = df['High'] + (df['High'] * 0.02)
90
- df['Target1'] = df['Target1'].round(2)
91
- df['Target2'] = df['High'] + (df['High'] * 0.04)
92
- df['Target2'] = df['Target2'].round(2)
93
- df['Target3'] = "will announced"
94
- df['SL'] = df['Low']
95
- df['LTP'] = ltp
96
- date_index = df.loc[df['Date'] == startdate].index[0]
97
- df = df.loc[date_index-1:]
98
- df['Date'] = pd.to_datetime(df['Date'])
99
- df.reset_index(drop=True,inplace=True)
100
-
101
- return df
102
-
103
- async def eqt(ticker, startdate, share_qty = 90):
104
-
105
- df = await fin_data(ticker, startdate)
106
- logo, Industry = await info(ticker)
107
- entry = False
108
- trading = False
109
- shares_held = 0
110
- buy_price = 0
111
- target1 = False
112
- target2 = False
113
- target3 = False
114
- tgt1 = 0
115
- tgt2 = 0
116
- tgt3 = 0
117
- total_profit = 0
118
- profits = []
119
- stop_loss = 0
120
- capital_list = []
121
- data = {}
122
- totalshares = share_qty
123
- ltp = await latestprice(ticker)
124
-
125
- for i in range(1, len(df)-1):
126
- try:
127
- 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:
128
- buy_price = df.at[i, 'High']
129
- stop_loss = df.at[i, 'Low']
130
- capital = buy_price * share_qty
131
- capital_list.append(capital)
132
- shares_held = share_qty
133
- entdate = df.at[i+1, 'Date']
134
- entry_info = {"Date": pd.to_datetime(df.at[i+1, 'Date']).strftime('%d-%m-%Y'), "Note": "Entry Successful", "SL": stop_loss}
135
- entryStock_info = df.iloc[i: i+1].reset_index(drop=True).to_dict(orient='records')[0] # Entry info
136
- entryStock_info['Date'] = str(pd.to_datetime(df.at[i, 'Date']).strftime('%d-%m-%Y'))
137
- data['StockInfo'] = {}
138
- data['StockInfo']['Stock'] = {}
139
- data['StockInfo']['Stock']['Name'] = ticker
140
- data['StockInfo']['Stock']['Industry'] = Industry
141
- data['StockInfo']['Stock']['Logo'] = logo
142
- data['StockInfo']['Stock']['Status'] = "Active"
143
- data['StockInfo']['Stock']['Levels'] = "Entry"
144
- data['StockInfo']['Stock']['Values'] = entryStock_info
145
- buying_price = entryStock_info['High']
146
- ltp = entryStock_info['LTP']
147
- data['StockInfo']['Stock']['Values']['Share QTY'] = share_qty
148
- data['StockInfo']['Stock']['Values']['Invested Amount'] = (share_qty * buy_price).round(2)
149
- data['StockInfo']['Stock']['Values']['Percentage'] = await calculate_percentage_loss(buying_price, ltp)
150
- data['StockInfo']['Stock']['Values']['Total P/L'] = await calculate_profit(ltp, totalshares, buy_price)
151
- data['StockInfo']['Entry'] = entry_info
152
- entry = True
153
- trading = True
154
-
155
- if trading and not target1:
156
- if (df.at[i + 1, 'High'] - buy_price) >= 0.02 * buy_price:
157
- stop_loss = buy_price
158
- target1 = True
159
- tgt1 = 0.02 * buy_price * (share_qty / 3)
160
- shares_held -= (share_qty / 3)
161
- total_profit = round(tgt1,2)
162
- 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}
163
- data['StockInfo']['TGT1'] = target1_info
164
- data['StockInfo']['Stock']['Values']['SL'] = stop_loss
165
- data['StockInfo']['Stock']['Levels'] = data['StockInfo']['Stock']['Levels'] + " TGT1"
166
- data['StockInfo']['Stock']['Values']['Total P/L'] = await calculate_profit(ltp, totalshares, buy_price)
167
- data['StockInfo']['Entry']['Trade Status'] = "Trading is ongoing...."
168
-
169
- if trading and target1 and not target2:
170
- if (df.at[i + 1, 'High'] - buy_price) >= 0.04 * buy_price:
171
- target2 = True
172
- tgt2 = 0.04 * buy_price * (share_qty / 3)
173
- total_profit += round(tgt2,2)
174
- shares_held -= (share_qty / 3)
175
- data['StockInfo']['Stock']['Levels'] = data['StockInfo']['Stock']['Levels'] + " TGT2"
176
- data['StockInfo']['Stock']['Values']['Total P/L'] = await calculate_profit(ltp, totalshares, buy_price)
177
- 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}
178
- data['StockInfo']['TGT2'] = target2_info
179
- data['StockInfo']['Entry']['Trade Status'] = "Trading is ongoing...."
180
-
181
- if trading and target2 and not target3:
182
- 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']):
183
- stop_loss = df.at[i + 1, 'Low']
184
- data['StockInfo']['Stock']['Values']['SL'] = stop_loss
185
- if df.at[i + 2, 'Low'] < stop_loss:
186
- target3 = True
187
- tgt3 = stop_loss * (share_qty / 3)
188
- shares_held -= (share_qty / 3)
189
- total_profit += round(tgt3,2)
190
- 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}
191
- data['StockInfo']['Stock']['Values']['Target3'] = tgt3
192
- data['StockInfo']['TGT3'] = target3_info
193
- data['StockInfo']['Stock']['Levels'] = data['StockInfo']['Stock']['Levels'] +" TGT3"
194
- data['StockInfo']['Stock']['Values']['Total P/L'] = await calculate_profit(ltp, totalshares, buy_price)
195
- data['StockInfo']['TotalProfit'] = {}
196
- data['StockInfo']['TotalProfit']['Profit'] = total_profit
197
- data['StockInfo']['Entry']['Trade Status'] = "Trade closed successfully...."
198
- data['StockInfo']['TotalProfit']['Trade Status'] = "Trade closed successfully...."
199
- break
200
-
201
- if (df.at[i + 1, 'Low'] < stop_loss and trading and entdate != df.at[i + 1, 'Date']) or stop_loss > ltp:
202
- profit_loss = (shares_held * stop_loss) - (shares_held * buy_price)
203
- total_profit += profit_loss
204
- profits.append(total_profit)
205
- shares_held = 0
206
- if data['StockInfo']['Stock']['Values']['Target3'] == "will announced" :
207
- data['StockInfo']['Stock']['Values']['Target3'] = "-"
208
- data['StockInfo']['Stock']['Status'] = "Closed"
209
- data['StockInfo']['Stock']['Levels'] = data['StockInfo']['Stock']['Levels'] +" SL"
210
- 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"}
211
- data['StockInfo']['SL'] = stoploss_info
212
- data['StockInfo']['TotalProfit'] = {}
213
- data['StockInfo']['TotalProfit']['Profit'] = round(total_profit, 2)
214
- data['StockInfo']['Stock']['Values']['Total P/L'] = round(total_profit, 2)
215
- data['StockInfo']['Entry']['Trade Status'] = "Trade closed successfully...."
216
- data['StockInfo']['TotalProfit']['Trade Status'] = "Trade closed successfully...."
217
- buy_price = 0
218
- entry = False
219
- trading = False
220
- target1 = target2 = target3 = False
221
- tgt1 = tgt2 = tgt3 = 0
222
- total_profit = 0
223
- break
224
-
225
- except IndexError:
226
- continue
227
-
228
- if capital_list and profits:
229
-
230
- return data
231
-
232
- else:
233
- if data:
234
-
235
- return data
236
-
237
- else:
238
- data['StockInfo'] = {}
239
- data['StockInfo']['Stock'] = {}
240
- data['StockInfo']['Stock']['Name'] = ticker
241
- data['StockInfo']['Stock']['Industry'] = Industry
242
- data['StockInfo']['Stock']['Logo'] = logo
243
- data['StockInfo']['Stock']['Status'] = "Waiting for entry"
244
- entryStock_info = df.iloc[1: 2].reset_index(drop=True).to_dict(orient='records')[0] # Entry info
245
- entryStock_info['Date'] = str(pd.to_datetime(df.at[1, 'Date']).strftime('%d-%m-%Y'))
246
- data['StockInfo']['Stock']['Values'] = entryStock_info
247
- data['StockInfo']['Stock']['Values']['Target3'] = "-"
248
- data['StockInfo']['Info'] = "Don't buy stock right now...."
249
-
250
- return data
251
-
252
 
253
  app = FastAPI()
254
 
@@ -262,10 +17,6 @@ app.add_middleware(
262
  allow_headers=["*"],
263
  )
264
 
265
- # @app.get('/')
266
- # def index():
267
- # return {"message": "welcome to Investify"}
268
-
269
  templates = Jinja2Templates(directory="templates")
270
 
271
  @app.get("/", response_class=HTMLResponse)
 
2
  from fastapi.templating import Jinja2Templates
3
  from fastapi import FastAPI, Request, HTTPException
4
  from fastapi.middleware.cors import CORSMiddleware
5
+ from pycatchs import eqt
6
  import warnings
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
  app = FastAPI()
9
 
 
17
  allow_headers=["*"],
18
  )
19
 
 
 
 
 
20
  templates = Jinja2Templates(directory="templates")
21
 
22
  @app.get("/", response_class=HTMLResponse)