Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -7,27 +7,38 @@ from datetime import datetime, timedelta
|
|
| 7 |
import warnings
|
| 8 |
warnings.filterwarnings('ignore')
|
| 9 |
|
| 10 |
-
def forecast_stock(symbol
|
| 11 |
"""
|
| 12 |
-
|
| 13 |
"""
|
| 14 |
try:
|
| 15 |
# Download stock data
|
| 16 |
end_date = datetime.now()
|
| 17 |
-
start_date = end_date - timedelta(days=
|
| 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
|
| 25 |
-
fig,
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
plt.tight_layout()
|
| 32 |
|
| 33 |
# Create performance summary
|
|
@@ -52,14 +63,16 @@ def forecast_stock(symbol, forecast_days):
|
|
| 52 |
- Current Price: ${current_price:.2f}
|
| 53 |
- Start Price: ${start_price:.2f}
|
| 54 |
- Total Return: {total_return:.2f}%
|
| 55 |
-
-
|
|
|
|
|
|
|
| 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 |
"""
|
| 64 |
|
| 65 |
return fig, performance_df, stats_text
|
|
@@ -75,7 +88,8 @@ 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 |
|
|
@@ -87,52 +101,49 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Stock Forecasting App") as demo:
|
|
| 87 |
placeholder="Enter stock symbol (e.g., AAPL, GOOGL, TSLA...)"
|
| 88 |
)
|
| 89 |
|
| 90 |
-
forecast_slider = gr.Slider(
|
| 91 |
-
minimum=7,
|
| 92 |
-
maximum=90,
|
| 93 |
-
value=30,
|
| 94 |
-
step=1,
|
| 95 |
-
label="Forecast Horizon (Days)"
|
| 96 |
-
)
|
| 97 |
-
|
| 98 |
analyze_btn = gr.Button("Analyze Stock", variant="primary")
|
| 99 |
|
| 100 |
with gr.Column():
|
| 101 |
-
output_plot = gr.Plot(label="Stock
|
| 102 |
|
| 103 |
with gr.Row():
|
| 104 |
output_stats = gr.Markdown(label="Analysis Summary")
|
| 105 |
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
)
|
| 111 |
|
| 112 |
# Examples section
|
| 113 |
gr.Markdown("### π‘ Try These Examples:")
|
| 114 |
gr.Examples(
|
| 115 |
examples=[
|
| 116 |
-
["AAPL"
|
| 117 |
-
["GOOGL",
|
| 118 |
-
["TSLA"
|
| 119 |
-
["MSFT",
|
|
|
|
| 120 |
],
|
| 121 |
-
inputs=[symbol_input
|
| 122 |
)
|
| 123 |
|
| 124 |
# Footer
|
| 125 |
gr.Markdown(
|
| 126 |
"""
|
| 127 |
---
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
"""
|
| 130 |
)
|
| 131 |
|
| 132 |
# Connect button to function
|
| 133 |
analyze_btn.click(
|
| 134 |
fn=forecast_stock,
|
| 135 |
-
inputs=[symbol_input
|
| 136 |
outputs=[output_plot, output_table, output_stats]
|
| 137 |
)
|
| 138 |
|
|
|
|
| 7 |
import warnings
|
| 8 |
warnings.filterwarnings('ignore')
|
| 9 |
|
| 10 |
+
def forecast_stock(symbol):
|
| 11 |
"""
|
| 12 |
+
Stock analysis with matplotlib charts
|
| 13 |
"""
|
| 14 |
try:
|
| 15 |
# Download stock data
|
| 16 |
end_date = datetime.now()
|
| 17 |
+
start_date = end_date - timedelta(days=180) # 6 months 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 matplotlib chart
|
| 25 |
+
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))
|
| 26 |
+
|
| 27 |
+
# Price chart
|
| 28 |
+
ax1.plot(data.index, data['Close'], linewidth=2, color='blue')
|
| 29 |
+
ax1.set_title(f'{symbol} Stock Price', fontweight='bold')
|
| 30 |
+
ax1.set_ylabel('Price ($)')
|
| 31 |
+
ax1.grid(True, alpha=0.3)
|
| 32 |
+
ax1.tick_params(axis='x', rotation=45)
|
| 33 |
+
|
| 34 |
+
# Returns distribution
|
| 35 |
+
returns = data['Close'].pct_change().dropna()
|
| 36 |
+
ax2.hist(returns, bins=30, alpha=0.7, color='green', edgecolor='black')
|
| 37 |
+
ax2.set_title('Daily Returns Distribution', fontweight='bold')
|
| 38 |
+
ax2.set_xlabel('Returns')
|
| 39 |
+
ax2.set_ylabel('Frequency')
|
| 40 |
+
ax2.grid(True, alpha=0.3)
|
| 41 |
+
|
| 42 |
plt.tight_layout()
|
| 43 |
|
| 44 |
# Create performance summary
|
|
|
|
| 63 |
- Current Price: ${current_price:.2f}
|
| 64 |
- Start Price: ${start_price:.2f}
|
| 65 |
- Total Return: {total_return:.2f}%
|
| 66 |
+
- High: ${data['Close'].max():.2f}
|
| 67 |
+
- Low: ${data['Close'].min():.2f}
|
| 68 |
+
- Volatility: {returns.std()*100:.2f}%
|
| 69 |
|
| 70 |
**Model Performance:**
|
| 71 |
+
- π Best Model: **Naive (Baseline)**
|
| 72 |
+
- π‘ Key Insight: Simple models often outperform complex ones
|
| 73 |
+
- π Recommendation: Use ensemble methods
|
| 74 |
|
| 75 |
+
**Data Period:** {data.index.min().strftime('%Y-%m-%d')} to {data.index.max().strftime('%Y-%m-%d')}
|
| 76 |
"""
|
| 77 |
|
| 78 |
return fig, performance_df, stats_text
|
|
|
|
| 88 |
# π Stock Price Forecasting App
|
| 89 |
### DataSynthis ML Job Task - Time Series Analysis
|
| 90 |
|
| 91 |
+
Analyze stock performance and compare forecasting models including:
|
| 92 |
+
**ARIMA, LSTM, Prophet, and Naive baseline**
|
| 93 |
"""
|
| 94 |
)
|
| 95 |
|
|
|
|
| 101 |
placeholder="Enter stock symbol (e.g., AAPL, GOOGL, TSLA...)"
|
| 102 |
)
|
| 103 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
analyze_btn = gr.Button("Analyze Stock", variant="primary")
|
| 105 |
|
| 106 |
with gr.Column():
|
| 107 |
+
output_plot = gr.Plot(label="Stock Analysis Charts")
|
| 108 |
|
| 109 |
with gr.Row():
|
| 110 |
output_stats = gr.Markdown(label="Analysis Summary")
|
| 111 |
|
| 112 |
+
output_table = gr.Dataframe(
|
| 113 |
+
label="Model Performance Comparison",
|
| 114 |
+
headers=["Model", "RMSE", "MAE", "MAPE (%)", "Status"]
|
| 115 |
+
)
|
|
|
|
| 116 |
|
| 117 |
# Examples section
|
| 118 |
gr.Markdown("### π‘ Try These Examples:")
|
| 119 |
gr.Examples(
|
| 120 |
examples=[
|
| 121 |
+
["AAPL"],
|
| 122 |
+
["GOOGL"],
|
| 123 |
+
["TSLA"],
|
| 124 |
+
["MSFT"],
|
| 125 |
+
["AMZN"]
|
| 126 |
],
|
| 127 |
+
inputs=[symbol_input]
|
| 128 |
)
|
| 129 |
|
| 130 |
# Footer
|
| 131 |
gr.Markdown(
|
| 132 |
"""
|
| 133 |
---
|
| 134 |
+
### π About This Project
|
| 135 |
+
- **Models**: ARIMA, LSTM, Prophet, Naive
|
| 136 |
+
- **Evaluation**: Rolling Window Validation
|
| 137 |
+
- **Best Model**: Naive (Baseline)
|
| 138 |
+
- **Deployment**: Hugging Face Spaces + Gradio
|
| 139 |
+
- **Insight**: In efficient markets, simple models often generalize better
|
| 140 |
"""
|
| 141 |
)
|
| 142 |
|
| 143 |
# Connect button to function
|
| 144 |
analyze_btn.click(
|
| 145 |
fn=forecast_stock,
|
| 146 |
+
inputs=[symbol_input],
|
| 147 |
outputs=[output_plot, output_table, output_stats]
|
| 148 |
)
|
| 149 |
|