Update app.py
Browse files
app.py
CHANGED
|
@@ -10,25 +10,20 @@ from plotly.subplots import make_subplots
|
|
| 10 |
import requests
|
| 11 |
from bs4 import BeautifulSoup
|
| 12 |
from textblob import TextBlob
|
| 13 |
-
import
|
|
|
|
| 14 |
|
| 15 |
-
|
| 16 |
-
STOCK_SYMBOL_REGEX = r"^[A-Z]{1,5}(\.[A-Z]{2,4})?$"
|
| 17 |
|
| 18 |
-
class
|
| 19 |
def __init__(self):
|
| 20 |
self.data = None
|
| 21 |
self.models = {}
|
| 22 |
self.scaler = None
|
| 23 |
|
| 24 |
def fetch_stock_data(self, stock_symbol, period='1y'):
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
# Handle missing data using forward fill
|
| 28 |
-
self.data.fillna(method='ffill', inplace=True)
|
| 29 |
-
self.add_features()
|
| 30 |
-
except Exception as e:
|
| 31 |
-
raise ValueError(f"Error fetching stock data: {e}")
|
| 32 |
|
| 33 |
def add_features(self):
|
| 34 |
self.data['Returns'] = self.data['Close'].pct_change()
|
|
@@ -36,22 +31,19 @@ class AdvancedTradingAnalyzer:
|
|
| 36 |
self.data['SMA_200'] = ta.trend.sma_indicator(self.data['Close'], window=200)
|
| 37 |
self.data['RSI'] = ta.momentum.rsi(self.data['Close'], window=14)
|
| 38 |
self.data['MACD'] = ta.trend.macd_diff(self.data['Close'])
|
| 39 |
-
self.data['ATR'] = ta.volatility.average_true_range(self.data['High'], self.data['Low'], self.data['Close'])
|
| 40 |
-
self.data['Bollinger_High'], self.data['Bollinger_Mid'], self.data['Bollinger_Low'] = ta.volatility.bollinger_hband(self.data['Close']), ta.volatility.bollinger_mavg(self.data['Close']), ta.volatility.bollinger_lband(self.data['Close'])
|
| 41 |
-
self.data['Stochastic_K'] = ta.momentum.stoch(self.data['High'], self.data['Low'], self.data['Close'])
|
| 42 |
-
self.data['Stochastic_D'] = ta.momentum.stoch_signal(self.data['High'], self.data['Low'], self.data['Close'])
|
| 43 |
-
self.data['OBV'] = ta.volume.on_balance_volume(self.data['Close'], self.data['Volume'])
|
| 44 |
-
self.data['ADX'] = ta.trend.adx(self.data['High'], self.data['Low'], self.data['Close'])
|
| 45 |
self.data.dropna(inplace=True)
|
| 46 |
|
| 47 |
def prepare_data(self, days):
|
| 48 |
-
features = ['Open', 'High', 'Low', 'Volume', 'Returns', 'SMA_50', 'SMA_200', 'RSI', 'MACD'
|
| 49 |
X = self.data[features]
|
| 50 |
y = self.data['Close'].shift(-days)
|
|
|
|
| 51 |
X = X[:-days]
|
| 52 |
y = y[:-days]
|
|
|
|
| 53 |
self.scaler = StandardScaler()
|
| 54 |
X_scaled = self.scaler.fit_transform(X)
|
|
|
|
| 55 |
return X_scaled, y
|
| 56 |
|
| 57 |
def train_models(self):
|
|
@@ -66,9 +58,7 @@ class AdvancedTradingAnalyzer:
|
|
| 66 |
input_data = np.array([[
|
| 67 |
last_data['Open'], last_data['High'], last_data['Low'], last_data['Volume'],
|
| 68 |
last_data['Returns'], last_data['SMA_50'], last_data['SMA_200'],
|
| 69 |
-
last_data['RSI'], last_data['MACD']
|
| 70 |
-
last_data['Stochastic_K'], last_data['Stochastic_D'],
|
| 71 |
-
last_data['OBV'], last_data['ADX']
|
| 72 |
]])
|
| 73 |
input_scaled = self.scaler.transform(input_data)
|
| 74 |
return self.models[days].predict(input_scaled)[0]
|
|
@@ -78,46 +68,19 @@ class AdvancedTradingAnalyzer:
|
|
| 78 |
response = requests.get(url)
|
| 79 |
soup = BeautifulSoup(response.text, 'html.parser')
|
| 80 |
news_items = soup.find_all('div', {'class': 'Py(14px) Pos(r)'})
|
|
|
|
| 81 |
sentiments = []
|
| 82 |
for item in news_items[:5]:
|
| 83 |
title = item.find('h3').text
|
| 84 |
blob = TextBlob(title)
|
| 85 |
sentiments.append(blob.sentiment.polarity)
|
|
|
|
| 86 |
return np.mean(sentiments)
|
| 87 |
|
| 88 |
-
def
|
| 89 |
-
|
| 90 |
-
return np.sqrt(252) * log_returns.std()
|
| 91 |
-
|
| 92 |
-
def calculate_sharpe_ratio(self, risk_free_rate=0.02):
|
| 93 |
-
returns = self.data['Returns'].dropna()
|
| 94 |
-
excess_returns = returns - risk_free_rate/252
|
| 95 |
-
return np.sqrt(252) * excess_returns.mean() / excess_returns.std()
|
| 96 |
-
|
| 97 |
-
def calculate_var(self, confidence_level=0.95):
|
| 98 |
-
returns = self.data['Returns'].dropna()
|
| 99 |
-
return np.percentile(returns, 100 * (1 - confidence_level))
|
| 100 |
-
|
| 101 |
-
def perform_monte_carlo_simulation(self, num_simulations=1000, days=30):
|
| 102 |
-
last_price = self.data['Close'].iloc[-1]
|
| 103 |
-
simulation_df = pd.DataFrame()
|
| 104 |
-
for x in range(num_simulations):
|
| 105 |
-
count = 0
|
| 106 |
-
price_series = []
|
| 107 |
-
price = last_price
|
| 108 |
-
for y in range(days):
|
| 109 |
-
if count == 251:
|
| 110 |
-
break
|
| 111 |
-
price = price * (1 + np.random.normal(0, self.data['Returns'].std()))
|
| 112 |
-
price_series.append(price)
|
| 113 |
-
count += 1
|
| 114 |
-
simulation_df[x] = price_series
|
| 115 |
-
return simulation_df
|
| 116 |
-
|
| 117 |
-
def plot_analysis(self, predictions, monte_carlo_df):
|
| 118 |
-
fig = make_subplots(rows=3, cols=1, shared_xaxes=True,
|
| 119 |
vertical_spacing=0.03,
|
| 120 |
-
subplot_titles=('Price and Moving Averages', 'RSI'
|
| 121 |
|
| 122 |
fig.add_trace(go.Candlestick(x=self.data.index,
|
| 123 |
open=self.data['Open'],
|
|
@@ -130,10 +93,6 @@ class AdvancedTradingAnalyzer:
|
|
| 130 |
row=1, col=1)
|
| 131 |
fig.add_trace(go.Scatter(x=self.data.index, y=self.data['SMA_200'], name='200-day SMA'),
|
| 132 |
row=1, col=1)
|
| 133 |
-
fig.add_trace(go.Scatter(x=self.data.index, y=self.data['Bollinger_High'], name='Bollinger High', line=dict(color='rgba(250,0,0,0.3)')),
|
| 134 |
-
row=1, col=1)
|
| 135 |
-
fig.add_trace(go.Scatter(x=self.data.index, y=self.data['Bollinger_Low'], name='Bollinger Low', line=dict(color='rgba(0,250,0,0.3)')),
|
| 136 |
-
row=1, col=1)
|
| 137 |
|
| 138 |
last_date = self.data.index[-1]
|
| 139 |
for days, prediction in predictions.items():
|
|
@@ -148,151 +107,22 @@ class AdvancedTradingAnalyzer:
|
|
| 148 |
fig.add_hline(y=70, line_dash="dash", line_color="red", row=2, col=1)
|
| 149 |
fig.add_hline(y=30, line_dash="dash", line_color="green", row=2, col=1)
|
| 150 |
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
y=monte_carlo_df.iloc[:, i],
|
| 154 |
-
mode='lines',
|
| 155 |
-
line=dict(width=0.5),
|
| 156 |
-
showlegend=False),
|
| 157 |
-
row=3, col=1)
|
| 158 |
-
|
| 159 |
-
fig.update_layout(height=1200, title_text="Advanced Stock Analysis")
|
| 160 |
-
fig.update_xaxes(title_text="Date", row=3, col=1)
|
| 161 |
fig.update_yaxes(title_text="Price", row=1, col=1)
|
| 162 |
fig.update_yaxes(title_text="RSI", row=2, col=1)
|
| 163 |
-
fig.update_yaxes(title_text="Simulated Price", row=3, col=1)
|
| 164 |
|
| 165 |
return fig
|
| 166 |
|
| 167 |
-
analyzer =
|
| 168 |
-
|
| 169 |
-
def analyze_options(stock_symbol):
|
| 170 |
-
stock = yf.Ticker(stock_symbol)
|
| 171 |
-
options = stock.options
|
| 172 |
-
|
| 173 |
-
if not options:
|
| 174 |
-
return "No options data available for this stock."
|
| 175 |
-
|
| 176 |
-
nearest_expiry = options[0]
|
| 177 |
-
calls = stock.option_chain(nearest_expiry).calls
|
| 178 |
-
puts = stock.option_chain(nearest_expiry).puts
|
| 179 |
-
|
| 180 |
-
current_price = stock.history(period="1d")['Close'].iloc[-1]
|
| 181 |
-
|
| 182 |
-
atm_call = calls[calls['strike'] >= current_price].iloc[0]
|
| 183 |
-
atm_put = puts[puts['strike'] <= current_price].iloc[-1]
|
| 184 |
-
|
| 185 |
-
result = f"Options Analysis (Expiry: {nearest_expiry}):\n"
|
| 186 |
-
result += f"Current Stock Price: ₹{current_price:.2f}\n\n"
|
| 187 |
-
result += f"At-the-money Call:\n"
|
| 188 |
-
result += f" Strike: ₹{atm_call['strike']:.2f}\n"
|
| 189 |
-
result += f" Last Price: ₹{atm_call['lastPrice']:.2f}\n"
|
| 190 |
-
result += f" Implied Volatility: {atm_call['impliedVolatility']*100:.2f}%\n\n"
|
| 191 |
-
result += f"At-the-money Put:\n"
|
| 192 |
-
result += f" Strike: ₹{atm_put['strike']:.2f}\n"
|
| 193 |
-
result += f" Last Price: ₹{atm_put['lastPrice']:.2f}\n"
|
| 194 |
-
result += f" Implied Volatility: {atm_put['impliedVolatility']*100:.2f}%\n\n"
|
| 195 |
-
|
| 196 |
-
put_call_ratio = puts['volume'].sum() / calls['volume'].sum()
|
| 197 |
-
result += f"Put/Call Ratio: {put_call_ratio:.2f}\n"
|
| 198 |
-
|
| 199 |
-
if put_call_ratio > 1:
|
| 200 |
-
result += "High put/call ratio suggests bearish sentiment.\n"
|
| 201 |
-
elif put_call_ratio < 0.7:
|
| 202 |
-
result += "Low put/call ratio suggests bullish sentiment.\n"
|
| 203 |
-
else:
|
| 204 |
-
result += "Put/call ratio suggests neutral market sentiment.\n"
|
| 205 |
-
|
| 206 |
-
return result
|
| 207 |
-
|
| 208 |
-
def sector_comparison(stock_symbol):
|
| 209 |
-
stock = yf.Ticker(stock_symbol)
|
| 210 |
-
sector = stock.info.get('sector', 'N/A')
|
| 211 |
-
industry = stock.info.get('industry', 'N/A')
|
| 212 |
-
|
| 213 |
-
industry_stocks = yf.Ticker(industry).info.get('components', [])[:5]
|
| 214 |
-
|
| 215 |
-
if not industry_stocks:
|
| 216 |
-
return "Unable to fetch sector comparison data."
|
| 217 |
-
|
| 218 |
-
comparison_data = []
|
| 219 |
-
for symbol in industry_stocks:
|
| 220 |
-
comp_stock = yf.Ticker(symbol)
|
| 221 |
-
info = comp_stock.info
|
| 222 |
-
comparison_data.append({
|
| 223 |
-
'Symbol': symbol,
|
| 224 |
-
'Company': info.get('longName', 'N/A'),
|
| 225 |
-
'Price': info.get('currentPrice', 'N/A'),
|
| 226 |
-
'P/E Ratio': info.get('trailingPE', 'N/A'),
|
| 227 |
-
'Market Cap (B)': info.get('marketCap', 'N/A') / 1e9,
|
| 228 |
-
'52W High': info.get('fiftyTwoWeekHigh', 'N/A'),
|
| 229 |
-
'52W Low': info.get('fiftyTwoWeekLow', 'N/A'),
|
| 230 |
-
})
|
| 231 |
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
result = f"Sector: {sector}\nIndustry: {industry}\n\n"
|
| 236 |
-
result += df.to_string()
|
| 237 |
-
return result
|
| 238 |
-
|
| 239 |
-
def technical_analysis(data):
|
| 240 |
-
last_close = data['Close'].iloc[-1]
|
| 241 |
-
sma_50 = data['SMA_50'].iloc[-1]
|
| 242 |
-
sma_200 = data['SMA_200'].iloc[-1]
|
| 243 |
-
rsi = data['RSI'].iloc[-1]
|
| 244 |
-
macd = data['MACD'].iloc[-1]
|
| 245 |
-
stoch_k = data['Stochastic_K'].iloc[-1]
|
| 246 |
-
stoch_d = data['Stochastic_D'].iloc[-1]
|
| 247 |
-
adx = data['ADX'].iloc[-1]
|
| 248 |
-
|
| 249 |
-
analysis = "Technical Analysis:\n"
|
| 250 |
-
|
| 251 |
-
if last_close > sma_50 > sma_200:
|
| 252 |
-
analysis += "- Strong uptrend: Price above both 50 and 200 SMAs\n"
|
| 253 |
-
elif sma_50 > sma_200:
|
| 254 |
-
analysis += "- Potential uptrend: 50 SMA above 200 SMA (Golden Cross)\n"
|
| 255 |
-
elif sma_200 > sma_50:
|
| 256 |
-
analysis += "- Potential downtrend: 200 SMA above 50 SMA (Death Cross)\n"
|
| 257 |
-
|
| 258 |
-
if rsi > 70:
|
| 259 |
-
analysis += "- RSI indicates overbought conditions\n"
|
| 260 |
-
elif rsi < 30:
|
| 261 |
-
analysis += "- RSI indicates oversold conditions\n"
|
| 262 |
-
|
| 263 |
-
if macd > 0:
|
| 264 |
-
analysis += "- MACD is positive, indicating bullish momentum\n"
|
| 265 |
-
else:
|
| 266 |
-
analysis += "- MACD is negative, indicating bearish momentum\n"
|
| 267 |
-
|
| 268 |
-
if stoch_k > 80 and stoch_d > 80:
|
| 269 |
-
analysis += "- Stochastic Oscillator indicates overbought conditions\n"
|
| 270 |
-
elif stoch_k < 20 and stoch_d < 20:
|
| 271 |
-
analysis += "- Stochastic Oscillator indicates oversold conditions\n"
|
| 272 |
-
|
| 273 |
-
if adx > 25:
|
| 274 |
-
analysis += f"- ADX ({adx:.2f}) indicates a strong trend\n"
|
| 275 |
-
else:
|
| 276 |
-
analysis += f"- ADX ({adx:.2f}) indicates a weak trend\n"
|
| 277 |
-
|
| 278 |
-
return analysis
|
| 279 |
-
|
| 280 |
-
def analyze_stock(stock_symbol, period='1y'):
|
| 281 |
-
# Input Validation
|
| 282 |
-
if not re.match(STOCK_SYMBOL_REGEX, stock_symbol):
|
| 283 |
-
raise ValueError("Invalid stock symbol format.")
|
| 284 |
-
|
| 285 |
-
analyzer.fetch_stock_data(stock_symbol, period)
|
| 286 |
analyzer.train_models()
|
| 287 |
predictions = {days: analyzer.predict(days) for days in [3, 5, 15]}
|
| 288 |
sentiment = analyzer.get_sentiment(stock_symbol)
|
| 289 |
|
| 290 |
current_price = analyzer.data['Close'].iloc[-1]
|
| 291 |
-
volatility = analyzer.calculate_volatility()
|
| 292 |
-
sharpe_ratio = analyzer.calculate_sharpe_ratio()
|
| 293 |
-
var = analyzer.calculate_var()
|
| 294 |
-
|
| 295 |
-
monte_carlo_df = analyzer.perform_monte_carlo_simulation()
|
| 296 |
|
| 297 |
results = {}
|
| 298 |
for days, prediction in predictions.items():
|
|
@@ -304,100 +134,71 @@ def analyze_stock(stock_symbol, period='1y'):
|
|
| 304 |
'percent_change': percent_change
|
| 305 |
}
|
| 306 |
|
| 307 |
-
plot = analyzer.plot_analysis(predictions
|
| 308 |
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
result += "
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
result += "Mixed Signals: Consider additional research and caution.\n"
|
| 339 |
-
|
| 340 |
-
if sharpe_ratio > 1:
|
| 341 |
-
result += "Favorable risk-adjusted returns based on historical data.\n"
|
| 342 |
-
elif sharpe_ratio < 0:
|
| 343 |
-
result += "Poor risk-adjusted returns based on historical data.\n"
|
| 344 |
-
else:
|
| 345 |
-
result += "Moderate risk-adjusted returns based on historical data.\n"
|
| 346 |
-
|
| 347 |
-
result += "\n" + tech_analysis
|
| 348 |
-
result += "\n" + options_analysis
|
| 349 |
-
result += "\nSector Comparison:\n" + sector_comp
|
| 350 |
-
|
| 351 |
-
return result
|
| 352 |
|
| 353 |
-
def update_ui(stock_symbol, period='1y'):
|
| 354 |
-
try:
|
| 355 |
-
results, sentiment, current_price, rsi, macd, volatility, sharpe_ratio, var, plot, options_analysis, sector_comp, tech_analysis = analyze_stock(stock_symbol, period)
|
| 356 |
-
return (
|
| 357 |
-
get_prediction_text(results, sentiment, current_price, rsi, macd, volatility, sharpe_ratio, var, options_analysis, sector_comp, tech_analysis, 3),
|
| 358 |
-
get_prediction_text(results, sentiment, current_price, rsi, macd, volatility, sharpe_ratio, var, options_analysis, sector_comp, tech_analysis, 5),
|
| 359 |
-
get_prediction_text(results, sentiment, current_price, rsi, macd, volatility, sharpe_ratio, var, options_analysis, sector_comp, tech_analysis, 15),
|
| 360 |
-
plot
|
| 361 |
-
)
|
| 362 |
-
except ValueError as ve:
|
| 363 |
-
return (
|
| 364 |
-
str(ve), # Display the specific error message
|
| 365 |
-
"",
|
| 366 |
-
"",
|
| 367 |
-
None # Return None for the plot if an error occurs
|
| 368 |
-
)
|
| 369 |
-
except Exception as e:
|
| 370 |
-
return (
|
| 371 |
-
f"An unexpected error occurred: {e}",
|
| 372 |
-
"",
|
| 373 |
-
"",
|
| 374 |
-
None # Return None for the plot if an error occurs
|
| 375 |
-
)
|
| 376 |
-
|
| 377 |
-
# Gradio interface
|
| 378 |
with gr.Blocks(css="#warnings {color: red}") as iface:
|
| 379 |
-
gr.Markdown("# Advanced
|
| 380 |
-
gr.Markdown("Enter
|
| 381 |
gr.Markdown("This tool is for educational purposes only and should not be considered as financial advice.", elem_id="warnings")
|
| 382 |
|
| 383 |
stock_input = gr.Textbox(label="Stock Symbol")
|
| 384 |
-
period_input = gr.Dropdown(choices=['1mo', '3mo', '6mo', '1y', '2y', '5y', '10y', 'ytd', 'max'], label="Period", value='1y')
|
| 385 |
analyze_button = gr.Button("Analyze Stock")
|
| 386 |
|
| 387 |
with gr.Tabs():
|
| 388 |
with gr.TabItem("3-Day Prediction"):
|
| 389 |
-
pred_3_day =
|
| 390 |
with gr.TabItem("5-Day Prediction"):
|
| 391 |
-
pred_5_day =
|
| 392 |
with gr.TabItem("15-Day Prediction"):
|
| 393 |
-
pred_15_day =
|
| 394 |
|
| 395 |
-
chart_output = gr.Plot(label="
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 396 |
|
| 397 |
analyze_button.click(
|
| 398 |
update_ui,
|
| 399 |
-
inputs=[stock_input
|
| 400 |
-
outputs=[
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 401 |
)
|
| 402 |
|
| 403 |
if __name__ == "__main__":
|
|
|
|
| 10 |
import requests
|
| 11 |
from bs4 import BeautifulSoup
|
| 12 |
from textblob import TextBlob
|
| 13 |
+
import os
|
| 14 |
+
from dotenv import load_dotenv
|
| 15 |
|
| 16 |
+
load_dotenv()
|
|
|
|
| 17 |
|
| 18 |
+
class SimpleMarketAnalyzer:
|
| 19 |
def __init__(self):
|
| 20 |
self.data = None
|
| 21 |
self.models = {}
|
| 22 |
self.scaler = None
|
| 23 |
|
| 24 |
def fetch_stock_data(self, stock_symbol, period='1y'):
|
| 25 |
+
self.data = yf.download(stock_symbol, period=period)
|
| 26 |
+
self.add_features()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
def add_features(self):
|
| 29 |
self.data['Returns'] = self.data['Close'].pct_change()
|
|
|
|
| 31 |
self.data['SMA_200'] = ta.trend.sma_indicator(self.data['Close'], window=200)
|
| 32 |
self.data['RSI'] = ta.momentum.rsi(self.data['Close'], window=14)
|
| 33 |
self.data['MACD'] = ta.trend.macd_diff(self.data['Close'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
self.data.dropna(inplace=True)
|
| 35 |
|
| 36 |
def prepare_data(self, days):
|
| 37 |
+
features = ['Open', 'High', 'Low', 'Volume', 'Returns', 'SMA_50', 'SMA_200', 'RSI', 'MACD']
|
| 38 |
X = self.data[features]
|
| 39 |
y = self.data['Close'].shift(-days)
|
| 40 |
+
|
| 41 |
X = X[:-days]
|
| 42 |
y = y[:-days]
|
| 43 |
+
|
| 44 |
self.scaler = StandardScaler()
|
| 45 |
X_scaled = self.scaler.fit_transform(X)
|
| 46 |
+
|
| 47 |
return X_scaled, y
|
| 48 |
|
| 49 |
def train_models(self):
|
|
|
|
| 58 |
input_data = np.array([[
|
| 59 |
last_data['Open'], last_data['High'], last_data['Low'], last_data['Volume'],
|
| 60 |
last_data['Returns'], last_data['SMA_50'], last_data['SMA_200'],
|
| 61 |
+
last_data['RSI'], last_data['MACD']
|
|
|
|
|
|
|
| 62 |
]])
|
| 63 |
input_scaled = self.scaler.transform(input_data)
|
| 64 |
return self.models[days].predict(input_scaled)[0]
|
|
|
|
| 68 |
response = requests.get(url)
|
| 69 |
soup = BeautifulSoup(response.text, 'html.parser')
|
| 70 |
news_items = soup.find_all('div', {'class': 'Py(14px) Pos(r)'})
|
| 71 |
+
|
| 72 |
sentiments = []
|
| 73 |
for item in news_items[:5]:
|
| 74 |
title = item.find('h3').text
|
| 75 |
blob = TextBlob(title)
|
| 76 |
sentiments.append(blob.sentiment.polarity)
|
| 77 |
+
|
| 78 |
return np.mean(sentiments)
|
| 79 |
|
| 80 |
+
def plot_analysis(self, predictions):
|
| 81 |
+
fig = make_subplots(rows=2, cols=1, shared_xaxes=True,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
vertical_spacing=0.03,
|
| 83 |
+
subplot_titles=('Price and Moving Averages', 'RSI'))
|
| 84 |
|
| 85 |
fig.add_trace(go.Candlestick(x=self.data.index,
|
| 86 |
open=self.data['Open'],
|
|
|
|
| 93 |
row=1, col=1)
|
| 94 |
fig.add_trace(go.Scatter(x=self.data.index, y=self.data['SMA_200'], name='200-day SMA'),
|
| 95 |
row=1, col=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
last_date = self.data.index[-1]
|
| 98 |
for days, prediction in predictions.items():
|
|
|
|
| 107 |
fig.add_hline(y=70, line_dash="dash", line_color="red", row=2, col=1)
|
| 108 |
fig.add_hline(y=30, line_dash="dash", line_color="green", row=2, col=1)
|
| 109 |
|
| 110 |
+
fig.update_layout(height=800, title_text="Stock Analysis")
|
| 111 |
+
fig.update_xaxes(title_text="Date", row=2, col=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
fig.update_yaxes(title_text="Price", row=1, col=1)
|
| 113 |
fig.update_yaxes(title_text="RSI", row=2, col=1)
|
|
|
|
| 114 |
|
| 115 |
return fig
|
| 116 |
|
| 117 |
+
analyzer = SimpleMarketAnalyzer()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
+
def analyze_stock(stock_symbol):
|
| 120 |
+
analyzer.fetch_stock_data(stock_symbol)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
analyzer.train_models()
|
| 122 |
predictions = {days: analyzer.predict(days) for days in [3, 5, 15]}
|
| 123 |
sentiment = analyzer.get_sentiment(stock_symbol)
|
| 124 |
|
| 125 |
current_price = analyzer.data['Close'].iloc[-1]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
results = {}
|
| 128 |
for days, prediction in predictions.items():
|
|
|
|
| 134 |
'percent_change': percent_change
|
| 135 |
}
|
| 136 |
|
| 137 |
+
plot = analyzer.plot_analysis(predictions)
|
| 138 |
|
| 139 |
+
return results, sentiment, current_price, analyzer.data['RSI'].iloc[-1], analyzer.data['MACD'].iloc[-1], plot
|
| 140 |
+
|
| 141 |
+
def create_prediction_tab(days):
|
| 142 |
+
def get_prediction_text(results, sentiment, current_price, rsi, macd):
|
| 143 |
+
pred = results[days]
|
| 144 |
+
result = f"Current Price: ₹{current_price:.2f}\n"
|
| 145 |
+
result += f"Predicted Price ({days} days): ₹{pred['prediction']:.2f}\n"
|
| 146 |
+
result += f"Predicted Change: ₹{pred['change']:.2f} ({pred['percent_change']:.2f}%)\n\n"
|
| 147 |
+
result += f"Sentiment: {'Positive' if sentiment > 0 else 'Negative' if sentiment < 0 else 'Neutral'} ({sentiment:.2f})\n\n"
|
| 148 |
+
result += f"RSI: {rsi:.2f} "
|
| 149 |
+
if rsi > 70:
|
| 150 |
+
result += "(Potentially Overbought)\n"
|
| 151 |
+
elif rsi < 30:
|
| 152 |
+
result += "(Potentially Oversold)\n"
|
| 153 |
+
else:
|
| 154 |
+
result += "(Neutral)\n"
|
| 155 |
+
result += f"MACD: {'Positive' if macd > 0 else 'Negative'} Momentum\n\n"
|
| 156 |
+
result += "Analysis:\n"
|
| 157 |
+
if pred['percent_change'] > 0 and sentiment > 0 and rsi < 70:
|
| 158 |
+
result += f"Potentially Bullish: Positive {days}-day prediction, sentiment, and not overbought.\n"
|
| 159 |
+
elif pred['percent_change'] < 0 and sentiment < 0 and rsi > 30:
|
| 160 |
+
result += f"Potentially Bearish: Negative {days}-day prediction, sentiment, and not oversold.\n"
|
| 161 |
+
else:
|
| 162 |
+
result += "Mixed Signals: Consider additional research and caution.\n"
|
| 163 |
+
return result
|
| 164 |
+
|
| 165 |
+
return gr.Column([
|
| 166 |
+
gr.Textbox(label=f"{days}-Day Prediction", lines=10, interactive=False),
|
| 167 |
+
])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
with gr.Blocks(css="#warnings {color: red}") as iface:
|
| 170 |
+
gr.Markdown("# Advanced Indian Stock Market Analyzer")
|
| 171 |
+
gr.Markdown("Enter an Indian stock symbol to get a comprehensive market analysis. Use .NS suffix for NSE stocks (e.g., RELIANCE.NS, TATAMOTORS.NS).")
|
| 172 |
gr.Markdown("This tool is for educational purposes only and should not be considered as financial advice.", elem_id="warnings")
|
| 173 |
|
| 174 |
stock_input = gr.Textbox(label="Stock Symbol")
|
|
|
|
| 175 |
analyze_button = gr.Button("Analyze Stock")
|
| 176 |
|
| 177 |
with gr.Tabs():
|
| 178 |
with gr.TabItem("3-Day Prediction"):
|
| 179 |
+
pred_3_day = create_prediction_tab(3)
|
| 180 |
with gr.TabItem("5-Day Prediction"):
|
| 181 |
+
pred_5_day = create_prediction_tab(5)
|
| 182 |
with gr.TabItem("15-Day Prediction"):
|
| 183 |
+
pred_15_day = create_prediction_tab(15)
|
| 184 |
|
| 185 |
+
chart_output = gr.Plot(label="Stock Analysis Chart")
|
| 186 |
+
|
| 187 |
+
def update_ui(stock_symbol):
|
| 188 |
+
results, sentiment, current_price, rsi, macd, plot = analyze_stock(stock_symbol)
|
| 189 |
+
return (
|
| 190 |
+
get_prediction_text(results, sentiment, current_price, rsi, macd) for days in [3, 5, 15]
|
| 191 |
+
) + (plot,)
|
| 192 |
|
| 193 |
analyze_button.click(
|
| 194 |
update_ui,
|
| 195 |
+
inputs=[stock_input],
|
| 196 |
+
outputs=[
|
| 197 |
+
pred_3_day.children[0],
|
| 198 |
+
pred_5_day.children[0],
|
| 199 |
+
pred_15_day.children[0],
|
| 200 |
+
chart_output
|
| 201 |
+
]
|
| 202 |
)
|
| 203 |
|
| 204 |
if __name__ == "__main__":
|