jarvisx17 commited on
Commit
e4b8b8e
·
1 Parent(s): 87bc3c9

Update main.py

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