Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,71 +1,32 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import pandas as pd
|
| 3 |
-
import numpy as np
|
| 4 |
import matplotlib.pyplot as plt
|
| 5 |
import yfinance as yf
|
| 6 |
from datetime import datetime, timedelta
|
| 7 |
import warnings
|
| 8 |
warnings.filterwarnings('ignore')
|
| 9 |
|
| 10 |
-
# Set matplotlib style
|
| 11 |
-
plt.style.use('default')
|
| 12 |
-
|
| 13 |
def analyze_stock(symbol):
|
| 14 |
"""
|
| 15 |
-
Stock analysis with
|
| 16 |
"""
|
| 17 |
try:
|
| 18 |
# Download stock data
|
| 19 |
end_date = datetime.now()
|
| 20 |
-
start_date = end_date - timedelta(days=180)
|
| 21 |
|
| 22 |
data = yf.download(symbol, start=start_date, end=end_date, progress=False)
|
| 23 |
|
| 24 |
if data.empty or len(data) < 5:
|
| 25 |
return None, None, "β No data found for this symbol. Try AAPL, GOOGL, TSLA, etc."
|
| 26 |
|
| 27 |
-
# Create
|
| 28 |
-
fig,
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
ax1.grid(True, alpha=0.3)
|
| 35 |
-
ax1.tick_params(axis='x', rotation=45)
|
| 36 |
-
|
| 37 |
-
# Chart 2: Daily returns distribution
|
| 38 |
-
returns = data['Close'].pct_change().dropna()
|
| 39 |
-
ax2.hist(returns, bins=50, alpha=0.7, color='#2ca02c', edgecolor='black')
|
| 40 |
-
ax2.set_title('Daily Returns Distribution', fontsize=14, fontweight='bold')
|
| 41 |
-
ax2.set_xlabel('Daily Returns')
|
| 42 |
-
ax2.set_ylabel('Frequency')
|
| 43 |
-
ax2.grid(True, alpha=0.3)
|
| 44 |
-
|
| 45 |
-
# Chart 3: Trading volume
|
| 46 |
-
ax3.bar(data.index, data['Volume'], alpha=0.7, color='#ff7f0e')
|
| 47 |
-
ax3.set_title('Trading Volume', fontsize=14, fontweight='bold')
|
| 48 |
-
ax3.set_ylabel('Volume')
|
| 49 |
-
ax3.tick_params(axis='x', rotation=45)
|
| 50 |
-
ax3.grid(True, alpha=0.3)
|
| 51 |
-
|
| 52 |
-
# Chart 4: Model performance comparison
|
| 53 |
-
models = ['Naive', 'LSTM', 'ARIMA', 'Prophet']
|
| 54 |
-
rmse_scores = [1.77, 6.44, 6.65, 58.52]
|
| 55 |
-
colors = ['#2ca02c', '#ff7f0e', '#1f77b4', '#d62728']
|
| 56 |
-
|
| 57 |
-
bars = ax4.bar(models, rmse_scores, color=colors, alpha=0.8)
|
| 58 |
-
ax4.set_title('Model Performance (RMSE)', fontsize=14, fontweight='bold')
|
| 59 |
-
ax4.set_ylabel('RMSE Score')
|
| 60 |
-
ax4.tick_params(axis='x', rotation=45)
|
| 61 |
-
ax4.grid(True, alpha=0.3)
|
| 62 |
-
|
| 63 |
-
# Add value labels on bars
|
| 64 |
-
for bar, value in zip(bars, rmse_scores):
|
| 65 |
-
height = bar.get_height()
|
| 66 |
-
ax4.text(bar.get_x() + bar.get_width()/2, height + 1,
|
| 67 |
-
f'{value}', ha='center', va='bottom', fontweight='bold')
|
| 68 |
-
|
| 69 |
plt.tight_layout()
|
| 70 |
|
| 71 |
# Create performance summary
|
|
@@ -78,17 +39,11 @@ def analyze_stock(symbol):
|
|
| 78 |
}
|
| 79 |
performance_df = pd.DataFrame(performance_data)
|
| 80 |
|
| 81 |
-
# Extract values
|
| 82 |
-
current_price = float(data['Close'].iloc[-1])
|
| 83 |
-
start_price = float(data['Close'].iloc[0])
|
| 84 |
-
high_price = float(data['Close'].max())
|
| 85 |
-
low_price = float(data['Close'].min())
|
| 86 |
-
|
| 87 |
-
# Calculate volatility safely
|
| 88 |
-
if len(returns) > 0:
|
| 89 |
-
volatility = float(returns.std()) * 100
|
| 90 |
-
else:
|
| 91 |
-
volatility = 0.0
|
| 92 |
|
| 93 |
total_return = ((current_price / start_price) - 1) * 100
|
| 94 |
price_change = current_price - start_price
|
|
@@ -101,13 +56,12 @@ def analyze_stock(symbol):
|
|
| 101 |
- **Price Change**: ${price_change:+.2f} ({total_return:+.2f}%)
|
| 102 |
- **Period High**: ${high_price:.2f}
|
| 103 |
- **Period Low**: ${low_price:.2f}
|
| 104 |
-
- **Volatility**: {volatility:.2f}%
|
| 105 |
- **Data Points**: {len(data)} trading days
|
| 106 |
|
| 107 |
## π― Model Performance
|
| 108 |
- **π Best Model**: Naive (Baseline)
|
| 109 |
-
- **π‘ Key Insight**: Simple models often outperform complex ones
|
| 110 |
-
- **π Recommendation**: Use ensemble methods
|
| 111 |
|
| 112 |
**Analysis Period**: {data.index.min().strftime('%Y-%m-%d')} to {data.index.max().strftime('%Y-%m-%d')}
|
| 113 |
"""
|
|
@@ -115,7 +69,7 @@ def analyze_stock(symbol):
|
|
| 115 |
return fig, performance_df, stats_text
|
| 116 |
|
| 117 |
except Exception as e:
|
| 118 |
-
error_msg = f"β Error: {str(e)}\n\nπ‘ Try
|
| 119 |
return None, None, error_msg
|
| 120 |
|
| 121 |
# Create Gradio interface
|
|
@@ -138,15 +92,14 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Stock Forecasting App") as demo:
|
|
| 138 |
analyze_btn = gr.Button("π Analyze Stock", variant="primary", size="lg")
|
| 139 |
|
| 140 |
with gr.Column():
|
| 141 |
-
output_plot = gr.Plot(label="π
|
| 142 |
|
| 143 |
with gr.Row():
|
| 144 |
output_stats = gr.Markdown(label="π Analysis Summary")
|
| 145 |
|
| 146 |
output_table = gr.Dataframe(
|
| 147 |
label="π― Model Performance Comparison",
|
| 148 |
-
headers=["Model", "RMSE", "MAE", "MAPE (%)", "Status"]
|
| 149 |
-
datatype=["str", "number", "number", "number", "str"]
|
| 150 |
)
|
| 151 |
|
| 152 |
# Examples section
|
|
@@ -156,11 +109,9 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Stock Forecasting App") as demo:
|
|
| 156 |
["AAPL"],
|
| 157 |
["GOOGL"],
|
| 158 |
["TSLA"],
|
| 159 |
-
["MSFT"]
|
| 160 |
-
["AMZN"]
|
| 161 |
],
|
| 162 |
-
inputs=[symbol_input]
|
| 163 |
-
label="Click any example to load it"
|
| 164 |
)
|
| 165 |
|
| 166 |
# Footer
|
|
@@ -174,7 +125,7 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Stock Forecasting App") as demo:
|
|
| 174 |
- **Prophet** (Facebook's Model)
|
| 175 |
- **Naive** (Baseline)
|
| 176 |
|
| 177 |
-
**Key Finding:**
|
| 178 |
|
| 179 |
**Deployment:** Hugging Face Spaces + Gradio
|
| 180 |
""")
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import pandas as pd
|
|
|
|
| 3 |
import matplotlib.pyplot as plt
|
| 4 |
import yfinance as yf
|
| 5 |
from datetime import datetime, timedelta
|
| 6 |
import warnings
|
| 7 |
warnings.filterwarnings('ignore')
|
| 8 |
|
|
|
|
|
|
|
|
|
|
| 9 |
def analyze_stock(symbol):
|
| 10 |
"""
|
| 11 |
+
Stock analysis with safe data handling
|
| 12 |
"""
|
| 13 |
try:
|
| 14 |
# Download stock data
|
| 15 |
end_date = datetime.now()
|
| 16 |
+
start_date = end_date - timedelta(days=180)
|
| 17 |
|
| 18 |
data = yf.download(symbol, start=start_date, end=end_date, progress=False)
|
| 19 |
|
| 20 |
if data.empty or len(data) < 5:
|
| 21 |
return None, None, "β No data found for this symbol. Try AAPL, GOOGL, TSLA, etc."
|
| 22 |
|
| 23 |
+
# Create simple chart
|
| 24 |
+
fig, ax = plt.subplots(figsize=(10, 5))
|
| 25 |
+
ax.plot(data.index, data['Close'], linewidth=2, color='blue')
|
| 26 |
+
ax.set_title(f'{symbol} Stock Price', fontsize=14, fontweight='bold')
|
| 27 |
+
ax.set_ylabel('Price ($)')
|
| 28 |
+
ax.grid(True, alpha=0.3)
|
| 29 |
+
ax.tick_params(axis='x', rotation=45)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
plt.tight_layout()
|
| 31 |
|
| 32 |
# Create performance summary
|
|
|
|
| 39 |
}
|
| 40 |
performance_df = pd.DataFrame(performance_data)
|
| 41 |
|
| 42 |
+
# Extract values safely - convert to native Python types
|
| 43 |
+
current_price = float(data['Close'].iloc[-1])
|
| 44 |
+
start_price = float(data['Close'].iloc[0])
|
| 45 |
+
high_price = float(data['Close'].max())
|
| 46 |
+
low_price = float(data['Close'].min())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
total_return = ((current_price / start_price) - 1) * 100
|
| 49 |
price_change = current_price - start_price
|
|
|
|
| 56 |
- **Price Change**: ${price_change:+.2f} ({total_return:+.2f}%)
|
| 57 |
- **Period High**: ${high_price:.2f}
|
| 58 |
- **Period Low**: ${low_price:.2f}
|
|
|
|
| 59 |
- **Data Points**: {len(data)} trading days
|
| 60 |
|
| 61 |
## π― Model Performance
|
| 62 |
- **π Best Model**: Naive (Baseline)
|
| 63 |
+
- **π‘ Key Insight**: Simple models often outperform complex ones
|
| 64 |
+
- **π Recommendation**: Use ensemble methods
|
| 65 |
|
| 66 |
**Analysis Period**: {data.index.min().strftime('%Y-%m-%d')} to {data.index.max().strftime('%Y-%m-%d')}
|
| 67 |
"""
|
|
|
|
| 69 |
return fig, performance_df, stats_text
|
| 70 |
|
| 71 |
except Exception as e:
|
| 72 |
+
error_msg = f"β Error: {str(e)}\n\nπ‘ Try symbols like: AAPL, TSLA, GOOGL, MSFT"
|
| 73 |
return None, None, error_msg
|
| 74 |
|
| 75 |
# Create Gradio interface
|
|
|
|
| 92 |
analyze_btn = gr.Button("π Analyze Stock", variant="primary", size="lg")
|
| 93 |
|
| 94 |
with gr.Column():
|
| 95 |
+
output_plot = gr.Plot(label="π Price Chart")
|
| 96 |
|
| 97 |
with gr.Row():
|
| 98 |
output_stats = gr.Markdown(label="π Analysis Summary")
|
| 99 |
|
| 100 |
output_table = gr.Dataframe(
|
| 101 |
label="π― Model Performance Comparison",
|
| 102 |
+
headers=["Model", "RMSE", "MAE", "MAPE (%)", "Status"]
|
|
|
|
| 103 |
)
|
| 104 |
|
| 105 |
# Examples section
|
|
|
|
| 109 |
["AAPL"],
|
| 110 |
["GOOGL"],
|
| 111 |
["TSLA"],
|
| 112 |
+
["MSFT"]
|
|
|
|
| 113 |
],
|
| 114 |
+
inputs=[symbol_input]
|
|
|
|
| 115 |
)
|
| 116 |
|
| 117 |
# Footer
|
|
|
|
| 125 |
- **Prophet** (Facebook's Model)
|
| 126 |
- **Naive** (Baseline)
|
| 127 |
|
| 128 |
+
**Key Finding:** Simple models often outperform complex ones in efficient markets.
|
| 129 |
|
| 130 |
**Deployment:** Hugging Face Spaces + Gradio
|
| 131 |
""")
|