cryogenic22/Stock_Agent_optimized
0
1# ui/components.py2 3import streamlit as st4from config.settings import CHART_PATTERNS, TECHNICAL_INDICATORS5# ui/components.py6 7import streamlit as st8from datetime import datetime9from config.settings import CHART_PATTERNS, TECHNICAL_INDICATORS10 11def create_sidebar():12 """Create the sidebar with analysis options"""13 with st.sidebar:14 st.title("๐ Chart Analysis AI")15 16 # Add New Chat button at the top17 if st.button("๐ New Chat", key="new_chat_button", type="primary"):18 # Save current chat if it exists19 if st.session_state.chat_history:20 timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")21 st.session_state['last_saved_chat'] = f"chat_{timestamp}"22 return "new_chat", None, [], [], "Individual Analysis"23 24 upload_option = st.radio(25 "Choose input method:",26 ("Upload Images", "Take Screenshot", "Ask Question"),27 key="sidebar_upload_method"28 )29 30 uploaded_files = None31 if upload_option == "Upload Images":32 uploaded_files = st.file_uploader(33 "Upload your charts",34 type=["png", "jpg", "jpeg"],35 accept_multiple_files=True,36 key="sidebar_file_uploader"37 )38 if uploaded_files:39 st.info(f"Uploaded {len(uploaded_files)} charts")40 elif upload_option == "Take Screenshot":41 if st.button("Take Screenshot", key="sidebar_screenshot_btn"):42 st.info("Feature coming soon! For now, please use the Upload Images option.")43 44 st.subheader("Analysis Options")45 patterns = st.multiselect(46 "Patterns to Look For",47 CHART_PATTERNS,48 key="sidebar_patterns"49 )50 51 indicators = st.multiselect(52 "Technical Indicators",53 TECHNICAL_INDICATORS,54 key="sidebar_indicators"55 )56 57 # Add comparison options58 if uploaded_files and len(uploaded_files) > 1:59 st.subheader("Comparison Options")60 comparison_type = st.selectbox(61 "Comparison Type",62 ["Individual Analysis", "Correlated Analysis", "Market Trend Analysis"],63 key="comparison_type"64 )65 st.info("""66 - Individual Analysis: Analyze each chart separately67 - Correlated Analysis: Find relationships between charts68 - Market Trend Analysis: Identify broader market patterns69 """)70 else:71 comparison_type = "Individual Analysis"72 73 return upload_option, uploaded_files, patterns, indicators, comparison_type74 75def show_analysis_section(uploaded_files):76 """Show the main analysis section"""77 if uploaded_files:78 # Create a grid layout for multiple images79 cols = st.columns(min(len(uploaded_files), 2)) # Max 2 columns80 for idx, uploaded_file in enumerate(uploaded_files):81 with cols[idx % 2]:82 st.image(uploaded_file, caption=f"Chart {idx + 1}", use_container_width=True)83 84 analyze_btn = st.button("Analyze Charts", key="main_analyze_btn")85 return analyze_btn86 87def show_chat_history(chat_history):88 """Display chat history"""89 st.subheader("Current Chat History")90 for idx, chat in enumerate(chat_history):91 timestamp = chat.get('timestamp', datetime.now().isoformat())92 analysis_type = chat.get('analysis_type', 'Analysis')93 94 with st.container():95 if analysis_type in ['Individual', 'Correlated Analysis']:96 st.markdown("**Initial Analysis:**")97 elif 'question' in chat:98 st.markdown(f"**Follow-up Question:** {chat['question']}")99 100 st.markdown(chat.get('analysis', ''))101 st.markdown("---")102 103def show_follow_up_section(key_suffix="", previous_response=None):104 """Show the follow-up question section with enhanced chat UI"""105 # Show previous response if provided106 if previous_response:107 with st.container():108 st.markdown("**Previous Response:**")109 st.markdown(previous_response)110 st.markdown("---")111 112 # Input section113 col1, col2 = st.columns([4, 1])114 with col1:115 follow_up = st.text_input(116 "Ask a follow-up question:",117 key=f"followup_input_{key_suffix}",118 placeholder="Type your question here..."119 )120 with col2:121 send_btn = st.button("Send", key=f"followup_send_btn_{key_suffix}")122 123 return follow_up if send_btn else None124 125def show_save_options():126 """Show save chat options"""127 st.subheader("Save Analysis")128 save_name = st.text_input(129 "Save chat as (optional):",130 key="save_chat_name"131 )132 save_btn = st.button("Save", key="save_chat_btn")133 return save_name if save_btn else None134 135def display_conversation_group(conversation):136 """Display a group of related chat messages"""137 if not conversation:138 return139 140 # Use the first message timestamp for the expander label141 timestamp = conversation[0].get('timestamp', 'No date')142 analysis_type = conversation[0].get('analysis_type', 'Analysis')143 144 with st.expander(f"{analysis_type} from {timestamp[:16]}", expanded=True):145 for message in conversation:146 if message.get('analysis_type') in ['Individual', 'Correlated Analysis']:147 st.markdown("**Initial Analysis:**")148 elif message.get('question'):149 st.markdown(f"**Follow-up Question:** {message['question']}")150 151 st.markdown(message.get('analysis', ''))152 153def create_expertise_selector():154 """Create expertise level selector"""155 if 'expertise_level' not in st.session_state:156 st.session_state.expertise_level = "Novice"157 158 expertise_descriptions = {159 "Novice": "New to trading, explain concepts in simple terms",160 "Intermediate": "Familiar with basic concepts, can handle some technical terms",161 "Expert": "Experienced trader, use full technical analysis terminology"162 }163 164 with st.sidebar:165 st.subheader("Expertise Level")166 expertise_level = st.selectbox(167 "Select your trading knowledge level:",168 list(expertise_descriptions.keys()),169 key="expertise_selector"170 )171 st.info(expertise_descriptions[expertise_level])172 st.session_state.expertise_level = expertise_level173 174 return expertise_level