Spaces:
Paused
Paused
Tonic commited on
Commit ·
1702ce4
1
Parent(s): 8828171
adds relevant indicators from structured product creation
Browse files
README.md
CHANGED
|
@@ -13,7 +13,7 @@ short_description: Use Amazon Chronos To Predict Stock Prices
|
|
| 13 |
|
| 14 |
# Stock Analysis and Prediction Demo
|
| 15 |
|
| 16 |
-
A comprehensive stock analysis and prediction tool built with Gradio, featuring multiple prediction strategies and technical analysis indicators.
|
| 17 |
|
| 18 |
## Features
|
| 19 |
|
|
@@ -25,7 +25,7 @@ A comprehensive stock analysis and prediction tool built with Gradio, featuring
|
|
| 25 |
- RSI (Relative Strength Index)
|
| 26 |
- MACD (Moving Average Convergence Divergence)
|
| 27 |
- Bollinger Bands
|
| 28 |
-
- Simple Moving Averages (20 and
|
| 29 |
|
| 30 |
- **Trading Signals**:
|
| 31 |
- Buy/Sell recommendations based on multiple indicators
|
|
@@ -38,6 +38,41 @@ A comprehensive stock analysis and prediction tool built with Gradio, featuring
|
|
| 38 |
- Volume analysis
|
| 39 |
- Historical price trends
|
| 40 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
## Installation
|
| 42 |
|
| 43 |
1. Clone the repository:
|
|
@@ -68,10 +103,37 @@ python app.py
|
|
| 68 |
|
| 69 |
3. Enter a stock symbol (e.g., AAPL, GOOGL, MSFT) and select your desired parameters:
|
| 70 |
- Timeframe (1d, 1h, 15m)
|
| 71 |
-
- Number of days to predict
|
|
|
|
| 72 |
- Prediction strategy (Chronos or Technical)
|
| 73 |
|
| 74 |
-
4. Click "Analyze Stock" to get
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
## Prediction Strategies
|
| 77 |
|
|
|
|
| 13 |
|
| 14 |
# Stock Analysis and Prediction Demo
|
| 15 |
|
| 16 |
+
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.
|
| 17 |
|
| 18 |
## Features
|
| 19 |
|
|
|
|
| 25 |
- RSI (Relative Strength Index)
|
| 26 |
- MACD (Moving Average Convergence Divergence)
|
| 27 |
- Bollinger Bands
|
| 28 |
+
- Simple Moving Averages (20, 50, and 200-day)
|
| 29 |
|
| 30 |
- **Trading Signals**:
|
| 31 |
- Buy/Sell recommendations based on multiple indicators
|
|
|
|
| 38 |
- Volume analysis
|
| 39 |
- Historical price trends
|
| 40 |
|
| 41 |
+
- **Structured Product Analysis**:
|
| 42 |
+
- Extended prediction horizons (up to 1 year)
|
| 43 |
+
- Historical analysis up to 10 years
|
| 44 |
+
- Comprehensive risk metrics
|
| 45 |
+
- Sector and industry analysis
|
| 46 |
+
- Liquidity assessment
|
| 47 |
+
|
| 48 |
+
## Structured Product Features
|
| 49 |
+
|
| 50 |
+
### Extended Time Horizons
|
| 51 |
+
- Prediction window up to 365 days
|
| 52 |
+
- Historical data analysis up to 10 years
|
| 53 |
+
- Long-term trend analysis
|
| 54 |
+
- Extended technical indicators
|
| 55 |
+
|
| 56 |
+
### Risk Analysis
|
| 57 |
+
- Annualized volatility
|
| 58 |
+
- Maximum drawdown analysis
|
| 59 |
+
- Current drawdown tracking
|
| 60 |
+
- Sharpe and Sortino ratios
|
| 61 |
+
- Risk-adjusted return metrics
|
| 62 |
+
|
| 63 |
+
### Product Metrics
|
| 64 |
+
- Market capitalization
|
| 65 |
+
- Sector and industry classification
|
| 66 |
+
- Dividend yield analysis
|
| 67 |
+
- Volume metrics
|
| 68 |
+
- Liquidity scoring
|
| 69 |
+
|
| 70 |
+
### Sector Analysis
|
| 71 |
+
- Market cap ranking (Large/Mid/Small)
|
| 72 |
+
- Sector exposure
|
| 73 |
+
- Industry classification
|
| 74 |
+
- Liquidity assessment
|
| 75 |
+
|
| 76 |
## Installation
|
| 77 |
|
| 78 |
1. Clone the repository:
|
|
|
|
| 103 |
|
| 104 |
3. Enter a stock symbol (e.g., AAPL, GOOGL, MSFT) and select your desired parameters:
|
| 105 |
- Timeframe (1d, 1h, 15m)
|
| 106 |
+
- Number of days to predict (up to 365 days)
|
| 107 |
+
- Historical lookback period (up to 10 years)
|
| 108 |
- Prediction strategy (Chronos or Technical)
|
| 109 |
|
| 110 |
+
4. Click "Analyze Stock" to get:
|
| 111 |
+
- Price predictions and trading signals
|
| 112 |
+
- Structured product metrics
|
| 113 |
+
- Risk analysis
|
| 114 |
+
- Sector analysis
|
| 115 |
+
|
| 116 |
+
## Using for Structured Products
|
| 117 |
+
|
| 118 |
+
### Initial Screening
|
| 119 |
+
1. Use extended lookback period (up to 10 years) for long-term performance analysis
|
| 120 |
+
2. Look for stocks with stable volatility and good risk-adjusted returns
|
| 121 |
+
3. Check liquidity scores for trading feasibility
|
| 122 |
+
|
| 123 |
+
### Risk Assessment
|
| 124 |
+
1. Review risk metrics to match client risk profile
|
| 125 |
+
2. Analyze maximum drawdowns for worst-case scenarios
|
| 126 |
+
3. Compare risk-adjusted returns using Sharpe and Sortino ratios
|
| 127 |
+
|
| 128 |
+
### Product Structuring
|
| 129 |
+
1. Use prediction horizon (up to 1 year) for product maturity design
|
| 130 |
+
2. Consider dividend yields for income-generating products
|
| 131 |
+
3. Use sector analysis for proper diversification
|
| 132 |
+
|
| 133 |
+
### Portfolio Construction
|
| 134 |
+
1. Analyze multiple stocks for diversified bundles
|
| 135 |
+
2. Use sector metrics to avoid overexposure
|
| 136 |
+
3. Consider market cap rankings for appropriate sizing
|
| 137 |
|
| 138 |
## Prediction Strategies
|
| 139 |
|
app.py
CHANGED
|
@@ -60,9 +60,17 @@ def get_historical_data(symbol: str, timeframe: str = "1d", lookback_days: int =
|
|
| 60 |
ticker = yf.Ticker(symbol)
|
| 61 |
df = ticker.history(start=start_date, end=end_date, interval=interval)
|
| 62 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
# Calculate technical indicators
|
| 64 |
df['SMA_20'] = df['Close'].rolling(window=20).mean()
|
| 65 |
df['SMA_50'] = df['Close'].rolling(window=50).mean()
|
|
|
|
| 66 |
df['RSI'] = calculate_rsi(df['Close'])
|
| 67 |
df['MACD'], df['MACD_Signal'] = calculate_macd(df['Close'])
|
| 68 |
df['BB_Upper'], df['BB_Middle'], df['BB_Lower'] = calculate_bollinger_bands(df['Close'])
|
|
@@ -70,6 +78,16 @@ def get_historical_data(symbol: str, timeframe: str = "1d", lookback_days: int =
|
|
| 70 |
# Calculate returns and volatility
|
| 71 |
df['Returns'] = df['Close'].pct_change()
|
| 72 |
df['Volatility'] = df['Returns'].rolling(window=20).std()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
# Drop NaN values
|
| 75 |
df = df.dropna()
|
|
@@ -265,9 +283,9 @@ def calculate_trading_signals(df: pd.DataFrame) -> Dict:
|
|
| 265 |
|
| 266 |
def create_interface():
|
| 267 |
"""Create the Gradio interface"""
|
| 268 |
-
with gr.Blocks(title="
|
| 269 |
-
gr.Markdown("#
|
| 270 |
-
gr.Markdown("
|
| 271 |
|
| 272 |
with gr.Row():
|
| 273 |
with gr.Column():
|
|
@@ -279,11 +297,18 @@ def create_interface():
|
|
| 279 |
)
|
| 280 |
prediction_days = gr.Slider(
|
| 281 |
minimum=1,
|
| 282 |
-
maximum=
|
| 283 |
-
value=
|
| 284 |
step=1,
|
| 285 |
label="Days to Predict"
|
| 286 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 287 |
strategy = gr.Dropdown(
|
| 288 |
choices=["chronos", "technical"],
|
| 289 |
label="Prediction Strategy",
|
|
@@ -295,10 +320,56 @@ def create_interface():
|
|
| 295 |
plot = gr.Plot(label="Analysis and Prediction")
|
| 296 |
signals = gr.JSON(label="Trading Signals")
|
| 297 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
predict_btn.click(
|
| 299 |
-
fn=
|
| 300 |
-
inputs=[symbol, timeframe, prediction_days, strategy],
|
| 301 |
-
outputs=[signals, plot]
|
| 302 |
)
|
| 303 |
|
| 304 |
return demo
|
|
|
|
| 60 |
ticker = yf.Ticker(symbol)
|
| 61 |
df = ticker.history(start=start_date, end=end_date, interval=interval)
|
| 62 |
|
| 63 |
+
# Get additional info for structured products
|
| 64 |
+
info = ticker.info
|
| 65 |
+
df['Market_Cap'] = info.get('marketCap', None)
|
| 66 |
+
df['Sector'] = info.get('sector', None)
|
| 67 |
+
df['Industry'] = info.get('industry', None)
|
| 68 |
+
df['Dividend_Yield'] = info.get('dividendYield', None)
|
| 69 |
+
|
| 70 |
# Calculate technical indicators
|
| 71 |
df['SMA_20'] = df['Close'].rolling(window=20).mean()
|
| 72 |
df['SMA_50'] = df['Close'].rolling(window=50).mean()
|
| 73 |
+
df['SMA_200'] = df['Close'].rolling(window=200).mean()
|
| 74 |
df['RSI'] = calculate_rsi(df['Close'])
|
| 75 |
df['MACD'], df['MACD_Signal'] = calculate_macd(df['Close'])
|
| 76 |
df['BB_Upper'], df['BB_Middle'], df['BB_Lower'] = calculate_bollinger_bands(df['Close'])
|
|
|
|
| 78 |
# Calculate returns and volatility
|
| 79 |
df['Returns'] = df['Close'].pct_change()
|
| 80 |
df['Volatility'] = df['Returns'].rolling(window=20).std()
|
| 81 |
+
df['Annualized_Vol'] = df['Volatility'] * np.sqrt(252) # Annualized volatility
|
| 82 |
+
|
| 83 |
+
# Calculate drawdown metrics
|
| 84 |
+
df['Rolling_Max'] = df['Close'].rolling(window=252, min_periods=1).max()
|
| 85 |
+
df['Drawdown'] = (df['Close'] - df['Rolling_Max']) / df['Rolling_Max']
|
| 86 |
+
df['Max_Drawdown'] = df['Drawdown'].rolling(window=252, min_periods=1).min()
|
| 87 |
+
|
| 88 |
+
# Calculate liquidity metrics
|
| 89 |
+
df['Avg_Daily_Volume'] = df['Volume'].rolling(window=20).mean()
|
| 90 |
+
df['Volume_Volatility'] = df['Volume'].rolling(window=20).std()
|
| 91 |
|
| 92 |
# Drop NaN values
|
| 93 |
df = df.dropna()
|
|
|
|
| 283 |
|
| 284 |
def create_interface():
|
| 285 |
"""Create the Gradio interface"""
|
| 286 |
+
with gr.Blocks(title="Structured Product Analysis") as demo:
|
| 287 |
+
gr.Markdown("# Structured Product Analysis")
|
| 288 |
+
gr.Markdown("Analyze stocks for inclusion in structured financial products with extended time horizons.")
|
| 289 |
|
| 290 |
with gr.Row():
|
| 291 |
with gr.Column():
|
|
|
|
| 297 |
)
|
| 298 |
prediction_days = gr.Slider(
|
| 299 |
minimum=1,
|
| 300 |
+
maximum=365, # Extended to 1 year
|
| 301 |
+
value=30,
|
| 302 |
step=1,
|
| 303 |
label="Days to Predict"
|
| 304 |
)
|
| 305 |
+
lookback_days = gr.Slider(
|
| 306 |
+
minimum=365,
|
| 307 |
+
maximum=3650, # 10 years of history
|
| 308 |
+
value=365,
|
| 309 |
+
step=30,
|
| 310 |
+
label="Historical Lookback (Days)"
|
| 311 |
+
)
|
| 312 |
strategy = gr.Dropdown(
|
| 313 |
choices=["chronos", "technical"],
|
| 314 |
label="Prediction Strategy",
|
|
|
|
| 320 |
plot = gr.Plot(label="Analysis and Prediction")
|
| 321 |
signals = gr.JSON(label="Trading Signals")
|
| 322 |
|
| 323 |
+
with gr.Row():
|
| 324 |
+
with gr.Column():
|
| 325 |
+
gr.Markdown("### Structured Product Metrics")
|
| 326 |
+
metrics = gr.JSON(label="Product Metrics")
|
| 327 |
+
|
| 328 |
+
gr.Markdown("### Risk Analysis")
|
| 329 |
+
risk_metrics = gr.JSON(label="Risk Metrics")
|
| 330 |
+
|
| 331 |
+
gr.Markdown("### Sector Analysis")
|
| 332 |
+
sector_metrics = gr.JSON(label="Sector Metrics")
|
| 333 |
+
|
| 334 |
+
def analyze_stock(symbol, timeframe, prediction_days, lookback_days, strategy):
|
| 335 |
+
signals, fig = make_prediction(symbol, timeframe, prediction_days, strategy)
|
| 336 |
+
|
| 337 |
+
# Get historical data for additional metrics
|
| 338 |
+
df = get_historical_data(symbol, timeframe, lookback_days)
|
| 339 |
+
|
| 340 |
+
# Calculate structured product metrics
|
| 341 |
+
product_metrics = {
|
| 342 |
+
"Market_Cap": df['Market_Cap'].iloc[-1],
|
| 343 |
+
"Sector": df['Sector'].iloc[-1],
|
| 344 |
+
"Industry": df['Industry'].iloc[-1],
|
| 345 |
+
"Dividend_Yield": df['Dividend_Yield'].iloc[-1],
|
| 346 |
+
"Avg_Daily_Volume": df['Avg_Daily_Volume'].iloc[-1],
|
| 347 |
+
"Volume_Volatility": df['Volume_Volatility'].iloc[-1]
|
| 348 |
+
}
|
| 349 |
+
|
| 350 |
+
# Calculate risk metrics
|
| 351 |
+
risk_metrics = {
|
| 352 |
+
"Annualized_Volatility": df['Annualized_Vol'].iloc[-1],
|
| 353 |
+
"Max_Drawdown": df['Max_Drawdown'].iloc[-1],
|
| 354 |
+
"Current_Drawdown": df['Drawdown'].iloc[-1],
|
| 355 |
+
"Sharpe_Ratio": (df['Returns'].mean() * 252) / (df['Returns'].std() * np.sqrt(252)),
|
| 356 |
+
"Sortino_Ratio": (df['Returns'].mean() * 252) / (df['Returns'][df['Returns'] < 0].std() * np.sqrt(252))
|
| 357 |
+
}
|
| 358 |
+
|
| 359 |
+
# Calculate sector metrics
|
| 360 |
+
sector_metrics = {
|
| 361 |
+
"Sector": df['Sector'].iloc[-1],
|
| 362 |
+
"Industry": df['Industry'].iloc[-1],
|
| 363 |
+
"Market_Cap_Rank": "Large" if df['Market_Cap'].iloc[-1] > 1e10 else "Mid" if df['Market_Cap'].iloc[-1] > 1e9 else "Small",
|
| 364 |
+
"Liquidity_Score": "High" if df['Avg_Daily_Volume'].iloc[-1] > 1e6 else "Medium" if df['Avg_Daily_Volume'].iloc[-1] > 1e5 else "Low"
|
| 365 |
+
}
|
| 366 |
+
|
| 367 |
+
return signals, fig, product_metrics, risk_metrics, sector_metrics
|
| 368 |
+
|
| 369 |
predict_btn.click(
|
| 370 |
+
fn=analyze_stock,
|
| 371 |
+
inputs=[symbol, timeframe, prediction_days, lookback_days, strategy],
|
| 372 |
+
outputs=[signals, plot, metrics, risk_metrics, sector_metrics]
|
| 373 |
)
|
| 374 |
|
| 375 |
return demo
|