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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# %%
|
| 2 |
+
# Install necessary packages if not already installed
|
| 3 |
+
# pip install gradio yfinance prophet plotly matplotlib
|
| 4 |
+
|
| 5 |
+
import gradio as gr
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import yfinance as yf
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
from prophet import Prophet
|
| 10 |
+
import plotly.express as px
|
| 11 |
+
import plotly.graph_objects as go
|
| 12 |
+
import matplotlib.pyplot as plt
|
| 13 |
+
import numpy as np
|
| 14 |
+
|
| 15 |
+
# Functions for calculating indicators (SMA, RSI, etc.) and generating trading signals
|
| 16 |
+
# (Reuse the code you've already written for technical indicators and forecasting)
|
| 17 |
+
|
| 18 |
+
def calculate_sma(df, window):
|
| 19 |
+
return df['Close'].rolling(window=window).mean()
|
| 20 |
+
|
| 21 |
+
def calculate_macd(df):
|
| 22 |
+
short_ema = df['Close'].ewm(span=12, adjust=False).mean()
|
| 23 |
+
long_ema = df['Close'].ewm(span=26, adjust=False).mean()
|
| 24 |
+
macd = short_ema - long_ema
|
| 25 |
+
signal = macd.ewm(span=9, adjust=False).mean()
|
| 26 |
+
return macd, signal
|
| 27 |
+
|
| 28 |
+
def calculate_rsi(df):
|
| 29 |
+
delta = df['Close'].diff()
|
| 30 |
+
gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
|
| 31 |
+
loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()
|
| 32 |
+
rs = gain / loss
|
| 33 |
+
rsi = 100 - (100 / (1 + rs))
|
| 34 |
+
return rsi
|
| 35 |
+
|
| 36 |
+
def calculate_bollinger_bands(df):
|
| 37 |
+
middle_bb = df['Close'].rolling(window=20).mean()
|
| 38 |
+
upper_bb = middle_bb + 2 * df['Close'].rolling(window=20).std()
|
| 39 |
+
lower_bb = middle_bb - 2 * df['Close'].rolling(window=20).std()
|
| 40 |
+
return middle_bb, upper_bb, lower_bb
|
| 41 |
+
|
| 42 |
+
def calculate_stochastic_oscillator(df):
|
| 43 |
+
lowest_low = df['Low'].rolling(window=14).min()
|
| 44 |
+
highest_high = df['High'].rolling(window=14).max()
|
| 45 |
+
slowk = ((df['Close'] - lowest_low) / (highest_high - lowest_low)) * 100
|
| 46 |
+
slowd = slowk.rolling(window=3).mean()
|
| 47 |
+
return slowk, slowd
|
| 48 |
+
|
| 49 |
+
def generate_trading_signals(df):
|
| 50 |
+
|
| 51 |
+
# Calculate Simple Moving Averages (SMA)
|
| 52 |
+
df['SMA_50'] = calculate_sma(df, 50)
|
| 53 |
+
df['SMA_200'] = calculate_sma(df, 200)
|
| 54 |
+
|
| 55 |
+
# Calculate other technical indicators
|
| 56 |
+
df['RSI'] = calculate_rsi(df)
|
| 57 |
+
df['MiddleBB'], df['UpperBB'], df['LowerBB'] = calculate_bollinger_bands(df)
|
| 58 |
+
df['SlowK'], df['SlowD'] = calculate_stochastic_oscillator(df)
|
| 59 |
+
|
| 60 |
+
# Generate trading signals
|
| 61 |
+
df['SMA_Signal'] = np.where(df['SMA_50'] > df['SMA_200'], 1, 0)
|
| 62 |
+
|
| 63 |
+
macd, signal = calculate_macd(df)
|
| 64 |
+
df['MACD_Signal'] = np.where((macd > signal.shift(1)) & (macd.shift(1) < signal), 1, 0)
|
| 65 |
+
|
| 66 |
+
df['RSI_Signal'] = np.where(df['RSI'] < 30, 1, 0)
|
| 67 |
+
df['RSI_Signal'] = np.where(df['RSI'] > 70, -1, df['RSI_Signal'])
|
| 68 |
+
|
| 69 |
+
df['BB_Signal'] = np.where(df['Close'] < df['LowerBB'], 1, 0)
|
| 70 |
+
df['BB_Signal'] = np.where(df['Close'] > df['UpperBB'], -1, df['BB_Signal'])
|
| 71 |
+
|
| 72 |
+
df['Stochastic_Signal'] = np.where((df['SlowK'] < 20) & (df['SlowD'] < 20), 1, 0)
|
| 73 |
+
df['Stochastic_Signal'] = np.where((df['SlowK'] > 80) & (df['SlowD'] > 80), -1, df['Stochastic_Signal'])
|
| 74 |
+
|
| 75 |
+
# Summing the values of each individual signal column
|
| 76 |
+
df['Combined_Signal'] = df[['SMA_Signal', 'MACD_Signal', 'RSI_Signal', 'BB_Signal', 'Stochastic_Signal']].sum(axis=1)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
# %%
|
| 84 |
+
import plotly.graph_objects as go
|
| 85 |
+
|
| 86 |
+
def plot_combined_signals(df, ticker):
|
| 87 |
+
# Create a figure
|
| 88 |
+
fig = go.Figure()
|
| 89 |
+
|
| 90 |
+
# Add closing price trace
|
| 91 |
+
fig.add_trace(go.Scatter(
|
| 92 |
+
x=df.index, y=df['Close'],
|
| 93 |
+
mode='lines',
|
| 94 |
+
name='Closing Price',
|
| 95 |
+
line=dict(color='lightcoral', width=2)
|
| 96 |
+
))
|
| 97 |
+
|
| 98 |
+
# Add buy signals
|
| 99 |
+
buy_signals = df[df['Combined_Signal'] >= 2]
|
| 100 |
+
fig.add_trace(go.Scatter(
|
| 101 |
+
x=buy_signals.index, y=buy_signals['Close'],
|
| 102 |
+
mode='markers',
|
| 103 |
+
marker=dict(symbol='triangle-up', size=10, color='lightgreen'),
|
| 104 |
+
name='Buy Signal'
|
| 105 |
+
))
|
| 106 |
+
|
| 107 |
+
# Add sell signals
|
| 108 |
+
sell_signals = df[df['Combined_Signal'] <= -2]
|
| 109 |
+
fig.add_trace(go.Scatter(
|
| 110 |
+
x=sell_signals.index, y=sell_signals['Close'],
|
| 111 |
+
mode='markers',
|
| 112 |
+
marker=dict(symbol='triangle-down', size=10, color='lightsalmon'),
|
| 113 |
+
name='Sell Signal'
|
| 114 |
+
))
|
| 115 |
+
|
| 116 |
+
# Add combined signal trace
|
| 117 |
+
fig.add_trace(go.Scatter(
|
| 118 |
+
x=df.index, y=df['Combined_Signal'],
|
| 119 |
+
mode='lines',
|
| 120 |
+
name='Combined Signal',
|
| 121 |
+
line=dict(color='deepskyblue', width=2),
|
| 122 |
+
yaxis='y2'
|
| 123 |
+
))
|
| 124 |
+
|
| 125 |
+
# Update layout for secondary y-axis
|
| 126 |
+
fig.update_layout(
|
| 127 |
+
title=f'{ticker}: Stock Price and Combined Trading Signal (Last 60 Days)',
|
| 128 |
+
xaxis=dict(title='Date', gridcolor='gray', gridwidth=0.5),
|
| 129 |
+
yaxis=dict(title='Price', side='left', gridcolor='gray', gridwidth=0.5),
|
| 130 |
+
yaxis2=dict(title='Combined Signal', overlaying='y', side='right', showgrid=False),
|
| 131 |
+
plot_bgcolor='black',
|
| 132 |
+
paper_bgcolor='black',
|
| 133 |
+
font=dict(color='white'),
|
| 134 |
+
legend=dict(x=0.01, y=0.99, bgcolor='rgba(0,0,0,0)'),
|
| 135 |
+
hovermode='x unified'
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
return fig
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
# %%
|
| 142 |
+
def stock_analysis(ticker, start_date, end_date):
|
| 143 |
+
# Download stock data from Yahoo Finance
|
| 144 |
+
df = yf.download(ticker, start=start_date, end=end_date)
|
| 145 |
+
|
| 146 |
+
# Run your existing trading signals and indicators here
|
| 147 |
+
generate_trading_signals(df)
|
| 148 |
+
|
| 149 |
+
# Last 60 days
|
| 150 |
+
df_last_60 = df.tail(60)
|
| 151 |
+
|
| 152 |
+
# Plot trading signals using the improved function
|
| 153 |
+
fig_signals = plot_combined_signals(df_last_60, ticker)
|
| 154 |
+
|
| 155 |
+
# Prophet-based stock price forecasting
|
| 156 |
+
df_plot = df.reset_index()[['Date', 'Close']].rename(columns={'Date': 'ds', 'Close': 'y'})
|
| 157 |
+
m = Prophet()
|
| 158 |
+
m.fit(df_plot)
|
| 159 |
+
future = m.make_future_dataframe(periods=30)
|
| 160 |
+
forecast = m.predict(future)
|
| 161 |
+
#fig_forecast = px.line(forecast.tail(40), x="ds", y=['yhat', 'yhat_lower', 'yhat_upper'], title=f'{ticker} - 30 Days Forecast')
|
| 162 |
+
fig_forecast = m.plot_components(forecast)
|
| 163 |
+
|
| 164 |
+
# Combine the figures into HTML output
|
| 165 |
+
return fig_signals, fig_forecast
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
# %%
|
| 169 |
+
# Define Gradio interface
|
| 170 |
+
with gr.Blocks() as demo:
|
| 171 |
+
gr.Markdown("## Stock Market Analysis App")
|
| 172 |
+
|
| 173 |
+
ticker_input = gr.Textbox(label="Enter Stock Ticker (e.g., AAPL, NVDA)", value="NVDA")
|
| 174 |
+
start_date_input = gr.Textbox(label="Start Date (YYYY-MM-DD)", value="2022-01-01")
|
| 175 |
+
end_date_input = gr.Textbox(label="End Date (YYYY-MM-DD)", value=str(datetime.now().date()))
|
| 176 |
+
|
| 177 |
+
# Create a submit button that runs the stock analysis function
|
| 178 |
+
button = gr.Button("Analyze Stock")
|
| 179 |
+
|
| 180 |
+
# Outputs: Display results, charts
|
| 181 |
+
signals_output = gr.Plot(label="Trading Signals")
|
| 182 |
+
forecast_output = gr.Plot(label="Stock Price Forecast")
|
| 183 |
+
|
| 184 |
+
# Link button to function
|
| 185 |
+
button.click(stock_analysis, inputs=[ticker_input, start_date_input, end_date_input], outputs=[signals_output, forecast_output])
|
| 186 |
+
|
| 187 |
+
# Launch the interface
|
| 188 |
+
demo.launch()
|
| 189 |
+
|
| 190 |
+
|