Spaces:
Running
on
Zero
Running
on
Zero
add fallbacks, padding, scalign
Browse files- .gitignore +0 -41
- README.md +191 -34
- app.py +14 -10
.gitignore
DELETED
@@ -1,41 +0,0 @@
|
|
1 |
-
# Python
|
2 |
-
__pycache__/
|
3 |
-
*.py[cod]
|
4 |
-
*$py.class
|
5 |
-
*.so
|
6 |
-
.Python
|
7 |
-
build/
|
8 |
-
develop-eggs/
|
9 |
-
dist/
|
10 |
-
downloads/
|
11 |
-
eggs/
|
12 |
-
.eggs/
|
13 |
-
lib/
|
14 |
-
lib64/
|
15 |
-
parts/
|
16 |
-
sdist/
|
17 |
-
var/
|
18 |
-
wheels/
|
19 |
-
*.egg-info/
|
20 |
-
.installed.cfg
|
21 |
-
*.egg
|
22 |
-
|
23 |
-
# Virtual Environment
|
24 |
-
venv/
|
25 |
-
env/
|
26 |
-
ENV/
|
27 |
-
|
28 |
-
# IDE
|
29 |
-
.idea/
|
30 |
-
.vscode/
|
31 |
-
*.swp
|
32 |
-
*.swo
|
33 |
-
|
34 |
-
# OS
|
35 |
-
.DS_Store
|
36 |
-
Thumbs.db
|
37 |
-
|
38 |
-
# Project specific
|
39 |
-
*.log
|
40 |
-
.env
|
41 |
-
.env.local
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
README.md
CHANGED
@@ -13,66 +13,223 @@ tags:
|
|
13 |
- mcp-server-track
|
14 |
---
|
15 |
|
16 |
-
# Stock
|
17 |
|
18 |
-
A
|
19 |
|
20 |
## Features
|
21 |
|
22 |
-
- Multiple
|
23 |
-
-
|
24 |
-
- Technical analysis
|
25 |
-
|
26 |
-
-
|
27 |
-
-
|
28 |
-
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
-
|
33 |
-
-
|
34 |
-
-
|
35 |
-
-
|
36 |
-
|
37 |
-
-
|
38 |
-
-
|
39 |
-
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
40 |
|
41 |
## Installation
|
42 |
|
43 |
1. Clone the repository:
|
44 |
```bash
|
45 |
-
git clone
|
46 |
-
cd stock-
|
47 |
```
|
48 |
|
49 |
-
2.
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
```bash
|
51 |
pip install -r requirements.txt
|
52 |
```
|
53 |
|
54 |
## Usage
|
55 |
|
56 |
-
|
57 |
```bash
|
58 |
python app.py
|
59 |
```
|
60 |
|
61 |
-
|
62 |
|
63 |
-
|
|
|
|
|
|
|
|
|
64 |
|
65 |
-
|
66 |
-
-
|
67 |
-
-
|
68 |
-
-
|
69 |
-
-
|
70 |
-
- **Sector Analysis**: Market cap, industry classification, liquidity metrics
|
71 |
|
72 |
-
##
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
|
74 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
75 |
|
76 |
## Contributing
|
77 |
|
78 |
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
- mcp-server-track
|
14 |
---
|
15 |
|
16 |
+
# Stock Analysis and Prediction Demo
|
17 |
|
18 |
+
A comprehensive stock analysis and prediction tool built with Gradio, featuring multiple prediction strategies and technical analysis indicators. The application is particularly suited for structured financial product creation and analysis.
|
19 |
|
20 |
## Features
|
21 |
|
22 |
+
- **Multiple Prediction Strategies**:
|
23 |
+
- Chronos ML-based prediction
|
24 |
+
- Technical analysis-based prediction
|
25 |
+
|
26 |
+
- **Technical Indicators**:
|
27 |
+
- RSI (Relative Strength Index)
|
28 |
+
- MACD (Moving Average Convergence Divergence)
|
29 |
+
- Bollinger Bands
|
30 |
+
- Simple Moving Averages (20, 50, and 200-day)
|
31 |
+
|
32 |
+
- **Trading Signals**:
|
33 |
+
- Buy/Sell recommendations based on multiple indicators
|
34 |
+
- Overall trading signal combining all indicators
|
35 |
+
- Confidence intervals for predictions
|
36 |
+
|
37 |
+
- **Interactive Visualizations**:
|
38 |
+
- Price prediction with confidence intervals
|
39 |
+
- Technical indicators overlay
|
40 |
+
- Volume analysis
|
41 |
+
- Historical price trends
|
42 |
+
|
43 |
+
- **Structured Product Analysis**:
|
44 |
+
- Extended prediction horizons (up to 1 year)
|
45 |
+
- Historical analysis up to 10 years
|
46 |
+
- Comprehensive risk metrics
|
47 |
+
- Sector and industry analysis
|
48 |
+
- Liquidity assessment
|
49 |
+
|
50 |
+
## Structured Product Features
|
51 |
+
|
52 |
+
### Extended Time Horizons
|
53 |
+
- Prediction window up to 365 days
|
54 |
+
- Historical data analysis up to 10 years
|
55 |
+
- Long-term trend analysis
|
56 |
+
- Extended technical indicators
|
57 |
+
|
58 |
+
### Risk Analysis
|
59 |
+
- Annualized volatility
|
60 |
+
- Maximum drawdown analysis
|
61 |
+
- Current drawdown tracking
|
62 |
+
- Sharpe and Sortino ratios
|
63 |
+
- Risk-adjusted return metrics
|
64 |
+
|
65 |
+
### Product Metrics
|
66 |
+
- Market capitalization
|
67 |
+
- Sector and industry classification
|
68 |
+
- Dividend yield analysis
|
69 |
+
- Volume metrics
|
70 |
+
- Liquidity scoring
|
71 |
+
|
72 |
+
### Sector Analysis
|
73 |
+
- Market cap ranking (Large/Mid/Small)
|
74 |
+
- Sector exposure
|
75 |
+
- Industry classification
|
76 |
+
- Liquidity assessment
|
77 |
|
78 |
## Installation
|
79 |
|
80 |
1. Clone the repository:
|
81 |
```bash
|
82 |
+
git clone <repository-url>
|
83 |
+
cd stock-prediction
|
84 |
```
|
85 |
|
86 |
+
2. Create and activate a virtual environment:
|
87 |
+
```bash
|
88 |
+
python -m venv .venv
|
89 |
+
source .venv/bin/activate # On Windows: .venv\Scripts\activate
|
90 |
+
```
|
91 |
+
|
92 |
+
3. Install dependencies:
|
93 |
```bash
|
94 |
pip install -r requirements.txt
|
95 |
```
|
96 |
|
97 |
## Usage
|
98 |
|
99 |
+
1. Start the Gradio demo:
|
100 |
```bash
|
101 |
python app.py
|
102 |
```
|
103 |
|
104 |
+
2. Open your web browser and navigate to the URL shown in the terminal (typically http://localhost:7860)
|
105 |
|
106 |
+
3. Enter a stock symbol (e.g., AAPL, GOOGL, MSFT) and select your desired parameters:
|
107 |
+
- Timeframe (1d, 1h, 15m)
|
108 |
+
- Number of days to predict (up to 365 days)
|
109 |
+
- Historical lookback period (up to 10 years)
|
110 |
+
- Prediction strategy (Chronos or Technical)
|
111 |
|
112 |
+
4. Click "Analyze Stock" to get:
|
113 |
+
- Price predictions and trading signals
|
114 |
+
- Structured product metrics
|
115 |
+
- Risk analysis
|
116 |
+
- Sector analysis
|
|
|
117 |
|
118 |
+
## Using for Structured Products
|
119 |
+
|
120 |
+
### Initial Screening
|
121 |
+
1. Use extended lookback period (up to 10 years) for long-term performance analysis
|
122 |
+
2. Look for stocks with stable volatility and good risk-adjusted returns
|
123 |
+
3. Check liquidity scores for trading feasibility
|
124 |
+
|
125 |
+
### Risk Assessment
|
126 |
+
1. Review risk metrics to match client risk profile
|
127 |
+
2. Analyze maximum drawdowns for worst-case scenarios
|
128 |
+
3. Compare risk-adjusted returns using Sharpe and Sortino ratios
|
129 |
+
|
130 |
+
### Product Structuring
|
131 |
+
1. Use prediction horizon (up to 1 year) for product maturity design
|
132 |
+
2. Consider dividend yields for income-generating products
|
133 |
+
3. Use sector analysis for proper diversification
|
134 |
+
|
135 |
+
### Portfolio Construction
|
136 |
+
1. Analyze multiple stocks for diversified bundles
|
137 |
+
2. Use sector metrics to avoid overexposure
|
138 |
+
3. Consider market cap rankings for appropriate sizing
|
139 |
|
140 |
+
## Prediction Strategies
|
141 |
+
|
142 |
+
### Chronos Strategy
|
143 |
+
Uses Amazon's Chronos model for ML-based price prediction. This strategy:
|
144 |
+
- Analyzes historical price patterns
|
145 |
+
- Generates probabilistic forecasts
|
146 |
+
- Provides confidence intervals
|
147 |
+
|
148 |
+
### Technical Strategy
|
149 |
+
Uses traditional technical analysis indicators to generate predictions:
|
150 |
+
- RSI for overbought/oversold conditions
|
151 |
+
- MACD for trend direction
|
152 |
+
- Bollinger Bands for volatility
|
153 |
+
- Moving Averages for trend confirmation
|
154 |
+
|
155 |
+
## Trading Signals
|
156 |
+
|
157 |
+
The demo provides trading signals based on multiple technical indicators:
|
158 |
+
- RSI: Oversold (<30), Overbought (>70), Neutral
|
159 |
+
- MACD: Buy (MACD > Signal), Sell (MACD < Signal)
|
160 |
+
- Bollinger Bands: Buy (price < lower band), Sell (price > upper band)
|
161 |
+
- SMA: Buy (20-day > 50-day), Sell (20-day < 50-day)
|
162 |
+
|
163 |
+
An overall trading signal is calculated by combining all individual signals.
|
164 |
|
165 |
## Contributing
|
166 |
|
167 |
Contributions are welcome! Please feel free to submit a Pull Request.
|
168 |
+
|
169 |
+
## License
|
170 |
+
|
171 |
+
This project is licensed under the MIT License - see the LICENSE file for details.
|
172 |
+
|
173 |
+
## Practical Example: Creating a 6-Month 8% Yield Structured Product
|
174 |
+
|
175 |
+
### Scenario
|
176 |
+
A bank needs to create a structured product that offers an 8% yield over 6 months while maintaining profitability for the institution.
|
177 |
+
|
178 |
+
### Step-by-Step Implementation
|
179 |
+
|
180 |
+
1. **Initial Stock Screening**
|
181 |
+
- Use the application to analyze stocks with:
|
182 |
+
- High liquidity (for easy hedging)
|
183 |
+
- Stable volatility (for predictable risk)
|
184 |
+
- Strong technical indicators
|
185 |
+
- Positive long-term trends
|
186 |
+
- Recommended stocks: AAPL, MSFT, GOOGL (high liquidity, stable volatility)
|
187 |
+
|
188 |
+
2. **Product Structure Design**
|
189 |
+
- Use the 6-month prediction horizon
|
190 |
+
- Analyze historical volatility for barrier setting
|
191 |
+
- Set participation rate based on risk metrics
|
192 |
+
- Structure: Reverse Convertible with 8% coupon
|
193 |
+
|
194 |
+
3. **Risk Analysis**
|
195 |
+
- Use the application's risk metrics:
|
196 |
+
- Check maximum drawdown (should be < 15% for 6 months)
|
197 |
+
- Verify liquidity scores (should be > 80%)
|
198 |
+
- Analyze Sharpe ratio (should be > 1.5)
|
199 |
+
|
200 |
+
4. **Business Case Example**
|
201 |
+
|
202 |
+
**Product Parameters:**
|
203 |
+
- Notional Amount: $1,000,000
|
204 |
+
- Term: 6 months
|
205 |
+
- Coupon: 8% p.a. (4% for 6 months)
|
206 |
+
- Underlying: AAPL
|
207 |
+
- Barrier: 85% of initial price
|
208 |
+
- Participation: 100%
|
209 |
+
|
210 |
+
**Revenue Structure:**
|
211 |
+
- Client receives: 8% p.a. (4% for 6 months)
|
212 |
+
- Bank's hedging cost: ~5% p.a.
|
213 |
+
- Bank's profit margin: ~3% p.a.
|
214 |
+
- Total client payout: $40,000 (4% of $1M)
|
215 |
+
- Bank's profit: $15,000 (1.5% of $1M)
|
216 |
+
|
217 |
+
5. **Implementation Steps**
|
218 |
+
- Use the application's extended prediction horizon (180 days)
|
219 |
+
- Set technical indicators to monitor barrier risk
|
220 |
+
- Implement dynamic delta hedging based on predictions
|
221 |
+
- Monitor risk metrics daily using the application
|
222 |
+
|
223 |
+
6. **Risk Management**
|
224 |
+
- Use the application's volatility predictions for dynamic hedging
|
225 |
+
- Monitor technical indicators for early warning signals
|
226 |
+
- Set up automated alerts for barrier proximity
|
227 |
+
- Regular rebalancing based on prediction updates
|
228 |
+
|
229 |
+
### Key Success Factors
|
230 |
+
- Regular monitoring of prediction accuracy
|
231 |
+
- Dynamic adjustment of hedging strategy
|
232 |
+
- Clear communication of product risks to clients
|
233 |
+
- Proper documentation of all assumptions and methodologies
|
234 |
+
|
235 |
+
This example demonstrates how the application can be used to create profitable structured products while managing risk effectively. The bank can use this framework to create similar products with different underlying assets, terms, and yield targets.
|
app.py
CHANGED
@@ -225,21 +225,24 @@ def make_prediction(symbol: str, timeframe: str = "1d", prediction_days: int = 5
|
|
225 |
if strategy == "chronos":
|
226 |
try:
|
227 |
# Prepare data for Chronos
|
228 |
-
returns
|
229 |
-
|
|
|
|
|
|
|
230 |
|
231 |
# Ensure we have enough data points and pad if necessary
|
232 |
min_data_points = 64 # Minimum required by Chronos
|
233 |
-
if len(
|
234 |
# Pad the data with the last value
|
235 |
-
padding = np.full(min_data_points - len(
|
236 |
-
|
237 |
-
elif len(
|
238 |
# Take the most recent data points
|
239 |
-
|
240 |
|
241 |
# Reshape for Chronos (batch_size=1, sequence_length, features=1)
|
242 |
-
context = torch.tensor(
|
243 |
|
244 |
# Make prediction with GPU acceleration
|
245 |
pipe = load_pipeline()
|
@@ -270,8 +273,9 @@ def make_prediction(symbol: str, timeframe: str = "1d", prediction_days: int = 5
|
|
270 |
num_samples=100
|
271 |
).detach().cpu().numpy()
|
272 |
|
273 |
-
|
274 |
-
|
|
|
275 |
|
276 |
# If we had to limit the prediction length, extend the prediction
|
277 |
if actual_prediction_length < prediction_days:
|
|
|
225 |
if strategy == "chronos":
|
226 |
try:
|
227 |
# Prepare data for Chronos
|
228 |
+
# Use Close prices instead of returns for better prediction
|
229 |
+
prices = df['Close'].values
|
230 |
+
|
231 |
+
# Normalize the data using MinMaxScaler
|
232 |
+
normalized_prices = scaler.fit_transform(prices.reshape(-1, 1)).flatten()
|
233 |
|
234 |
# Ensure we have enough data points and pad if necessary
|
235 |
min_data_points = 64 # Minimum required by Chronos
|
236 |
+
if len(normalized_prices) < min_data_points:
|
237 |
# Pad the data with the last value
|
238 |
+
padding = np.full(min_data_points - len(normalized_prices), normalized_prices[-1])
|
239 |
+
normalized_prices = np.concatenate([padding, normalized_prices])
|
240 |
+
elif len(normalized_prices) > min_data_points:
|
241 |
# Take the most recent data points
|
242 |
+
normalized_prices = normalized_prices[-min_data_points:]
|
243 |
|
244 |
# Reshape for Chronos (batch_size=1, sequence_length, features=1)
|
245 |
+
context = torch.tensor(normalized_prices.reshape(1, -1, 1), dtype=torch.float32)
|
246 |
|
247 |
# Make prediction with GPU acceleration
|
248 |
pipe = load_pipeline()
|
|
|
273 |
num_samples=100
|
274 |
).detach().cpu().numpy()
|
275 |
|
276 |
+
# Denormalize predictions
|
277 |
+
mean_pred = scaler.inverse_transform(prediction.mean(axis=0).reshape(-1, 1)).flatten()
|
278 |
+
std_pred = prediction.std(axis=0) * (scaler.data_max_ - scaler.data_min_)
|
279 |
|
280 |
# If we had to limit the prediction length, extend the prediction
|
281 |
if actual_prediction_length < prediction_days:
|