jarvisx17 commited on
Commit
ec83a72
·
1 Parent(s): 06ac163

Update pycatchs/levels.py

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