Anupam251272 commited on
Commit
8a4020d
·
verified ·
1 Parent(s): e5c9ef1

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +220 -0
app.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import yfinance as yf
3
+ import pandas as pd
4
+ import numpy as np
5
+ from datetime import datetime, timedelta
6
+ import plotly.graph_objects as go
7
+ from transformers import pipeline
8
+ import torch
9
+ from textblob import TextBlob
10
+ import nltk
11
+ from ta.trend import SMAIndicator, MACD
12
+ from ta.momentum import RSIIndicator
13
+
14
+ # Download NLTK data
15
+ try:
16
+ nltk.download('punkt', quiet=True)
17
+ nltk.download('averaged_perceptron_tagger', quiet=True)
18
+ except Exception as e:
19
+ print(f"NLTK download warning (not critical): {e}")
20
+
21
+ class StockAnalysisApp:
22
+ def __init__(self):
23
+ try:
24
+ self.sentiment_analyzer = pipeline("sentiment-analysis",
25
+ device=0 if torch.cuda.is_available() else -1)
26
+ except:
27
+ self.sentiment_analyzer = pipeline("sentiment-analysis", device=-1)
28
+
29
+ def get_stock_data(self, ticker, period='1y'):
30
+ """Fetch stock data"""
31
+ try:
32
+ stock = yf.Ticker(ticker)
33
+ data = stock.history(period=period)
34
+ return data, stock.info
35
+ except Exception as e:
36
+ return None, None
37
+
38
+ def create_chart(self, data, ticker):
39
+ """Create interactive stock chart"""
40
+ try:
41
+ fig = go.Figure()
42
+
43
+ # Candlestick chart
44
+ fig.add_trace(go.Candlestick(
45
+ x=data.index,
46
+ open=data['Open'],
47
+ high=data['High'],
48
+ low=data['Low'],
49
+ close=data['Close'],
50
+ name=ticker
51
+ ))
52
+
53
+ # Add SMAs
54
+ sma20 = SMAIndicator(close=data['Close'], window=20).sma_indicator()
55
+ sma50 = SMAIndicator(close=data['Close'], window=50).sma_indicator()
56
+
57
+ fig.add_trace(go.Scatter(x=data.index, y=sma20,
58
+ name='SMA20',
59
+ line=dict(color='orange')))
60
+
61
+ fig.add_trace(go.Scatter(x=data.index, y=sma50,
62
+ name='SMA50',
63
+ line=dict(color='blue')))
64
+
65
+ fig.update_layout(
66
+ title=f'{ticker} Stock Price',
67
+ yaxis_title='Price',
68
+ template='plotly_dark',
69
+ xaxis_rangeslider_visible=False
70
+ )
71
+
72
+ return fig
73
+ except Exception as e:
74
+ return None
75
+
76
+ def get_technical_analysis(self, data):
77
+ """Generate technical analysis"""
78
+ try:
79
+ current_price = data['Close'].iloc[-1]
80
+ prev_price = data['Close'].iloc[-2]
81
+ price_change = ((current_price - prev_price) / prev_price) * 100
82
+
83
+ # Calculate indicators
84
+ rsi = RSIIndicator(close=data['Close']).rsi().iloc[-1]
85
+ macd = MACD(close=data['Close'])
86
+ macd_line = macd.macd().iloc[-1]
87
+ signal_line = macd.macd_signal().iloc[-1]
88
+
89
+ analysis = f"""
90
+ Technical Analysis Summary:
91
+
92
+ Current Price: ${current_price:.2f}
93
+ Daily Change: {price_change:.2f}%
94
+
95
+ Technical Indicators:
96
+ - RSI (14): {rsi:.2f} ({'Overbought' if rsi > 70 else 'Oversold' if rsi < 30 else 'Neutral'})
97
+ - MACD: {macd_line:.2f}
98
+ - Signal Line: {signal_line:.2f}
99
+ - MACD Status: {'Bullish' if macd_line > signal_line else 'Bearish'}
100
+
101
+ Volume Analysis:
102
+ - Current Volume: {int(data['Volume'].iloc[-1]):,}
103
+ - Avg Volume (20D): {int(data['Volume'].rolling(20).mean().iloc[-1]):,}
104
+ """
105
+ return analysis
106
+ except Exception as e:
107
+ return f"Error in technical analysis: {str(e)}"
108
+
109
+ def process_query(self, message, history):
110
+ """Process chat queries"""
111
+ try:
112
+ message = message.strip()
113
+
114
+ # Extract potential stock ticker
115
+ words = message.split()
116
+ ticker = None
117
+ for word in words:
118
+ if word.isupper() and 1 < len(word) <= 5:
119
+ ticker = word
120
+ break
121
+
122
+ if ticker:
123
+ data, info = self.get_stock_data(ticker)
124
+ if data is not None:
125
+ analysis = self.get_technical_analysis(data)
126
+ return analysis
127
+
128
+ # General queries
129
+ message_lower = message.lower()
130
+ if "help" in message_lower:
131
+ return """I can help you with:
132
+ 1. Stock Analysis (e.g., "Analyze AAPL")
133
+ 2. Technical Indicators (e.g., "What's RSI?")
134
+ 3. Market Information (e.g., "Tell me about TSLA")
135
+
136
+ You can also use the interface above to:
137
+ - View stock charts
138
+ - Get detailed technical analysis
139
+ - See price predictions
140
+ - Track multiple stocks"""
141
+
142
+ return "Please provide a stock ticker or ask for help to see what I can do."
143
+
144
+ except Exception as e:
145
+ return f"Error processing query: {str(e)}"
146
+
147
+ def create_ui():
148
+ """Create the complete Gradio interface"""
149
+ app = StockAnalysisApp()
150
+
151
+ def analyze_stock(ticker, period):
152
+ try:
153
+ data, info = app.get_stock_data(ticker, period)
154
+ if data is None:
155
+ return None, "Error fetching stock data"
156
+
157
+ chart = app.create_chart(data, ticker)
158
+ analysis = app.get_technical_analysis(data)
159
+
160
+ return chart, analysis
161
+ except Exception as e:
162
+ return None, f"Error: {str(e)}"
163
+
164
+ # Create the interface
165
+ with gr.Blocks(theme=gr.themes.Soft()) as interface:
166
+ gr.Markdown("""
167
+ # Stock Analysis Dashboard
168
+ Enter a stock ticker and select analysis period to get started.
169
+ """)
170
+
171
+ with gr.Row():
172
+ with gr.Column(scale=1):
173
+ ticker_input = gr.Textbox(
174
+ label="Stock Ticker",
175
+ placeholder="e.g., AAPL",
176
+ value="AAPL"
177
+ )
178
+ period_input = gr.Dropdown(
179
+ choices=["1mo", "3mo", "6mo", "1y", "2y", "5y"],
180
+ value="1y",
181
+ label="Analysis Period"
182
+ )
183
+ analyze_button = gr.Button("Analyze Stock")
184
+
185
+ with gr.Column(scale=2):
186
+ with gr.Tab("Chart"):
187
+ chart_output = gr.Plot()
188
+ with gr.Tab("Analysis"):
189
+ analysis_output = gr.Textbox(
190
+ label="Technical Analysis",
191
+ lines=10
192
+ )
193
+
194
+ gr.Markdown("---")
195
+
196
+ with gr.Row():
197
+ with gr.Column():
198
+ gr.Markdown("### Chat with AI Assistant")
199
+ chatbot = gr.ChatInterface(
200
+ app.process_query,
201
+ examples=[
202
+ "Analyze AAPL",
203
+ "What's the trend for TSLA?",
204
+ "Help"
205
+ ]
206
+ )
207
+
208
+ # Set up event handlers
209
+ analyze_button.click(
210
+ analyze_stock,
211
+ inputs=[ticker_input, period_input],
212
+ outputs=[chart_output, analysis_output]
213
+ )
214
+
215
+ return interface
216
+
217
+ # Launch the application
218
+ if __name__ == "__main__":
219
+ demo = create_ui()
220
+ demo.launch(share=True)