Spaces:
Sleeping

File size: 5,468 Bytes
e7cf9be
 
 
 
 
 
 
 
 
d624319
 
e7cf9be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2178ce4
 
e7cf9be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2178ce4
e7cf9be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Main dashboard layout and coordination functions.
"""
import streamlit as st
import sys
from pathlib import Path
import logging
from typing import Dict, List, Optional

# Add project root to path for imports
sys.path.append(str(Path(__file__).parent.parent.parent))

from .charts import create_line_chart, create_candlestick_chart, create_comparison_chart, create_volume_chart
from .widgets import create_date_range_selector, create_index_selector, display_index_info, create_chart_type_selector
from .educational import EducationalInsights

logger = logging.getLogger(__name__)


def setup_page_config():
    """Configure Streamlit page settings."""
    st.set_page_config(
        page_title="MarketWise - Educational Market Analysis",
        page_icon="🏦",
        layout="wide",
        initial_sidebar_state="expanded"
    )


def create_sidebar():
    """Build navigation sidebar with app information."""
    with st.sidebar:
        st.title("🏦 MarketWise")
        st.markdown("*Educational Market Analysis Platform*")
        
        st.markdown("---")
        
        st.markdown("""
        **Navigation:**
        - πŸ“Š **Market Explorer**: Analyze individual indices
        - πŸ“ˆ **Index Comparison**: Compare multiple markets
        - πŸŽ“ **Educational Insights**: Learn about investing
        """)
        
        st.markdown("---")
        
        st.markdown("""
        **About MarketWise:**
        
        MarketWise helps ordinary investors understand global market trends through 
        clear visualizations and educational content.
        
        **Data Coverage:**
        - 11 global market indices
        - 25+ years of historical data (2000-2025)
        - 65,000+ data points
        """)
        
        st.markdown("---")
        
        st.info("""
        πŸ’‘ **Tip**: Use the preset date range buttons for quick analysis, 
        or select 'Custom' for specific periods.
        """)


def load_data(symbols: List[str], start_date, end_date):
    """Data loading function.
    
    Args:
        symbols: List of symbols to load
        start_date: Start date for data
        end_date: End date for data
        
    Returns:
        Dictionary mapping symbols to DataFrames
    """
    try:
        from src.data.storage import MarketDataStorage
        
        storage = MarketDataStorage()
        
        if len(symbols) == 1:
            data = storage.get_historical_data(symbols[0], start_date, end_date)
            return {symbols[0]: data}
        else:
            return storage.get_multiple_symbols_data(symbols, start_date, end_date)
            
    except Exception as e:
        logger.error(f"Error loading data: {e}")
        st.error(f"Error loading data: {e}")
        return {}


def load_available_symbols():
    """Load available symbols.
    
    Returns:
        List of available symbols
    """
    try:
        from src.data.storage import MarketDataStorage
        
        storage = MarketDataStorage()
        return storage.get_available_symbols()
        
    except Exception as e:
        logger.error(f"Error loading symbols: {e}")
        st.error(f"Error loading available symbols: {e}")
        return []


@st.cache_data
def load_indices_config():
    """Load indices configuration with caching.
    
    Returns:
        Indices configuration dictionary
    """
    try:
        from src.utils.config import Config
        
        config = Config()
        return config.get_indices()
        
    except Exception as e:
        logger.error(f"Error loading config: {e}")
        st.error(f"Error loading configuration: {e}")
        return {'indices': {}}


def display_data_summary():
    """Display summary of available data."""
    try:
        from src.data.storage import MarketDataStorage
        
        storage = MarketDataStorage()
        summary = storage.get_data_summary()
        
        col1, col2, col3 = st.columns(3)
        
        with col1:
            st.metric("Total Records", f"{summary['total_records']:,}")
        
        with col2:
            st.metric("Market Indices", summary['unique_symbols'])
        
        with col3:
            if summary['earliest_date'] and summary['latest_date']:
                years = summary['latest_date'].year - summary['earliest_date'].year
                st.metric("Years of Data", f"{years}+")
        
        if summary['earliest_date'] and summary['latest_date']:
            st.info(
                f"πŸ“… Data Range: {summary['earliest_date'].strftime('%Y-%m-%d')} "
                f"to {summary['latest_date'].strftime('%Y-%m-%d')}"
            )
            
    except Exception as e:
        logger.error(f"Error displaying data summary: {e}")
        st.error("Unable to load data summary")


def check_dependencies():
    """Check if all required dependencies are available."""
    missing_deps = []
    
    try:
        import plotly
    except ImportError:
        missing_deps.append("plotly")
    
    try:
        import pandas
    except ImportError:
        missing_deps.append("pandas")
    
    try:
        from src.data.storage import MarketDataStorage
    except ImportError:
        missing_deps.append("MarketDataStorage (data layer)")
    
    if missing_deps:
        st.error(f"Missing dependencies: {', '.join(missing_deps)}")
        st.info("Please install requirements: `pip install -r requirements.txt`")
        return False
    
    return True