Spaces:
Running
Running
File size: 10,273 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 | import streamlit as st
import pandas as pd
import sqlite3
import plotly.express as px
import plotly.graph_objects as go
import os
def main():
st.set_page_config(page_title="Stock Trading Database Console", layout="wide")
st.title("📊 Stock Trading Database Console")
st.markdown("### SQLite Database Management & Analytics")
# Database file info
db_file = "stock_trading.db"
if os.path.exists(db_file):
size = os.path.getsize(db_file)
st.success(f"Database: {db_file} ({size/1024:.1f} KB)")
else:
st.warning(f"Database file {db_file} not found. Data will be created when you use the main app.")
return
# Connect to database
try:
conn = sqlite3.connect(db_file)
st.success("Database connection established")
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", "Tables", "Stock Data", "Trading Signals", "Model Metrics", "SQL Query"]
)
if section == "Overview":
show_overview(conn)
elif section == "Tables":
show_tables(conn)
elif section == "Stock Data":
show_stock_data(conn)
elif section == "Trading Signals":
show_trading_signals(conn)
elif section == "Model Metrics":
show_model_metrics(conn)
elif section == "SQL Query":
show_sql_interface(conn)
conn.close()
def show_overview(conn):
"""Show database overview"""
st.header("Database Overview")
# Get table information
tables_query = "SELECT name FROM sqlite_master WHERE type='table'"
tables = pd.read_sql(tables_query, conn)
if not tables.empty:
st.subheader("Available Tables")
st.dataframe(tables)
# Table statistics
col1, col2, col3, col4 = st.columns(4)
try:
stock_count = pd.read_sql("SELECT COUNT(*) as count FROM stock_data", conn).iloc[0]['count']
with col1:
st.metric("Stock Records", stock_count)
except:
with col1:
st.metric("Stock Records", 0)
try:
signals_count = pd.read_sql("SELECT COUNT(*) as count FROM trading_signals", conn).iloc[0]['count']
with col2:
st.metric("Trading Signals", signals_count)
except:
with col2:
st.metric("Trading Signals", 0)
try:
indicators_count = pd.read_sql("SELECT COUNT(*) as count FROM technical_indicators", conn).iloc[0]['count']
with col3:
st.metric("Technical Indicators", indicators_count)
except:
with col3:
st.metric("Technical Indicators", 0)
try:
models_count = pd.read_sql("SELECT COUNT(*) as count FROM model_metrics", conn).iloc[0]['count']
with col4:
st.metric("Model Metrics", models_count)
except:
with col4:
st.metric("Model Metrics", 0)
else:
st.info("No tables found. Use the main app to generate data.")
def show_tables(conn):
"""Show table schemas"""
st.header("Table Schemas")
# Get all tables
tables_query = "SELECT name FROM sqlite_master WHERE type='table'"
tables = pd.read_sql(tables_query, conn)
for table_name in tables['name']:
st.subheader(f"Table: {table_name}")
# Get table schema
schema_query = f"PRAGMA table_info({table_name})"
schema = pd.read_sql(schema_query, conn)
st.dataframe(schema)
# Get sample data
try:
sample_query = f"SELECT * FROM {table_name} LIMIT 3"
sample = pd.read_sql(sample_query, conn)
if not sample.empty:
st.write("Sample Data:")
st.dataframe(sample)
except:
st.write("No sample data available")
st.markdown("---")
def show_stock_data(conn):
"""Show stock OHLCV data"""
st.header("Stock Data Analysis")
try:
# Get unique symbols
symbols_query = "SELECT DISTINCT symbol FROM stock_data ORDER BY symbol"
symbols = pd.read_sql(symbols_query, conn)
if not symbols.empty:
selected_symbol = st.selectbox("Select Stock Symbol:", symbols['symbol'].tolist())
# Get data for selected symbol
data_query = f"""
SELECT * FROM stock_data
WHERE symbol = '{selected_symbol}'
ORDER BY date DESC
LIMIT 100
"""
stock_data = pd.read_sql(data_query, conn)
if not stock_data.empty:
st.dataframe(stock_data)
# Create candlestick chart
fig = go.Figure(data=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']
))
fig.update_layout(title=f"{selected_symbol} - Candlestick Chart")
st.plotly_chart(fig, use_container_width=True)
# Volume chart
fig_vol = px.bar(stock_data, x='date', y='volume', title=f"{selected_symbol} - Volume")
st.plotly_chart(fig_vol, use_container_width=True)
else:
st.info(f"No data found for {selected_symbol}")
else:
st.info("No stock data available. Train a model in the main app to generate data.")
except Exception as e:
st.error(f"Error loading stock data: {str(e)}")
def show_trading_signals(conn):
"""Show trading signals"""
st.header("Trading Signals Analysis")
try:
signals_query = "SELECT * FROM trading_signals ORDER BY signal_date DESC LIMIT 100"
signals = pd.read_sql(signals_query, conn)
if not signals.empty:
st.dataframe(signals)
# Signal distribution
col1, col2 = st.columns(2)
with col1:
signal_counts = signals['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, x='confidence', title="Confidence Distribution")
st.plotly_chart(fig_conf, use_container_width=True)
# Signals by symbol
if 'symbol' in signals.columns:
symbol_signals = signals.groupby('symbol')['signal'].count().reset_index()
fig_bar = px.bar(symbol_signals, x='symbol', y='signal', title="Signals by Symbol")
st.plotly_chart(fig_bar, use_container_width=True)
else:
st.info("No trading signals found. Generate signals in the main app.")
except Exception as e:
st.error(f"Error loading trading signals: {str(e)}")
def show_model_metrics(conn):
"""Show model performance metrics"""
st.header("Model Performance Metrics")
try:
metrics_query = "SELECT * FROM model_metrics ORDER BY training_date DESC"
metrics = pd.read_sql(metrics_query, conn)
if not metrics.empty:
st.dataframe(metrics)
# Performance charts
col1, col2 = st.columns(2)
with col1:
fig_acc = px.bar(metrics, x='symbol', y='accuracy', title="Model Accuracy")
st.plotly_chart(fig_acc, use_container_width=True)
with col2:
fig_prec = px.bar(metrics, x='symbol', y='precision_score', title="Model Precision")
st.plotly_chart(fig_prec, use_container_width=True)
else:
st.info("No model metrics found. Train models in the main app.")
except Exception as e:
st.error(f"Error loading model metrics: {str(e)}")
def show_sql_interface(conn):
"""SQL query interface"""
st.header("SQL Query Interface")
# Quick queries
st.subheader("Quick Queries")
col1, col2, col3 = st.columns(3)
with col1:
if st.button("Show All Tables"):
query = "SELECT name FROM sqlite_master WHERE type='table'"
result = pd.read_sql(query, conn)
st.dataframe(result)
with col2:
if st.button("Latest Signals"):
try:
query = "SELECT * FROM trading_signals ORDER BY created_at DESC LIMIT 10"
result = pd.read_sql(query, conn)
st.dataframe(result)
except Exception as e:
st.error(f"Error: {str(e)}")
with col3:
if st.button("Stock Summary"):
try:
query = """
SELECT symbol, COUNT(*) as records,
MIN(date) as first_date, MAX(date) as last_date
FROM stock_data
GROUP BY symbol
"""
result = pd.read_sql(query, conn)
st.dataframe(result)
except Exception as e:
st.error(f"Error: {str(e)}")
# Custom SQL
st.subheader("Custom SQL Query")
sql_query = st.text_area(
"Enter SQL Query:",
value="SELECT * FROM sqlite_master WHERE type='table';",
height=100
)
if st.button("Execute Query"):
try:
if sql_query.strip():
result = pd.read_sql(sql_query, conn)
st.dataframe(result)
st.success(f"Query executed successfully. {len(result)} rows returned.")
except Exception as e:
st.error(f"Query error: {str(e)}")
if __name__ == "__main__":
main() |