feat: Add CSV report viewing functionality to technical scanner page

This commit is contained in:
Bobby (aider) 2025-02-10 22:40:11 -08:00
parent e001d2e766
commit 099c8b353e

View File

@ -18,6 +18,30 @@ def init_session_state():
if 'page' not in st.session_state: if 'page' not in st.session_state:
st.session_state.page = 'Trading Journal' st.session_state.page = 'Trading Journal'
def load_scanner_reports():
"""Load and return available scanner reports"""
import os
import pandas as pd
from datetime import datetime
reports = []
reports_dir = "scanner_results"
if os.path.exists(reports_dir):
for file in os.listdir(reports_dir):
if file.endswith(".csv"):
file_path = os.path.join(reports_dir, file)
# Get file creation time
created = datetime.fromtimestamp(os.path.getctime(file_path))
reports.append({
'name': file,
'path': file_path,
'created': created
})
# Sort by creation time, newest first
return sorted(reports, key=lambda x: x['created'], reverse=True)
def format_datetime(dt): def format_datetime(dt):
"""Format datetime for display""" """Format datetime for display"""
if dt: if dt:
@ -269,41 +293,78 @@ def trading_journal_page():
def technical_scanner_page(): def technical_scanner_page():
st.header("Technical Scanner") st.header("Technical Scanner")
scanner_type = st.selectbox( # Create tabs for scanner and reports
"Select Scanner", scanner_tab, reports_tab = st.tabs(["Run Scanner", "View Reports"])
["SunnyBands", "ATR-EMA", "ATR-EMA v2"]
)
col1, col2 = st.columns(2) with scanner_tab:
with col1: scanner_type = st.selectbox(
min_price = st.number_input("Minimum Price", value=5.0, step=0.1) "Select Scanner",
max_price = st.number_input("Maximum Price", value=100.0, step=0.1) ["SunnyBands", "ATR-EMA", "ATR-EMA v2"]
)
col1, col2 = st.columns(2)
with col1:
min_price = st.number_input("Minimum Price", value=5.0, step=0.1)
max_price = st.number_input("Maximum Price", value=100.0, step=0.1)
with col2:
min_volume = st.number_input("Minimum Volume", value=500000, step=100000)
portfolio_size = st.number_input("Portfolio Size", value=100000.0, step=1000.0)
if st.button("Run Scanner"):
with st.spinner("Running scanner..."):
try:
signals = run_technical_scanner(scanner_type.lower().replace(" ", "_"))
if signals:
st.success(f"Found {len(signals)} signals")
for signal in signals:
with st.expander(f"{signal['ticker']} - ${signal['entry_price']:.2f}"):
col1, col2 = st.columns(2)
with col1:
st.metric("Entry Price", f"${signal['entry_price']:.2f}")
st.metric("Target", f"${signal['target_price']:.2f}")
st.metric("Stop Loss", f"${signal['stop_loss']:.2f}")
with col2:
st.metric("Shares", signal['shares'])
st.metric("Position Size", f"${signal['position_size']:.2f}")
st.metric("Risk Amount", f"${abs(signal['risk_amount']):.2f}")
else:
st.info("No signals found")
except Exception as e:
st.error(f"Error running scanner: {str(e)}")
with col2: with reports_tab:
min_volume = st.number_input("Minimum Volume", value=500000, step=100000) st.subheader("Scanner Reports")
portfolio_size = st.number_input("Portfolio Size", value=100000.0, step=1000.0)
reports = load_scanner_reports()
if st.button("Run Scanner"): if reports:
with st.spinner("Running scanner..."): # Create a selectbox to choose the report
try: selected_report = st.selectbox(
signals = run_technical_scanner(scanner_type.lower().replace(" ", "_")) "Select Report",
if signals: options=reports,
st.success(f"Found {len(signals)} signals") format_func=lambda x: f"{x['name']} ({x['created'].strftime('%Y-%m-%d %H:%M')})"
for signal in signals: )
with st.expander(f"{signal['ticker']} - ${signal['entry_price']:.2f}"):
col1, col2 = st.columns(2) if selected_report:
with col1: try:
st.metric("Entry Price", f"${signal['entry_price']:.2f}") # Load and display the CSV
st.metric("Target", f"${signal['target_price']:.2f}") df = pd.read_csv(selected_report['path'])
st.metric("Stop Loss", f"${signal['stop_loss']:.2f}")
with col2: # Add download button
st.metric("Shares", signal['shares']) st.download_button(
st.metric("Position Size", f"${signal['position_size']:.2f}") label="Download Report",
st.metric("Risk Amount", f"${abs(signal['risk_amount']):.2f}") data=df.to_csv(index=False),
else: file_name=selected_report['name'],
st.info("No signals found") mime='text/csv'
except Exception as e: )
st.error(f"Error running scanner: {str(e)}")
# Display the dataframe
st.dataframe(df)
except Exception as e:
st.error(f"Error loading report: {str(e)}")
else:
st.info("No scanner reports found")
def main(): def main():
st.set_page_config(page_title="Trading System", layout="wide") st.set_page_config(page_title="Trading System", layout="wide")