Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| import pandas as pd | |
| from datetime import datetime | |
| import json | |
| from src.utils import render_header | |
| # ============ PAGE CONFIGURATION ============ | |
| st.set_page_config( | |
| page_title="Settings | NSE Optimizer", | |
| page_icon="βοΈ", | |
| layout="wide" | |
| ) | |
| # ============ MAIN APP ============ | |
| def main(): | |
| render_header() | |
| st.title("βοΈ Settings & Preferences") | |
| st.markdown("Configure your portfolio optimizer preferences and manage your data") | |
| st.markdown("---") | |
| # Initialize session state with ALL required keys (fallback if Main_Page didn't run) | |
| if 'user_preferences' not in st.session_state: | |
| st.session_state.user_preferences = { | |
| 'risk_free_rate': 0.0654, | |
| 'default_years': 2, | |
| 'default_simulations': 1000, | |
| 'brokerage_rate': 0.0003, | |
| 'confidence_level': 0.95, | |
| 'rebalance_threshold': 0.05 | |
| } | |
| # Ensure all keys exist (safe update for existing sessions) | |
| defaults = { | |
| 'risk_free_rate': 0.0654, | |
| 'default_years': 2, | |
| 'default_simulations': 1000, | |
| 'brokerage_rate': 0.0003, | |
| 'confidence_level': 0.95, | |
| 'rebalance_threshold': 0.05 | |
| } | |
| for key, value in defaults.items(): | |
| if key not in st.session_state.user_preferences: | |
| st.session_state.user_preferences[key] = value | |
| if 'portfolio_history' not in st.session_state: | |
| st.session_state.portfolio_history = [] | |
| prefs = st.session_state.user_preferences | |
| # ============ RISK PARAMETERS ============ | |
| st.markdown("## π Risk Parameters") | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| risk_free_rate = st.slider( | |
| "Risk-free Rate (%)", | |
| 0.0, 15.0, | |
| prefs['risk_free_rate'] * 100, | |
| 0.1, | |
| help="Used for Sharpe ratio calculation. Current India 10Y G-Sec: 6.54%" | |
| ) / 100 | |
| default_years = st.slider( | |
| "Default Historical Data (Years)", | |
| 1, 10, | |
| prefs['default_years'], | |
| 1, | |
| help="Default period for historical data analysis" | |
| ) | |
| with col2: | |
| default_simulations = st.slider( | |
| "Default Monte Carlo Simulations", | |
| 500, 5000, | |
| prefs['default_simulations'], | |
| 500, | |
| help="Number of scenarios to simulate (more = more accurate but slower)" | |
| ) | |
| confidence_level = st.slider( | |
| "VaR Confidence Level (%)", | |
| 90, 99, | |
| int(prefs['confidence_level'] * 100), | |
| 1, | |
| help="Confidence level for Value at Risk calculations" | |
| ) / 100 | |
| st.markdown("---") | |
| # ============ TRADING PARAMETERS ============ | |
| st.markdown("## π° Trading Parameters") | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| brokerage_rate = st.slider( | |
| "Brokerage Rate (%)", | |
| 0.0, 0.5, | |
| prefs['brokerage_rate'] * 100, | |
| 0.01, | |
| help="Transaction cost percentage. Typical range: 0.03% - 0.10%" | |
| ) / 100 | |
| st.info(f""" | |
| **Estimated Cost per βΉ1,00,000 trade:** | |
| - Brokerage: βΉ{(100000 * brokerage_rate):,.2f} | |
| - Plus: STT, GST, Stamp Duty (approx 0.1%) | |
| """) | |
| with col2: | |
| rebalance_threshold = st.slider( | |
| "Rebalancing Threshold (%)", | |
| 1.0, 20.0, | |
| prefs.get('rebalance_threshold', 0.05) * 100, | |
| 1.0, | |
| help="Trigger rebalancing when allocation drifts by this percentage" | |
| ) / 100 | |
| st.markdown("---") | |
| # ============ SAVE/RESET BUTTONS ============ | |
| col1, col2, col3 = st.columns([2, 1, 2]) | |
| with col1: | |
| if st.button("πΎ Save Preferences", type="primary", use_container_width=True): | |
| st.session_state.user_preferences = { | |
| 'risk_free_rate': risk_free_rate, | |
| 'default_years': default_years, | |
| 'default_simulations': default_simulations, | |
| 'brokerage_rate': brokerage_rate, | |
| 'confidence_level': confidence_level, | |
| 'rebalance_threshold': rebalance_threshold | |
| } | |
| st.success("β Preferences saved successfully!") | |
| st.balloons() | |
| with col3: | |
| if st.button("π Reset to Defaults", use_container_width=True): | |
| st.session_state.user_preferences = defaults.copy() | |
| st.success("β Reset to default settings!") | |
| st.rerun() | |
| st.markdown("---") | |
| # ============ CACHE MANAGEMENT ============ | |
| st.markdown("## β‘ Cache Management") | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| if st.button("π Clear Data Cache", use_container_width=True): | |
| st.cache_data.clear() | |
| st.success("β Market data cache cleared!") | |
| with col2: | |
| if st.button("ποΈ Clear All Caches", use_container_width=True): | |
| st.cache_data.clear() | |
| st.cache_resource.clear() | |
| st.success("β All application caches cleared!") | |
| st.markdown("---") | |
| # ============ DATA EXPORT ============ | |
| st.markdown("## π€ Data Export") | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| if st.button("π₯ Export Settings (JSON)", use_container_width=True): | |
| export_data = { | |
| 'preferences': st.session_state.user_preferences, | |
| 'export_date': datetime.now().isoformat(), | |
| 'version': '2.0' | |
| } | |
| json_str = json.dumps(export_data, indent=2) | |
| st.download_button( | |
| "Download Settings", | |
| json_str, | |
| f"nse_optimizer_settings_{datetime.now().strftime('%Y%m%d')}.json", | |
| "application/json", | |
| use_container_width=True | |
| ) | |
| with col2: | |
| if st.session_state.portfolio_history: | |
| if st.button("π₯ Export History (CSV)", use_container_width=True): | |
| history_data = [] | |
| for portfolio in st.session_state.portfolio_history: | |
| history_data.append({ | |
| 'Date': portfolio['date'].strftime('%Y-%m-%d %H:%M:%S'), | |
| 'Amount': portfolio['amount'], | |
| 'Stocks': portfolio['stocks'], | |
| 'Sharpe Ratio': portfolio['sharpe'] | |
| }) | |
| df = pd.DataFrame(history_data) | |
| csv = df.to_csv(index=False) | |
| st.download_button( | |
| "Download History", | |
| csv, | |
| f"portfolio_history_{datetime.now().strftime('%Y%m%d')}.csv", | |
| "text/csv", | |
| use_container_width=True | |
| ) | |
| else: | |
| st.info("No portfolio history to export") | |
| if __name__ == "__main__": | |
| main() |