Spaces:
Build error
Build error
File size: 11,816 Bytes
9974f2c |
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 |
#!/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()
|