jarvisx17 commited on
Commit
558c675
·
1 Parent(s): d093e30

Upload 3 files

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