finrobotpub / app.py
Starfish55's picture
Upload 9 files
9974f2c verified
#!/usr/bin/env python3
"""
FinRobot Hugging Face Space Application
A comprehensive AI Agent Platform for Financial Analysis using Large Language Models
"""
import streamlit as st
import autogen
from finrobot.utils import get_current_date, register_keys_from_json
from finrobot.agents.workflow import SingleAssistant, SingleAssistantShadow
import json
import os
from datetime import datetime
# Page configuration
st.set_page_config(
page_title="FinRobot - AI Agent Platform for Financial Analysis",
page_icon="🤖",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS
st.markdown("""
<style>
.main-header {
font-size: 3rem;
font-weight: bold;
text-align: center;
margin-bottom: 2rem;
background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.feature-card {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 1.5rem;
border-radius: 10px;
color: white;
margin: 1rem 0;
}
.success-message {
background-color: #d4edda;
border: 1px solid #c3e6cb;
color: #155724;
padding: 1rem;
border-radius: 5px;
margin: 1rem 0;
}
</style>
""", unsafe_allow_html=True)
def initialize_finrobot():
"""Initialize FinRobot with API configurations"""
try:
# Load OpenAI configuration
with open("OAI_CONFIG_LIST", "r") as f:
oai_config = json.load(f)
llm_config = {
"config_list": oai_config,
"timeout": 120,
"temperature": 0,
}
# Register API keys
register_keys_from_json("config_api_keys")
return llm_config
except Exception as e:
st.error(f"Error initializing FinRobot: {str(e)}")
return None
def create_market_analyst(llm_config):
"""Create Market Analyst agent"""
return SingleAssistant(
"Market_Analyst",
llm_config,
human_input_mode="NEVER",
)
def create_financial_analyst(llm_config):
"""Create Financial Analyst agent for report writing"""
return SingleAssistantShadow(
"Expert_Investor",
llm_config,
max_consecutive_auto_reply=None,
human_input_mode="TERMINATE",
)
def main():
# Header
st.markdown('<h1 class="main-header">🤖 FinRobot</h1>', unsafe_allow_html=True)
st.markdown('<h2 style="text-align: center; color: #666;">AI Agent Platform for Financial Analysis using LLMs</h2>', unsafe_allow_html=True)
# Sidebar
st.sidebar.title("🎛️ Configuration")
# Initialize FinRobot
if 'llm_config' not in st.session_state:
with st.spinner("Initializing FinRobot..."):
st.session_state.llm_config = initialize_finrobot()
if st.session_state.llm_config is None:
st.error("❌ Failed to initialize FinRobot. Please check your configuration files.")
return
# Agent selection
agent_type = st.sidebar.selectbox(
"Select Agent Type",
["Market Forecaster", "Financial Analyst", "Trade Strategist"]
)
st.sidebar.markdown("---")
# Main content area
if agent_type == "Market Forecaster":
st.markdown('<div class="feature-card">', unsafe_allow_html=True)
st.markdown("### 📈 Market Forecaster Agent")
st.markdown("Predicts stock movements using company ticker, financials, and market news.")
st.markdown('</div>', unsafe_allow_html=True)
col1, col2 = st.columns([2, 1])
with col1:
company_ticker = st.text_input("Company Ticker Symbol", value="AAPL", help="Enter stock ticker (e.g., AAPL, MSFT, NVDA)")
analysis_type = st.selectbox("Analysis Type", ["Brief Analysis", "Detailed Analysis", "Risk Assessment"])
with col2:
st.markdown("**Current Date:**")
st.info(get_current_date())
if st.button("🚀 Analyze Stock", type="primary"):
if company_ticker:
with st.spinner("Analyzing stock..."):
try:
assistant = create_market_analyst(st.session_state.llm_config)
message = f"""
Use all the tools provided to retrieve information available for {company_ticker} upon {get_current_date()}.
Analyze the positive developments and potential concerns of {company_ticker} with 2-4 most important factors respectively and keep them concise.
Most factors should be inferred from company related news.
Then make a rough prediction (e.g. up/down by 2-3%) of the {company_ticker} stock price movement for next week.
Provide a summary analysis to support your prediction.
"""
# Note: In a real implementation, you would call assistant.chat(message)
# For demo purposes, we'll show a placeholder
st.success("✅ Analysis completed!")
st.markdown(f"""
**Analysis for {company_ticker}:**
📊 **Positive Developments:**
- Strong quarterly earnings growth
- New product launches driving revenue
- Market expansion in emerging regions
⚠️ **Potential Concerns:**
- Supply chain disruptions
- Regulatory challenges
- Competitive pressure
🔮 **Prediction:** Expected 2-3% upward movement next week
*Note: This is a demo. In production, the agent would perform real analysis.*
""")
except Exception as e:
st.error(f"Error during analysis: {str(e)}")
else:
st.warning("Please enter a company ticker symbol.")
elif agent_type == "Financial Analyst":
st.markdown('<div class="feature-card">', unsafe_allow_html=True)
st.markdown("### 📋 Financial Analyst Agent")
st.markdown("Generates comprehensive equity research reports from 10-K forms and financial data.")
st.markdown('</div>', unsafe_allow_html=True)
col1, col2 = st.columns([2, 1])
with col1:
company_name = st.text_input("Company Name", value="Microsoft")
fiscal_year = st.text_input("Fiscal Year", value="2023")
with col2:
st.markdown("**Report Features:**")
st.markdown("• Financial statement analysis")
st.markdown("• Risk assessment")
st.markdown("• Performance visualization")
st.markdown("• PDF generation")
if st.button("📊 Generate Report", type="primary"):
if company_name and fiscal_year:
with st.spinner("Generating financial report..."):
try:
assistant = create_financial_analyst(st.session_state.llm_config)
st.success("✅ Report generation completed!")
st.markdown(f"""
**Financial Report for {company_name} - {fiscal_year}**
📈 **Key Metrics:**
- Revenue Growth: +15.2%
- Net Income: +12.8%
- Operating Margin: 42.1%
📊 **Financial Highlights:**
- Strong cloud revenue growth
- Improved operational efficiency
- Strategic acquisitions contributing to growth
⚠️ **Risk Factors:**
- Market competition
- Regulatory changes
- Economic uncertainties
*Note: This is a demo. In production, the agent would generate a full PDF report.*
""")
except Exception as e:
st.error(f"Error generating report: {str(e)}")
else:
st.warning("Please enter both company name and fiscal year.")
elif agent_type == "Trade Strategist":
st.markdown('<div class="feature-card">', unsafe_allow_html=True)
st.markdown("### ⚡ Trade Strategist Agent")
st.markdown("Advanced trading strategies with multimodal capabilities and real-time analysis.")
st.markdown('</div>', unsafe_allow_html=True)
col1, col2 = st.columns([2, 1])
with col1:
strategy_type = st.selectbox("Strategy Type", ["Momentum", "Mean Reversion", "Arbitrage", "Portfolio Optimization"])
risk_level = st.select_slider("Risk Level", options=["Low", "Medium", "High"], value="Medium")
with col2:
st.markdown("**Strategy Features:**")
st.markdown("• Real-time data analysis")
st.markdown("• Risk management")
st.markdown("• Portfolio optimization")
st.markdown("• Performance tracking")
if st.button("🎯 Generate Strategy", type="primary"):
with st.spinner("Generating trading strategy..."):
try:
st.success("✅ Strategy generated successfully!")
st.markdown(f"""
**{strategy_type} Trading Strategy - {risk_level} Risk**
📊 **Strategy Overview:**
- Entry signals based on technical indicators
- Stop-loss and take-profit levels defined
- Position sizing optimized for risk level
📈 **Expected Performance:**
- Annual Return: 12-18%
- Maximum Drawdown: 5-8%
- Sharpe Ratio: 1.2-1.8
⚙️ **Implementation:**
- Automated execution ready
- Real-time monitoring enabled
- Risk controls active
*Note: This is a demo. In production, the agent would provide detailed strategy parameters.*
""")
except Exception as e:
st.error(f"Error generating strategy: {str(e)}")
# Footer
st.markdown("---")
st.markdown("""
<div style="text-align: center; color: #666; margin-top: 2rem;">
<p>🤖 <strong>FinRobot</strong> - An Open-Source AI Agent Platform for Financial Analysis using Large Language Models</p>
<p>Built with ❤️ by <a href="https://github.com/AI4Finance-Foundation/FinRobot" target="_blank">AI4Finance Foundation</a></p>
</div>
""", unsafe_allow_html=True)
if __name__ == "__main__":
main()