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