File size: 11,845 Bytes
a9237fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import pandas as pd
from database import DatabaseManager
from sqlalchemy import text
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime, timedelta

def database_console():
    """Database console interface for viewing and managing stock data"""
    st.title("📊 Database Console - Stock Trading Data")
    st.markdown("### SQLite Database Management")
    
    # Show database file location
    st.info("Database file: stock_trading.db (persistent storage)")
    
    # Initialize database
    try:
        if 'console_db' not in st.session_state:
            from database import DatabaseManager
            st.session_state.console_db = DatabaseManager()
        db = st.session_state.console_db
        st.success("Database connection established")
        
        # Show database file size if it exists
        import os
        if os.path.exists('stock_trading.db'):
            size = os.path.getsize('stock_trading.db')
            st.metric("Database Size", f"{size / 1024:.1f} KB")
            
    except Exception as e:
        st.error(f"Database connection failed: {str(e)}")
        return
    
    # Sidebar navigation
    st.sidebar.header("Database Navigation")
    section = st.sidebar.selectbox(
        "Select Section:",
        ["Overview", "Stock Data", "Technical Indicators", "Trading Signals", "Model Metrics", "SQL Query"]
    )
    
    if section == "Overview":
        show_database_overview(db)
    elif section == "Stock Data":
        show_stock_data(db)
    elif section == "Technical Indicators":
        show_technical_indicators(db)
    elif section == "Trading Signals":
        show_trading_signals(db)
    elif section == "Model Metrics":
        show_model_metrics(db)
    elif section == "SQL Query":
        show_sql_interface(db)

def show_database_overview(db):
    """Show database overview and statistics"""
    st.header("Database Overview")
    
    col1, col2, col3, col4 = st.columns(4)
    
    try:
        # Get table counts
        stock_count = db.session.execute(text("SELECT COUNT(*) FROM stock_data")).scalar()
        indicator_count = db.session.execute(text("SELECT COUNT(*) FROM technical_indicators")).scalar()
        signal_count = db.session.execute(text("SELECT COUNT(*) FROM trading_signals")).scalar()
        model_count = db.session.execute(text("SELECT COUNT(*) FROM model_metrics")).scalar()
        
        with col1:
            st.metric("Stock Records", stock_count)
        with col2:
            st.metric("Technical Indicators", indicator_count)
        with col3:
            st.metric("Trading Signals", signal_count)
        with col4:
            st.metric("Model Records", model_count)
            
    except Exception as e:
        st.warning(f"Error getting counts: {str(e)}")
        # Initialize tables if they don't exist
        if st.button("Initialize Database Tables"):
            initialize_database_tables(db)
    
    # Recent activity
    st.subheader("Recent Activity")
    try:
        recent_signals = pd.read_sql("""
            SELECT symbol, signal, confidence, live_price, created_at 
            FROM trading_signals 
            ORDER BY created_at DESC 
            LIMIT 10
        """, db.engine)
        
        if not recent_signals.empty:
            st.dataframe(recent_signals)
        else:
            st.info("No recent trading signals found")
            
    except Exception as e:
        st.info("No trading signals table found yet")

def show_stock_data(db):
    """Show stock OHLCV data"""
    st.header("Stock Data (OHLCV)")
    
    # Stock selection
    symbol = st.selectbox(
        "Select Stock Symbol:",
        ["RELIANCE.NS", "TCS.NS", "INFY.NS", "HDFCBANK.NS", "ICICIBANK.NS"]
    )
    
    try:
        # Get stock data
        query = """
            SELECT * FROM stock_data 
            WHERE symbol = :symbol 
            ORDER BY date DESC 
            LIMIT 100
        """
        stock_data = pd.read_sql(query, db.engine, params={"symbol": symbol})
        
        if not stock_data.empty:
            st.dataframe(stock_data)
            
            # Create price chart
            fig = go.Figure()
            fig.add_trace(go.Candlestick(
                x=stock_data['date'],
                open=stock_data['open_price'],
                high=stock_data['high_price'],
                low=stock_data['low_price'],
                close=stock_data['close_price'],
                name=symbol
            ))
            fig.update_layout(title=f"{symbol} - Price Chart", xaxis_title="Date", yaxis_title="Price (₹)")
            st.plotly_chart(fig, use_container_width=True)
            
        else:
            st.info(f"No stock data found for {symbol}")
            if st.button(f"Load {symbol} Data"):
                load_sample_data(db, symbol)
                
    except Exception as e:
        st.error(f"Error loading stock data: {str(e)}")

def show_technical_indicators(db):
    """Show technical indicators data"""
    st.header("Technical Indicators")
    
    symbol = st.selectbox(
        "Select Stock:",
        ["RELIANCE.NS", "TCS.NS", "INFY.NS", "HDFCBANK.NS", "ICICIBANK.NS"],
        key="tech_symbol"
    )
    
    try:
        query = """
            SELECT * FROM technical_indicators 
            WHERE symbol = :symbol 
            ORDER BY date DESC 
            LIMIT 50
        """
        tech_data = pd.read_sql(query, db.engine, params={"symbol": symbol})
        
        if not tech_data.empty:
            st.dataframe(tech_data)
            
            # Create indicators chart
            col1, col2 = st.columns(2)
            
            with col1:
                if 'rsi' in tech_data.columns:
                    fig_rsi = px.line(tech_data, x='date', y='rsi', title='RSI')
                    st.plotly_chart(fig_rsi, use_container_width=True)
            
            with col2:
                if 'macd' in tech_data.columns:
                    fig_macd = px.line(tech_data, x='date', y='macd', title='MACD')
                    st.plotly_chart(fig_macd, use_container_width=True)
                    
        else:
            st.info(f"No technical indicators found for {symbol}")
            
    except Exception as e:
        st.error(f"Error loading technical indicators: {str(e)}")

def show_trading_signals(db):
    """Show trading signals"""
    st.header("Trading Signals")
    
    try:
        # Get all signals
        signals_data = pd.read_sql("""
            SELECT * FROM trading_signals 
            ORDER BY signal_date DESC 
            LIMIT 100
        """, db.engine)
        
        if not signals_data.empty:
            st.dataframe(signals_data)
            
            # Signal distribution
            col1, col2 = st.columns(2)
            
            with col1:
                signal_counts = signals_data['signal'].value_counts()
                fig_pie = px.pie(values=signal_counts.values, names=signal_counts.index, 
                               title="Signal Distribution")
                st.plotly_chart(fig_pie, use_container_width=True)
            
            with col2:
                fig_conf = px.histogram(signals_data, x='confidence', title="Confidence Distribution")
                st.plotly_chart(fig_conf, use_container_width=True)
                
        else:
            st.info("No trading signals found")
            
    except Exception as e:
        st.error(f"Error loading trading signals: {str(e)}")

def show_model_metrics(db):
    """Show model performance metrics"""
    st.header("Model Performance Metrics")
    
    try:
        metrics_data = pd.read_sql("""
            SELECT * FROM model_metrics 
            ORDER BY training_date DESC
        """, db.engine)
        
        if not metrics_data.empty:
            st.dataframe(metrics_data)
            
            # Performance charts
            col1, col2 = st.columns(2)
            
            with col1:
                fig_acc = px.bar(metrics_data, x='symbol', y='accuracy', 
                               title="Model Accuracy by Symbol")
                st.plotly_chart(fig_acc, use_container_width=True)
            
            with col2:
                fig_prec = px.bar(metrics_data, x='symbol', y='precision_score', 
                                title="Model Precision by Symbol")
                st.plotly_chart(fig_prec, use_container_width=True)
                
        else:
            st.info("No model metrics found")
            
    except Exception as e:
        st.error(f"Error loading model metrics: {str(e)}")

def show_sql_interface(db):
    """SQL query interface"""
    st.header("SQL Query Interface")
    
    # Predefined queries
    st.subheader("Quick Queries")
    col1, col2, col3 = st.columns(3)
    
    with col1:
        if st.button("Show All Tables"):
            try:
                tables = db.engine.execute(text("SELECT name FROM sqlite_master WHERE type='table'")).fetchall()
                st.write("Tables:", [table[0] for table in tables])
            except Exception as e:
                st.error(f"Error: {str(e)}")
    
    with col2:
        if st.button("Latest Signals"):
            try:
                result = pd.read_sql("SELECT * FROM trading_signals ORDER BY created_at DESC LIMIT 5", db.engine)
                st.dataframe(result)
            except Exception as e:
                st.error(f"Error: {str(e)}")
    
    with col3:
        if st.button("Stock Summary"):
            try:
                result = pd.read_sql("""
                    SELECT symbol, COUNT(*) as records, 
                           MIN(date) as first_date, MAX(date) as last_date 
                    FROM stock_data 
                    GROUP BY symbol
                """, db.engine)
                st.dataframe(result)
            except Exception as e:
                st.error(f"Error: {str(e)}")
    
    # Custom SQL query
    st.subheader("Custom SQL Query")
    sql_query = st.text_area(
        "Enter SQL Query:",
        value="SELECT * FROM trading_signals LIMIT 10;",
        height=100
    )
    
    if st.button("Execute Query"):
        try:
            if sql_query.strip():
                result = pd.read_sql(sql_query, db.engine)
                st.dataframe(result)
                st.success(f"Query executed successfully. {len(result)} rows returned.")
        except Exception as e:
            st.error(f"Query error: {str(e)}")

def initialize_database_tables(db):
    """Initialize database tables with sample data"""
    try:
        from database import Base
        Base.metadata.create_all(db.engine)
        st.success("Database tables initialized successfully")
        st.rerun()
    except Exception as e:
        st.error(f"Error initializing tables: {str(e)}")

def load_sample_data(db, symbol):
    """Load sample data for testing"""
    try:
        import yfinance as yf
        from technical_indicators import TechnicalIndicators
        
        # Download stock data
        ticker = yf.Ticker(symbol)
        data = ticker.history(period="1mo")
        
        if not data.empty:
            # Save stock data
            db.save_stock_data(symbol, data)
            
            # Calculate and save technical indicators
            tech = TechnicalIndicators()
            data_with_indicators = tech.calculate_all_indicators(data)
            db.save_technical_indicators(symbol, data_with_indicators)
            
            st.success(f"Sample data loaded for {symbol}")
            st.rerun()
        else:
            st.error(f"Could not fetch data for {symbol}")
            
    except Exception as e:
        st.error(f"Error loading sample data: {str(e)}")

if __name__ == "__main__":
    database_console()