Reality123b commited on
Commit
1e0965c
·
verified ·
1 Parent(s): 9c3ace8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +147 -0
app.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import yfinance as yf
3
+ import pandas as pd
4
+ import numpy as np
5
+ from sklearn.model_selection import train_test_split
6
+ from sklearn.preprocessing import MinMaxScaler
7
+ from sklearn.linear_model import LinearRegression
8
+ from sklearn.metrics import mean_squared_error, r2_score
9
+ import mplfinance as mpf
10
+ import matplotlib.pyplot as plt
11
+
12
+
13
+ def get_stock_data(symbol, timeframe):
14
+ """Fetches stock data from Yahoo Finance."""
15
+ ticker = yf.Ticker(symbol)
16
+
17
+ # Calculate period based on timeframe
18
+ if timeframe in ['1m', '5m', '15m', '30m']:
19
+ period = "1d"
20
+ elif timeframe in ['1h']:
21
+ period = "5d"
22
+ else:
23
+ period = "60d"
24
+
25
+ data = ticker.history(period=period, interval=timeframe)
26
+ return data
27
+
28
+
29
+ def calculate_indicators(data):
30
+ """Calculates technical indicators."""
31
+ data['SMA20'] = data['Close'].rolling(window=20).mean() # Simple Moving Average (20 days)
32
+ data['EMA20'] = data['Close'].ewm(span=20, adjust=False).mean() # Exponential Moving Average (20 days)
33
+ data['RSI'] = calculate_rsi(data['Close']) # Relative Strength Index
34
+ data['MACD'], data['MACD_Signal'], _ = calculate_macd(data['Close']) # Moving Average Convergence Divergence
35
+ data['Stochastic_K'], data['Stochastic_D'] = calculate_stochastic(data['High'], data['Low'], data['Close']) # Stochastic Oscillator
36
+ return data
37
+
38
+
39
+
40
+ def calculate_rsi(close_prices, period=14):
41
+ """Calculates the Relative Strength Index (RSI)."""
42
+ delta = close_prices.diff()
43
+ gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
44
+ loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
45
+ rs = gain / loss
46
+ rsi = 100 - (100 / (1 + rs))
47
+ return rsi
48
+
49
+ def calculate_macd(close_prices, fast_period=12, slow_period=26, signal_period=9):
50
+ """Calculates the Moving Average Convergence Divergence (MACD)."""
51
+ fast_ema = close_prices.ewm(span=fast_period, adjust=False).mean()
52
+ slow_ema = close_prices.ewm(span=slow_period, adjust=False).mean()
53
+ macd = fast_ema - slow_ema
54
+ macd_signal = macd.ewm(span=signal_period, adjust=False).mean()
55
+ macd_histogram = macd - macd_signal
56
+ return macd, macd_signal, macd_histogram
57
+
58
+ def calculate_stochastic(high_prices, low_prices, close_prices, period=14):
59
+ """Calculates the Stochastic Oscillator."""
60
+ lowest_low = low_prices.rolling(window=period).min()
61
+ highest_high = high_prices.rolling(window=period).max()
62
+ k = ((close_prices - lowest_low) / (highest_high - lowest_low)) * 100
63
+ d = k.rolling(window=3).mean()
64
+ return k, d
65
+
66
+ def predict_next_day(symbol, timeframe):
67
+ """Predicts the next day's closing price."""
68
+ data = get_stock_data(symbol, timeframe)
69
+ data = calculate_indicators(data)
70
+
71
+ # Prepare data for training
72
+ data = data.dropna()
73
+ X = data[['SMA20', 'EMA20', 'RSI', 'MACD', 'MACD_Signal', 'Stochastic_K', 'Stochastic_D']]
74
+ y = data['Close']
75
+
76
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
77
+
78
+ # Scale the data
79
+ scaler = MinMaxScaler()
80
+ # Create a linear regression model
81
+ model = LinearRegression()
82
+ model.fit(X_train, y_train)
83
+
84
+ # Predict next day's closing price
85
+ last_data_point = data.iloc[-1]
86
+ last_data_point = last_data_point[['SMA20', 'EMA20', 'RSI', 'MACD', 'MACD_Signal', 'Stochastic_K', 'Stochastic_D']]
87
+ predicted_price = model.predict([last_data_point.values])[0]
88
+
89
+ # Calculate model evaluation metrics
90
+ y_pred = model.predict(X_test)
91
+ mse = mean_squared_error(y_test, y_pred)
92
+ rmse = np.sqrt(mse)
93
+ r2 = r2_score(y_test, y_pred)
94
+
95
+ print(f"Mean Squared Error: {mse:.2f}")
96
+ print(f"Root Mean Squared Error: {rmse:.2f}")
97
+ print(f"R-squared: {r2:.2f}")
98
+
99
+ return predicted_price
100
+
101
+ def plot_candlestick(data, symbol, timeframe, predicted_price=None):
102
+ """Plots the candlestick chart with technical indicators."""
103
+ fig, ax = plt.subplots(figsize=(12, 6))
104
+ mpf.plot(data, type='candle', style='charles', ax=ax, volume=True, show_nontrading=True)
105
+
106
+ # Add moving averages
107
+ ax.plot(data.index, data['SMA20'], label='SMA20', color='blue', alpha=0.7)
108
+ ax.plot(data.index, data['EMA20'], label='EMA20', color='red', alpha=0.7)
109
+
110
+ # Add prediction
111
+ if predicted_price is not None:
112
+ last_timestamp = data.index[-1] + pd.Timedelta(timeframe)
113
+ ax.scatter(last_timestamp, predicted_price, color='green', marker='*', s=100, label='Prediction')
114
+
115
+ ax.legend()
116
+ ax.set_title(f"{symbol} - {timeframe}")
117
+ ax.tick_params(axis='x', rotation=45)
118
+ fig.tight_layout()
119
+ return fig
120
+
121
+ def main():
122
+ """Gradio Interface."""
123
+
124
+ symbol = gr.inputs.Textbox(label="Symbol", default="AAPL")
125
+ timeframe = gr.inputs.Dropdown(label="Timeframe", choices=["1m", "5m", "15m", "30m", "1h", "1d"], default="1d")
126
+
127
+ with gr.Blocks() as interface:
128
+ gr.Markdown("## Real-time Stock Market Analysis")
129
+ with gr.Row():
130
+ symbol_input = gr.Textbox(label="Symbol", default="AAPL", interactive=True)
131
+ timeframe_input = gr.Dropdown(label="Timeframe", choices=["1m", "5m", "15m", "30m", "1h", "1d"], value="1d", interactive=True)
132
+
133
+ with gr.Row():
134
+ predict_button = gr.Button(value="Predict")
135
+ predicted_price = gr.Textbox(label="Predicted Price")
136
+
137
+ with gr.Row():
138
+ output_plot = gr.Plot(label="Candlestick Chart")
139
+
140
+ predict_button.click(fn=predict_next_day, inputs=[symbol_input, timeframe_input], outputs=predicted_price)
141
+
142
+ predicted_price.change(fn=plot_candlestick, inputs=[symbol_input, timeframe_input, predicted_price], outputs=output_plot)
143
+
144
+ interface.launch()
145
+
146
+ if _name_ == "_main_":
147
+ main()