Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -7,9 +7,6 @@ from datetime import datetime, timedelta
|
|
| 7 |
import warnings
|
| 8 |
warnings.filterwarnings('ignore')
|
| 9 |
|
| 10 |
-
# Set matplotlib style
|
| 11 |
-
plt.style.use('seaborn-v0_8')
|
| 12 |
-
|
| 13 |
def forecast_stock(symbol, forecast_days):
|
| 14 |
"""
|
| 15 |
Main function to generate stock forecast and analysis
|
|
@@ -17,80 +14,50 @@ def forecast_stock(symbol, forecast_days):
|
|
| 17 |
try:
|
| 18 |
# Download stock data
|
| 19 |
end_date = datetime.now()
|
| 20 |
-
start_date = end_date - timedelta(days=365
|
| 21 |
|
| 22 |
data = yf.download(symbol, start=start_date, end=end_date, progress=False)
|
| 23 |
|
| 24 |
-
if data.empty:
|
| 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 |
-
# Plot 2: Daily returns
|
| 38 |
-
returns = data['Close'].pct_change().dropna()
|
| 39 |
-
ax2.hist(returns, bins=50, alpha=0.7, color='green', edgecolor='black')
|
| 40 |
-
ax2.set_title('Daily Returns Distribution', fontsize=14, fontweight='bold')
|
| 41 |
-
ax2.set_xlabel('Returns')
|
| 42 |
-
ax2.set_ylabel('Frequency')
|
| 43 |
-
ax2.grid(True, alpha=0.3)
|
| 44 |
-
|
| 45 |
-
# Plot 3: Volume
|
| 46 |
-
ax3.bar(data.index, data['Volume'], alpha=0.7, color='orange')
|
| 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 |
-
# Plot 4: Model performance comparison
|
| 53 |
-
models = ['Naive', 'LSTM', 'ARIMA', 'Prophet']
|
| 54 |
-
rmse_scores = [1.77, 6.44, 6.65, 58.52]
|
| 55 |
-
colors = ['green', 'orange', 'blue', 'red']
|
| 56 |
-
|
| 57 |
-
bars = ax4.bar(models, rmse_scores, color=colors, alpha=0.7)
|
| 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 |
-
|
| 62 |
-
# Add value labels on bars
|
| 63 |
-
for bar, value in zip(bars, rmse_scores):
|
| 64 |
-
ax4.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5,
|
| 65 |
-
f'{value}', ha='center', va='bottom', fontweight='bold')
|
| 66 |
-
|
| 67 |
-
ax4.grid(True, alpha=0.3)
|
| 68 |
-
|
| 69 |
plt.tight_layout()
|
| 70 |
|
| 71 |
# Create performance summary
|
| 72 |
-
|
| 73 |
'Model': ['Naive', 'LSTM', 'ARIMA', 'Prophet'],
|
| 74 |
'RMSE': [1.77, 6.44, 6.65, 58.52],
|
| 75 |
'MAE': [1.36, 5.30, 4.98, 34.89],
|
| 76 |
'MAPE (%)': [1.24, 4.82, 4.46, 32.81],
|
| 77 |
'Status': ['β
Best', 'β οΈ Needs Tuning', 'β οΈ Needs Tuning', 'β Poor']
|
| 78 |
-
}
|
|
|
|
| 79 |
|
| 80 |
# Create stats summary
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
stats_text = f"""
|
| 82 |
π **Stock Analysis Summary for {symbol}**
|
| 83 |
|
| 84 |
**Price Statistics:**
|
| 85 |
-
- Current Price: ${
|
| 86 |
-
-
|
| 87 |
-
-
|
| 88 |
-
-
|
| 89 |
|
| 90 |
-
**Model
|
| 91 |
- Best Model: **Naive (Baseline)**
|
| 92 |
-
- Key
|
| 93 |
-
- Recommendation: Use ensemble methods
|
| 94 |
|
| 95 |
**Period:** {data.index.min().strftime('%Y-%m-%d')} to {data.index.max().strftime('%Y-%m-%d')}
|
| 96 |
"""
|
|
@@ -98,7 +65,8 @@ def forecast_stock(symbol, forecast_days):
|
|
| 98 |
return fig, performance_df, stats_text
|
| 99 |
|
| 100 |
except Exception as e:
|
| 101 |
-
|
|
|
|
| 102 |
|
| 103 |
# Create Gradio interface
|
| 104 |
with gr.Blocks(theme=gr.themes.Soft(), title="Stock Forecasting App") as demo:
|
|
@@ -107,8 +75,7 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Stock Forecasting App") as demo:
|
|
| 107 |
# π Stock Price Forecasting App
|
| 108 |
### DataSynthis ML Job Task - Time Series Analysis
|
| 109 |
|
| 110 |
-
|
| 111 |
-
**ARIMA, LSTM, Prophet, and Naive baseline**
|
| 112 |
"""
|
| 113 |
)
|
| 114 |
|
|
@@ -131,7 +98,7 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Stock Forecasting App") as demo:
|
|
| 131 |
analyze_btn = gr.Button("Analyze Stock", variant="primary")
|
| 132 |
|
| 133 |
with gr.Column():
|
| 134 |
-
output_plot = gr.Plot(label="Stock
|
| 135 |
|
| 136 |
with gr.Row():
|
| 137 |
output_stats = gr.Markdown(label="Analysis Summary")
|
|
@@ -139,8 +106,7 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Stock Forecasting App") as demo:
|
|
| 139 |
with gr.Row():
|
| 140 |
output_table = gr.Dataframe(
|
| 141 |
label="Model Performance Comparison",
|
| 142 |
-
headers=["Model", "RMSE", "MAE", "MAPE (%)", "Status"]
|
| 143 |
-
datatype=["str", "number", "number", "number", "str"]
|
| 144 |
)
|
| 145 |
|
| 146 |
# Examples section
|
|
@@ -150,8 +116,7 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Stock Forecasting App") as demo:
|
|
| 150 |
["AAPL", 30],
|
| 151 |
["GOOGL", 30],
|
| 152 |
["TSLA", 30],
|
| 153 |
-
["MSFT", 30]
|
| 154 |
-
["AMZN", 30]
|
| 155 |
],
|
| 156 |
inputs=[symbol_input, forecast_slider]
|
| 157 |
)
|
|
@@ -160,12 +125,7 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Stock Forecasting App") as demo:
|
|
| 160 |
gr.Markdown(
|
| 161 |
"""
|
| 162 |
---
|
| 163 |
-
|
| 164 |
-
- **Models**: ARIMA, LSTM, Prophet, Naive
|
| 165 |
-
- **Evaluation**: Rolling Window Validation
|
| 166 |
-
- **Best Model**: Naive (Baseline)
|
| 167 |
-
- **Deployment**: Hugging Face Spaces + Gradio
|
| 168 |
-
- **Insight**: In efficient markets, simple models often generalize better
|
| 169 |
"""
|
| 170 |
)
|
| 171 |
|
|
@@ -178,4 +138,4 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Stock Forecasting App") as demo:
|
|
| 178 |
|
| 179 |
# Launch the app
|
| 180 |
if __name__ == "__main__":
|
| 181 |
-
demo.launch(
|
|
|
|
| 7 |
import warnings
|
| 8 |
warnings.filterwarnings('ignore')
|
| 9 |
|
|
|
|
|
|
|
|
|
|
| 10 |
def forecast_stock(symbol, forecast_days):
|
| 11 |
"""
|
| 12 |
Main function to generate stock forecast and analysis
|
|
|
|
| 14 |
try:
|
| 15 |
# Download stock data
|
| 16 |
end_date = datetime.now()
|
| 17 |
+
start_date = end_date - timedelta(days=365) # Reduced to 1 year for faster loading
|
| 18 |
|
| 19 |
data = yf.download(symbol, start=start_date, end=end_date, progress=False)
|
| 20 |
|
| 21 |
+
if data.empty or len(data) < 10:
|
| 22 |
return None, None, "β No data found for this symbol. Try AAPL, GOOGL, TSLA, etc."
|
| 23 |
|
| 24 |
+
# Create a single figure instead of subplots for simplicity
|
| 25 |
+
fig, ax = plt.subplots(figsize=(10, 6))
|
| 26 |
+
ax.plot(data.index, data['Close'], linewidth=2, color='blue')
|
| 27 |
+
ax.set_title(f'{symbol} Stock Price', fontsize=14, fontweight='bold')
|
| 28 |
+
ax.set_ylabel('Price ($)')
|
| 29 |
+
ax.grid(True, alpha=0.3)
|
| 30 |
+
ax.tick_params(axis='x', rotation=45)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
plt.tight_layout()
|
| 32 |
|
| 33 |
# Create performance summary
|
| 34 |
+
performance_data = {
|
| 35 |
'Model': ['Naive', 'LSTM', 'ARIMA', 'Prophet'],
|
| 36 |
'RMSE': [1.77, 6.44, 6.65, 58.52],
|
| 37 |
'MAE': [1.36, 5.30, 4.98, 34.89],
|
| 38 |
'MAPE (%)': [1.24, 4.82, 4.46, 32.81],
|
| 39 |
'Status': ['β
Best', 'β οΈ Needs Tuning', 'β οΈ Needs Tuning', 'β Poor']
|
| 40 |
+
}
|
| 41 |
+
performance_df = pd.DataFrame(performance_data)
|
| 42 |
|
| 43 |
# Create stats summary
|
| 44 |
+
current_price = data['Close'].iloc[-1]
|
| 45 |
+
start_price = data['Close'].iloc[0]
|
| 46 |
+
total_return = ((current_price / start_price) - 1) * 100
|
| 47 |
+
|
| 48 |
stats_text = f"""
|
| 49 |
π **Stock Analysis Summary for {symbol}**
|
| 50 |
|
| 51 |
**Price Statistics:**
|
| 52 |
+
- Current Price: ${current_price:.2f}
|
| 53 |
+
- Start Price: ${start_price:.2f}
|
| 54 |
+
- Total Return: {total_return:.2f}%
|
| 55 |
+
- Data Points: {len(data)} days
|
| 56 |
|
| 57 |
+
**Model Performance:**
|
| 58 |
- Best Model: **Naive (Baseline)**
|
| 59 |
+
- Key Insight: Simple models often outperform complex ones
|
| 60 |
+
- Recommendation: Use ensemble methods
|
| 61 |
|
| 62 |
**Period:** {data.index.min().strftime('%Y-%m-%d')} to {data.index.max().strftime('%Y-%m-%d')}
|
| 63 |
"""
|
|
|
|
| 65 |
return fig, performance_df, stats_text
|
| 66 |
|
| 67 |
except Exception as e:
|
| 68 |
+
error_msg = f"β Error: {str(e)}. Try a different stock symbol like AAPL or TSLA."
|
| 69 |
+
return None, None, error_msg
|
| 70 |
|
| 71 |
# Create Gradio interface
|
| 72 |
with gr.Blocks(theme=gr.themes.Soft(), title="Stock Forecasting App") as demo:
|
|
|
|
| 75 |
# π Stock Price Forecasting App
|
| 76 |
### DataSynthis ML Job Task - Time Series Analysis
|
| 77 |
|
| 78 |
+
Analyze stock performance and compare forecasting models.
|
|
|
|
| 79 |
"""
|
| 80 |
)
|
| 81 |
|
|
|
|
| 98 |
analyze_btn = gr.Button("Analyze Stock", variant="primary")
|
| 99 |
|
| 100 |
with gr.Column():
|
| 101 |
+
output_plot = gr.Plot(label="Stock Price Chart")
|
| 102 |
|
| 103 |
with gr.Row():
|
| 104 |
output_stats = gr.Markdown(label="Analysis Summary")
|
|
|
|
| 106 |
with gr.Row():
|
| 107 |
output_table = gr.Dataframe(
|
| 108 |
label="Model Performance Comparison",
|
| 109 |
+
headers=["Model", "RMSE", "MAE", "MAPE (%)", "Status"]
|
|
|
|
| 110 |
)
|
| 111 |
|
| 112 |
# Examples section
|
|
|
|
| 116 |
["AAPL", 30],
|
| 117 |
["GOOGL", 30],
|
| 118 |
["TSLA", 30],
|
| 119 |
+
["MSFT", 30]
|
|
|
|
| 120 |
],
|
| 121 |
inputs=[symbol_input, forecast_slider]
|
| 122 |
)
|
|
|
|
| 125 |
gr.Markdown(
|
| 126 |
"""
|
| 127 |
---
|
| 128 |
+
**About:** Stock forecasting models comparison | **Deployment:** Hugging Face Spaces
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
"""
|
| 130 |
)
|
| 131 |
|
|
|
|
| 138 |
|
| 139 |
# Launch the app
|
| 140 |
if __name__ == "__main__":
|
| 141 |
+
demo.launch()
|