-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
559 lines (452 loc) · 23.8 KB
/
Copy pathapp.py
File metadata and controls
559 lines (452 loc) · 23.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
"""
Main Streamlit Application for Investor Decision Support System
"""
import streamlit as st
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import plotly.graph_objects as go
import plotly.express as px
# Import custom modules
from data_fetcher import DataFetcher
from portfolio_analysis import PortfolioAnalyzer
from capm_analysis import CAPMAnalyzer
from forecasting import StockForecaster
from visualization import FinancialVisualizer
# Page configuration
st.set_page_config(
page_title="Investor Decision Support System",
page_icon="📈",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS
st.markdown("""
<style>
.main-header {
font-size: 3rem;
color: #1f77b4;
text-align: center;
margin-bottom: 2rem;
}
.kpi-card {
background-color: #f0f2f6;
padding: 1rem;
border-radius: 0.5rem;
margin: 0.5rem 0;
}
.metric-label {
font-size: 0.9rem;
color: #666;
margin-bottom: 0.25rem;
}
.metric-value {
font-size: 1.5rem;
font-weight: bold;
color: #1f77b4;
}
</style>
""", unsafe_allow_html=True)
# Initialize session state
if 'data_fetched' not in st.session_state:
st.session_state.data_fetched = False
if 'stock_data' not in st.session_state:
st.session_state.stock_data = {}
if 'market_data' not in st.session_state:
st.session_state.market_data = pd.DataFrame()
def main():
"""Main application function"""
# Header
st.markdown('<h1 class="main-header">📈 Investor Decision Support System</h1>', unsafe_allow_html=True)
st.markdown("---")
# Sidebar
with st.sidebar:
st.header("⚙️ Configuration")
# Theme selection
theme = st.selectbox("Choose Theme", ["Light", "Dark"], index=0)
# Risk-free rate
risk_free_rate = st.number_input(
"Risk-Free Rate (%)",
min_value=0.0,
max_value=10.0,
value=2.0,
step=0.1
) / 100
# Data period
data_period = st.selectbox(
"Data Period",
["1y", "2y", "5y", "10y"],
index=0
)
st.markdown("---")
# Initialize data fetcher
data_fetcher = DataFetcher()
# Main content area
tab1, tab2, tab3, tab4, tab5 = st.tabs(["📊 Data Input", "💼 Portfolio Analysis", "📈 CAPM Analysis", "🔮 Forecasting", "📋 Summary"])
with tab1:
st.header("📊 Stock Data Input")
col1, col2 = st.columns([2, 1])
with col1:
# Stock symbols input
st.subheader("Select Stocks")
# Predefined stock lists
stock_lists = {
"Technology": ["AAPL", "MSFT", "GOOGL", "AMZN", "META"],
"Finance": ["JPM", "BAC", "WFC", "GS", "MS"],
"Healthcare": ["JNJ", "PFE", "UNH", "ABT", "MRK"],
"Indian Stocks": ["RELIANCE.NS", "TCS.NS", "INFY.NS", "HDFCBANK.NS", "ITC.NS"],
"Custom": []
}
selected_list = st.selectbox("Choose Stock Category", list(stock_lists.keys()))
if selected_list == "Custom":
symbols_input = st.text_area(
"Enter Stock Symbols (one per line)",
value="AAPL\nMSFT\nGOOGL",
height=100
)
symbols = [s.strip().upper() for s in symbols_input.split('\n') if s.strip()]
else:
symbols = st.multiselect(
"Select Stocks",
options=stock_lists[selected_list],
default=stock_lists[selected_list][:3]
)
# Fetch data button
if st.button("🔄 Fetch Data", type="primary"):
if symbols:
with st.spinner("Fetching stock data..."):
# Validate symbols
valid_symbols = data_fetcher.validate_symbols(symbols)
if valid_symbols:
# Fetch stock data
stock_data = data_fetcher.get_stock_data(valid_symbols, data_period)
market_data = data_fetcher.get_market_data(data_period)
if stock_data and not market_data.empty:
st.session_state.stock_data = stock_data
st.session_state.market_data = market_data
st.session_state.data_fetched = True
st.success(f"✅ Successfully fetched data for {len(stock_data)} stocks!")
else:
st.error("❌ Failed to fetch data. Please check your internet connection and symbol validity.")
else:
st.error("❌ No valid symbols found. Please check your input.")
else:
st.warning("⚠️ Please select at least one stock symbol.")
with col2:
st.subheader("📋 Data Summary")
if st.session_state.data_fetched:
st.success("✅ Data Loaded")
for symbol, data in st.session_state.stock_data.items():
info = data_fetcher.get_stock_info(symbol)
with st.expander(f"📊 {symbol}"):
st.write(f"**Name:** {info.get('name', 'N/A')}")
st.write(f"**Sector:** {info.get('sector', 'N/A')}")
st.write(f"**Industry:** {info.get('industry', 'N/A')}")
st.write(f"**Data Points:** {len(data)}")
st.write(f"**Current Price:** ${data['Close'].iloc[-1]:.2f}")
# Price chart
fig = px.line(data, x=data.index, y='Close', title=f"{symbol} Price History")
st.plotly_chart(fig, use_container_width=True)
else:
st.info("👈 Fetch data to see summary")
with tab2:
st.header("💼 Portfolio Analysis")
if not st.session_state.data_fetched:
st.warning("⚠️ Please fetch stock data first in the Data Input tab.")
else:
# Calculate returns
returns_data = data_fetcher.calculate_returns(st.session_state.stock_data)
if returns_data:
# Initialize portfolio analyzer
portfolio_analyzer = PortfolioAnalyzer(returns_data, risk_free_rate)
visualizer = FinancialVisualizer()
col1, col2 = st.columns([1, 2])
with col1:
st.subheader("🎯 Portfolio Configuration")
# Portfolio weights input
weights = {}
total_weight = 0
for symbol in returns_data.keys():
weight = st.slider(
f"Weight for {symbol}",
min_value=0.0,
max_value=1.0,
value=1.0/len(returns_data.keys()),
step=0.01,
format="%.2f"
)
weights[symbol] = weight
total_weight += weight
# Normalize weights
if total_weight > 0:
weights = {k: v/total_weight for k, v in weights.items()}
st.write(f"**Total Weight:** {total_weight:.2f}")
# Portfolio optimization
st.subheader("🚀 Optimization")
optimize_type = st.radio(
"Optimization Type",
["Maximize Sharpe Ratio", "Target Return"]
)
if optimize_type == "Target Return":
target_return = st.number_input(
"Target Annual Return (%)",
min_value=0.0,
max_value=50.0,
value=10.0,
step=0.5
) / 100
if st.button("🎯 Optimize for Target Return"):
with st.spinner("Optimizing portfolio..."):
result = portfolio_analyzer.optimize_portfolio(target_return)
if result['success']:
weights = result['weights']
st.success("✅ Portfolio optimized!")
else:
st.error(f"❌ Optimization failed: {result['message']}")
else:
if st.button("🎯 Optimize for Max Sharpe Ratio"):
with st.spinner("Optimizing portfolio..."):
result = portfolio_analyzer.optimize_portfolio()
if result['success']:
weights = result['weights']
st.success("✅ Portfolio optimized!")
else:
st.error(f"❌ Optimization failed: {result['message']}")
with col2:
st.subheader("📊 Portfolio Metrics")
# Calculate portfolio metrics
try:
portfolio_metrics = portfolio_analyzer.calculate_portfolio_metrics(list(weights.values()))
# Display KPI cards
col_a, col_b, col_c = st.columns(3)
with col_a:
st.metric(
"Expected Return",
f"{portfolio_metrics['expected_return']:.2%}",
delta=None
)
with col_b:
st.metric(
"Volatility",
f"{portfolio_metrics['volatility']:.2%}",
delta=None
)
with col_c:
st.metric(
"Sharpe Ratio",
f"{portfolio_metrics['sharpe_ratio']:.3f}",
delta=None
)
# Portfolio weights pie chart
weights_df = pd.DataFrame(list(weights.items()), columns=['Stock', 'Weight'])
fig = px.pie(weights_df, values='Weight', names='Stock', title='Portfolio Allocation')
st.plotly_chart(fig, use_container_width=True)
except Exception as e:
st.error(f"Error calculating portfolio metrics: {str(e)}")
# Efficient Frontier
st.subheader("📈 Efficient Frontier")
if st.button("🔄 Generate Efficient Frontier"):
with st.spinner("Generating efficient frontier..."):
efficient_frontier = portfolio_analyzer.generate_efficient_frontier(1000)
# Get optimal portfolio
optimal_result = portfolio_analyzer.optimize_portfolio()
# Plot efficient frontier
fig = visualizer.plot_efficient_frontier(
efficient_frontier,
optimal_result if optimal_result['success'] else None
)
st.plotly_chart(fig, use_container_width=True)
# Individual stock metrics
st.subheader("📋 Individual Stock Metrics")
individual_metrics = portfolio_analyzer.calculate_individual_metrics()
st.dataframe(individual_metrics, use_container_width=True)
# Correlation matrix
st.subheader("🔗 Correlation Matrix")
correlation_matrix = portfolio_analyzer.get_correlation_matrix()
fig = visualizer.plot_correlation_heatmap(correlation_matrix)
st.plotly_chart(fig, use_container_width=True)
with tab3:
st.header("📈 CAPM Analysis")
if not st.session_state.data_fetched:
st.warning("⚠️ Please fetch stock data first in the Data Input tab.")
else:
# Calculate returns
stock_returns = data_fetcher.calculate_returns(st.session_state.stock_data)
market_returns = data_fetcher.calculate_returns({"Market": st.session_state.market_data})["Market"]
if stock_returns and not market_returns.empty:
# Initialize CAPM analyzer
capm_analyzer = CAPMAnalyzer(stock_returns, market_returns, risk_free_rate)
visualizer = FinancialVisualizer()
# Perform CAPM analysis
with st.spinner("Performing CAPM analysis..."):
capm_results = capm_analyzer.analyze_all_stocks()
sml_data = capm_analyzer.calculate_security_market_line()
if not capm_results.empty:
# Display CAPM results
st.subheader("📊 CAPM Results")
st.dataframe(capm_results, use_container_width=True)
# Security Market Line plot
st.subheader("📈 Security Market Line")
fig = visualizer.plot_capm_analysis(capm_results, sml_data)
st.plotly_chart(fig, use_container_width=True)
# Risk metrics
st.subheader("⚠️ Market Risk Metrics")
risk_metrics = capm_analyzer.get_risk_metrics()
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Market Return", f"{risk_metrics['market_return']:.2%}")
with col2:
st.metric("Market Volatility", f"{risk_metrics['market_volatility']:.2%}")
with col3:
st.metric("Market Sharpe Ratio", f"{risk_metrics['market_sharpe_ratio']:.3f}")
with col4:
st.metric("Market Premium", f"{risk_metrics['market_premium']:.2%}")
else:
st.error("❌ Failed to perform CAPM analysis. Please check your data.")
else:
st.error("❌ Insufficient data for CAPM analysis.")
with tab4:
st.header("🔮 Stock Price Forecasting")
if not st.session_state.data_fetched:
st.warning("⚠️ Please fetch stock data first in the Data Input tab.")
else:
# Initialize forecaster
forecaster = StockForecaster(st.session_state.stock_data)
visualizer = FinancialVisualizer()
col1, col2 = st.columns([1, 2])
with col1:
st.subheader("🎯 Forecast Configuration")
# Select stock for forecasting
selected_stock = st.selectbox(
"Select Stock to Forecast",
options=list(st.session_state.stock_data.keys())
)
# Forecast parameters
forecast_periods = st.number_input(
"Forecast Periods (Days)",
min_value=5,
max_value=100,
value=30,
step=5
)
confidence_level = st.slider(
"Confidence Level",
min_value=0.8,
max_value=0.99,
value=0.95,
step=0.01
)
# ARIMA parameters (optional)
st.subheader("🔧 ARIMA Parameters (Auto if not specified)")
use_custom_params = st.checkbox("Use Custom ARIMA Parameters")
if use_custom_params:
col_p, col_d, col_q = st.columns(3)
with col_p:
p = st.number_input("p (AR)", min_value=0, max_value=5, value=1)
with col_d:
d = st.number_input("d (Differencing)", min_value=0, max_value=3, value=1)
with col_q:
q = st.number_input("q (MA)", min_value=0, max_value=5, value=1)
else:
p, d, q = None, None, None
# Generate forecast button
if st.button("🔮 Generate Forecast", type="primary"):
with st.spinner("Generating forecast..."):
# Fit model
if use_custom_params:
fit_result = forecaster.fit_arima_model(selected_stock, p, d, q)
else:
fit_result = forecaster.fit_arima_model(selected_stock)
if 'error' not in fit_result:
# Generate forecast
forecast_result = forecaster.forecast_prices(
selected_stock,
forecast_periods,
confidence_level
)
if 'error' not in forecast_result:
st.success("✅ Forecast generated successfully!")
# Display model diagnostics
st.subheader("🔍 Model Diagnostics")
st.write(f"**ARIMA Parameters:** {fit_result['parameters']}")
st.write(f"**AIC:** {fit_result['aic']:.2f}")
st.write(f"**BIC:** {fit_result['bic']:.2f}")
# Display forecast summary
forecast_summary = forecaster.get_forecast_summary(selected_stock)
st.subheader("📊 Forecast Summary")
st.write(f"**Current Price:** ${forecast_summary['current_price']:.2f}")
st.write(f"**Final Forecast:** ${forecast_summary['final_forecast']:.2f}")
st.write(f"**Price Change:** ${forecast_summary['price_change']:.2f}")
st.write(f"**Price Change %:** {forecast_summary['price_change_pct']:.2f}%")
# Store forecast for visualization
st.session_state.forecast_data = forecast_result['forecast_data']
st.session_state.selected_stock = selected_stock
else:
st.error(f"❌ Forecast failed: {forecast_result['error']}")
else:
st.error(f"❌ Model fitting failed: {fit_result['error']}")
with col2:
st.subheader("📈 Forecast Visualization")
if 'forecast_data' in st.session_state:
# Plot forecast
historical_prices = st.session_state.stock_data[st.session_state.selected_stock]['Close']
forecast_data = st.session_state.forecast_data
fig = visualizer.plot_stock_forecasts(
st.session_state.selected_stock,
historical_prices,
forecast_data
)
st.plotly_chart(fig, use_container_width=True)
else:
st.info("👈 Generate a forecast to see the visualization")
with tab5:
st.header("📋 Summary Report")
if not st.session_state.data_fetched:
st.warning("⚠️ Please fetch stock data first in the Data Input tab.")
else:
# Generate comprehensive summary
st.subheader("📊 Investment Summary")
# Data summary
st.write(f"**Analysis Date:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
st.write(f"**Number of Stocks Analyzed:** {len(st.session_state.stock_data)}")
st.write(f"**Risk-Free Rate:** {risk_free_rate:.2%}")
# Portfolio summary (if available)
if 'portfolio_metrics' in locals():
st.subheader("💼 Portfolio Summary")
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Expected Return", f"{portfolio_metrics['expected_return']:.2%}")
with col2:
st.metric("Volatility", f"{portfolio_metrics['volatility']:.2%}")
with col3:
st.metric("Sharpe Ratio", f"{portfolio_metrics['sharpe_ratio']:.3f}")
# Export functionality
st.subheader("📤 Export Options")
col1, col2 = st.columns(2)
with col1:
if st.button("📄 Generate PDF Report"):
st.info("PDF export functionality would be implemented here")
with col2:
if st.button("📊 Export Data to CSV"):
# Create summary DataFrame
summary_data = []
for symbol, data in st.session_state.stock_data.items():
current_price = data['Close'].iloc[-1]
price_change = (current_price - data['Close'].iloc[-2]) / data['Close'].iloc[-2]
summary_data.append({
'Symbol': symbol,
'Current Price': current_price,
'Price Change %': price_change * 100,
'Data Points': len(data)
})
summary_df = pd.DataFrame(summary_data)
# Download CSV
csv = summary_df.to_csv(index=False)
st.download_button(
label="📥 Download CSV",
data=csv,
file_name=f"investment_summary_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
mime="text/csv"
)
if __name__ == "__main__":
main()