Update main.py
Browse files
main.py
CHANGED
@@ -1,297 +1,310 @@
|
|
1 |
-
from fastapi import FastAPI, Request
|
2 |
-
from fastapi.
|
3 |
-
import
|
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 |
-
|
254 |
-
|
255 |
-
app.
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
#
|
268 |
-
#
|
269 |
-
|
270 |
-
#
|
271 |
-
|
272 |
-
#
|
273 |
-
#
|
274 |
-
#
|
275 |
-
#
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
284 |
|
285 |
|
286 |
-
# @app.post('/data')
|
287 |
-
# async def post_data(request: Request):
|
288 |
-
# data = await request.json()
|
289 |
-
# ticker = data.get('ticker')
|
290 |
-
# date = data.get('date')
|
291 |
-
# share_qty = data.get('qty')
|
292 |
-
# response = data_manager.get_equity_data(ticker, date, share_qty)
|
293 |
-
# return response
|
294 |
|
295 |
-
# if __name__ == "__main__":
|
296 |
-
# import uvicorn
|
297 |
-
# uvicorn.run(app, host="0.0.0.0", port=8000)
|
|
|
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)
|