Spaces:
Sleeping
Sleeping
Anupam251272
commited on
Commit
•
9998dca
1
Parent(s):
1744431
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import yfinance as yf
|
2 |
+
import pandas as pd
|
3 |
+
import matplotlib.pyplot as plt
|
4 |
+
import seaborn as sns
|
5 |
+
from prophet import Prophet
|
6 |
+
import gradio as gr
|
7 |
+
from ta.trend import SMAIndicator, EMAIndicator, MACD
|
8 |
+
from ta.momentum import RSIIndicator
|
9 |
+
|
10 |
+
# Function for trading strategy signals
|
11 |
+
def trading_signals(df, strategy="day trading"):
|
12 |
+
signals = ""
|
13 |
+
df = df.copy()
|
14 |
+
|
15 |
+
try:
|
16 |
+
if strategy.lower() == "day trading":
|
17 |
+
# Use Bollinger Bands and RSI for intraday trades
|
18 |
+
df['RSI'] = RSIIndicator(df['Close'], window=14).rsi()
|
19 |
+
df['EMA_9'] = EMAIndicator(df['Close'], window=9).ema_indicator()
|
20 |
+
df['EMA_21'] = EMAIndicator(df['Close'], window=21).ema_indicator()
|
21 |
+
df['Signal'] = (df['EMA_9'] > df['EMA_21']).astype(int)
|
22 |
+
|
23 |
+
signals = f"Day Trading Signals: {'Buy' if df['Signal'].iloc[-1] else 'Sell'}"
|
24 |
+
|
25 |
+
elif strategy.lower() == "swing trading":
|
26 |
+
# Swing Trading: SMA crossover
|
27 |
+
df['SMA_50'] = SMAIndicator(df['Close'], window=50).sma_indicator()
|
28 |
+
df['SMA_200'] = SMAIndicator(df['Close'], window=200).sma_indicator()
|
29 |
+
df['Signal'] = (df['SMA_50'] > df['SMA_200']).astype(int)
|
30 |
+
|
31 |
+
signals = f"Swing Trading Signals: {'Bullish' if df['Signal'].iloc[-1] else 'Bearish'}"
|
32 |
+
|
33 |
+
elif strategy.lower() == "momentum trading":
|
34 |
+
# Momentum Trading: RSI + MACD
|
35 |
+
df['RSI'] = RSIIndicator(df['Close'], window=14).rsi()
|
36 |
+
macd = MACD(df['Close'])
|
37 |
+
df['MACD'] = macd.macd()
|
38 |
+
df['MACD_signal'] = macd.macd_signal()
|
39 |
+
|
40 |
+
# Simplified momentum condition
|
41 |
+
df['Momentum'] = ((df['RSI'] > 50) & (df['MACD'] > df['MACD_signal'])).astype(int)
|
42 |
+
|
43 |
+
signals = f"Momentum Trading Signal: {'Strong Momentum' if df['Momentum'].iloc[-1] else 'Weak Momentum'}"
|
44 |
+
|
45 |
+
elif strategy.lower() == "scalping":
|
46 |
+
# Scalping: EMA crossover on 1-min data
|
47 |
+
df['EMA_3'] = EMAIndicator(df['Close'], window=3).ema_indicator()
|
48 |
+
df['EMA_9'] = EMAIndicator(df['Close'], window=9).ema_indicator()
|
49 |
+
df['Signal'] = (df['EMA_3'] > df['EMA_9']).astype(int)
|
50 |
+
|
51 |
+
signals = f"Scalping Signal: {'Buy' if df['Signal'].iloc[-1] else 'Sell'}"
|
52 |
+
|
53 |
+
else:
|
54 |
+
signals = "Invalid Strategy"
|
55 |
+
|
56 |
+
except Exception as e:
|
57 |
+
signals = f"Error in trading signals: {e}"
|
58 |
+
|
59 |
+
return signals
|
60 |
+
|
61 |
+
# Main function to fetch data, generate trends, and trading signals
|
62 |
+
def stock_analysis_with_trading(ticker, period="6mo", interval="1d", analysis_type="closing price trend", strategy=None):
|
63 |
+
try:
|
64 |
+
# Fetch historical stock data with enhanced error handling
|
65 |
+
stock = yf.Ticker(ticker)
|
66 |
+
|
67 |
+
# Try different methods to fetch data
|
68 |
+
try:
|
69 |
+
df = stock.history(period=period, interval=interval)
|
70 |
+
except Exception as initial_error:
|
71 |
+
# Fallback to different periods or intervals
|
72 |
+
try:
|
73 |
+
df = stock.history(period="1y", interval="1d")
|
74 |
+
except Exception as fallback_error:
|
75 |
+
return f"Error fetching data: {initial_error} | Fallback Error: {fallback_error}", None
|
76 |
+
|
77 |
+
if df is None or df.empty:
|
78 |
+
return f"No data found for ticker: {ticker}. Check ticker symbol and network connection.", None
|
79 |
+
|
80 |
+
if analysis_type.lower() == "closing price trend":
|
81 |
+
# Plot Closing Price Trend
|
82 |
+
plt.figure(figsize=(10, 6))
|
83 |
+
plt.plot(df.index, df['Close'], label='Closing Price')
|
84 |
+
plt.title(f"Closing Price Trend for {ticker}")
|
85 |
+
plt.xlabel("Date")
|
86 |
+
plt.ylabel("Closing Price (USD)")
|
87 |
+
plt.grid()
|
88 |
+
plt.legend()
|
89 |
+
plot_path = f"{ticker}_closing_price_trend.png"
|
90 |
+
plt.savefig(plot_path)
|
91 |
+
plt.close()
|
92 |
+
return f"Closing Price Analysis for {ticker}", plot_path
|
93 |
+
|
94 |
+
elif analysis_type.lower() == "forecast":
|
95 |
+
# Forecast with Prophet
|
96 |
+
forecast_df = df.reset_index()[['Date', 'Close']]
|
97 |
+
forecast_df.columns = ['ds', 'y']
|
98 |
+
model = Prophet()
|
99 |
+
model.fit(forecast_df)
|
100 |
+
future = model.make_future_dataframe(periods=30)
|
101 |
+
forecast = model.predict(future)
|
102 |
+
|
103 |
+
plt.figure(figsize=(10, 6))
|
104 |
+
model.plot(forecast)
|
105 |
+
plt.title(f"Forecasted Closing Price for {ticker}")
|
106 |
+
plt.xlabel("Date")
|
107 |
+
plt.ylabel("Price (USD)")
|
108 |
+
plot_path = f"{ticker}_forecast_trend.png"
|
109 |
+
plt.savefig(plot_path)
|
110 |
+
plt.close()
|
111 |
+
return "Forecast Generated Successfully", plot_path
|
112 |
+
|
113 |
+
elif strategy:
|
114 |
+
signals = trading_signals(df, strategy)
|
115 |
+
return signals, None
|
116 |
+
|
117 |
+
else:
|
118 |
+
return "Invalid analysis type or strategy provided.", None
|
119 |
+
|
120 |
+
except Exception as e:
|
121 |
+
return f"Comprehensive Error: {e}", None
|
122 |
+
|
123 |
+
# Gradio Interface
|
124 |
+
def chat_with_agent(ticker, period, interval, query, strategy):
|
125 |
+
response, plot_path = stock_analysis_with_trading(ticker, period, interval, query, strategy)
|
126 |
+
return response, plot_path if plot_path else None
|
127 |
+
|
128 |
+
# Define Gradio Interface
|
129 |
+
iface = gr.Interface(
|
130 |
+
fn=chat_with_agent,
|
131 |
+
inputs=[
|
132 |
+
gr.Textbox(label="Stock Ticker (e.g., AAPL, MSFT)"),
|
133 |
+
gr.Textbox(label="Time Period (e.g., 6mo, 1d)", value="6mo"),
|
134 |
+
gr.Textbox(label="Data Interval (e.g., 1d, 1h)", value="1d"),
|
135 |
+
gr.Textbox(label="Query (e.g., closing price trend, forecast)", value="closing price trend"),
|
136 |
+
gr.Textbox(label="Trading Strategy (optional)", value=""),
|
137 |
+
],
|
138 |
+
outputs=[
|
139 |
+
gr.Textbox(label="Analysis Result or Trading Signal"),
|
140 |
+
gr.Image(label="Trend or Forecast Visualization")
|
141 |
+
],
|
142 |
+
title="Stock Analysis & Trading Strategy Agent",
|
143 |
+
description="Analyze stock trends, forecast prices, and generate trading signals using technical indicators."
|
144 |
+
)
|
145 |
+
|
146 |
+
# Launch the interface
|
147 |
+
iface.launch(share=True)
|