itsJB commited on
Commit
0132af7
1 Parent(s): a550196

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +156 -0
  2. crew.py +179 -0
app.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import yfinance as yf
3
+ import plotly.graph_objs as go
4
+ from plotly.subplots import make_subplots
5
+ from crew import crew_creator
6
+ from dotenv import load_dotenv
7
+ load_dotenv()
8
+
9
+ st.set_page_config(layout="wide", page_title="Finance Agent", initial_sidebar_state="expanded")
10
+ st.sidebar.markdown('<p class="medium-font">Configuration</p>', unsafe_allow_html=True)
11
+
12
+ st.markdown("""
13
+ <div class="analysis-card">
14
+ <h2 class="analysis-title">AI-Agents Finance Analyst Platform</h2>
15
+ <p class="analysis-content">
16
+ Welcome to my cutting-edge stock analysis platform, leveraging Artificial Intelligence and Large Language Models (LLMs) to deliver professional-grade investment insights. Our system offers:
17
+ </p>
18
+ <ul class="analysis-list">
19
+ <li class="analysis-list-item">Comprehensive Data Analysis on stocks, and investing.</li>
20
+ <li class="analysis-list-item">In-depth fundamental and technical analyses</li>
21
+ <li class="analysis-list-item">Extensive web and news research integration</li>
22
+ <li class="analysis-list-item">Customizable analysis parameters including time frames and specific indicators</li>
23
+ </ul>
24
+ <p class="analysis-content">
25
+ Users can obtain a detailed, AI-generated analysis report by simply selecting a stock symbol, specifying a time period, and choosing desired analysis indicators. This platform aims to empower investors with data-driven, AI-enhanced decision-making tools for the complex world of stock market investments.
26
+ </p>
27
+ <p class="analysis-content">
28
+ Please note, this analysis is for informational purposes only and should not be construed as financial or investment advice.
29
+ </div>
30
+ """, unsafe_allow_html=True)
31
+
32
+ stock_symbol = st.sidebar.text_input("Enter Stock Symbol", value="NVDA", placeholder="META, AAPL, NVDA")
33
+ time_period = st.sidebar.selectbox("Select Time Period", ['1mo', '3mo', '6mo', '1y', '2y', '5y', 'max'])
34
+ indicators = st.sidebar.multiselect("Select Indicators", ['Moving Averages', 'Volume', 'RSI', 'MACD'])
35
+ analyze_button = st.sidebar.button("📊 Analyze Stock", help="Click to start the stock analysis")
36
+
37
+ # Initialize session state
38
+ if 'analyzed' not in st.session_state:
39
+ st.session_state.analyzed = False
40
+ st.session_state.stock_info = None
41
+ st.session_state.stock_data = None
42
+ st.session_state.result_file_path = None
43
+
44
+ def get_stock_data(stock_symbol, period='1y'):
45
+ return yf.download(stock_symbol, period=period)
46
+
47
+ def plot_stock_chart(stock_data, indicators):
48
+ fig = make_subplots(rows=3, cols=1, shared_xaxes=True, vertical_spacing=0.05, row_heights=[0.6, 0.2, 0.2])
49
+
50
+ # Main price chart
51
+ fig.add_trace(go.Candlestick(x=stock_data.index,
52
+ open=stock_data['Open'],
53
+ high=stock_data['High'],
54
+ low=stock_data['Low'],
55
+ close=stock_data['Close'],
56
+ name='Price'),
57
+ row=1, col=1)
58
+
59
+ # Add selected indicators
60
+ if 'Moving Averages' in indicators:
61
+ fig.add_trace(go.Scatter(x=stock_data.index, y=stock_data['Close'].rolling(window=50).mean(), name='50 MA', line=dict(color='orange')), row=1, col=1)
62
+ fig.add_trace(go.Scatter(x=stock_data.index, y=stock_data['Close'].rolling(window=200).mean(), name='200 MA', line=dict(color='red')), row=1, col=1)
63
+
64
+ if 'Volume' in indicators:
65
+ fig.add_trace(go.Bar(x=stock_data.index, y=stock_data['Volume'], name='Volume'), row=2, col=1)
66
+
67
+ if 'RSI' in indicators:
68
+ delta = stock_data['Close'].diff()
69
+ gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
70
+ loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()
71
+ rs = gain / loss
72
+ rsi = 100 - (100 / (1 + rs))
73
+ fig.add_trace(go.Scatter(x=stock_data.index, y=rsi, name='RSI'), row=3, col=1)
74
+
75
+ if 'MACD' in indicators:
76
+ ema12 = stock_data['Close'].ewm(span=12, adjust=False).mean()
77
+ ema26 = stock_data['Close'].ewm(span=26, adjust=False).mean()
78
+ macd = ema12 - ema26
79
+ signal = macd.ewm(span=9, adjust=False).mean()
80
+ fig.add_trace(go.Scatter(x=stock_data.index, y=macd, name='MACD'), row=3, col=1)
81
+ fig.add_trace(go.Scatter(x=stock_data.index, y=signal, name='Signal'), row=3, col=1)
82
+
83
+ fig.update_layout(
84
+ title='Stock Analysis',
85
+ yaxis_title='Price',
86
+ xaxis_rangeslider_visible=False,
87
+ height=800,
88
+ showlegend=True
89
+ )
90
+
91
+ fig.update_xaxes(
92
+ rangeselector=dict(
93
+ buttons=list([
94
+ dict(count=1, label="1m", step="month", stepmode="backward"),
95
+ dict(count=6, label="6m", step="month", stepmode="backward"),
96
+ dict(count=1, label="YTD", step="year", stepmode="todate"),
97
+ dict(count=1, label="1y", step="year", stepmode="backward"),
98
+ dict(step="all")
99
+ ])
100
+ ),
101
+ rangeslider=dict(visible=False),
102
+ type="date"
103
+ )
104
+
105
+ return fig
106
+
107
+ if analyze_button:
108
+ st.session_state.analyzed = False # Reset analyzed state
109
+ st.snow()
110
+
111
+ # Fetch stock info and data
112
+ with st.spinner(f"Fetching data for {stock_symbol}..."):
113
+ stock = yf.Ticker(stock_symbol)
114
+ st.session_state.stock_info = stock.info
115
+ st.session_state.stock_data = get_stock_data(stock_symbol, period=time_period)
116
+
117
+ # Create and run the crew
118
+ with st.spinner("Running analysis, please wait..."):
119
+
120
+ st.session_state.result_file_path = crew_creator(stock_symbol)
121
+
122
+ st.session_state.analyzed = True
123
+
124
+ # Display stock info if available
125
+ if st.session_state.stock_info:
126
+ st.markdown('<p class="medium-font">Stock Information</p>', unsafe_allow_html=True)
127
+ info = st.session_state.stock_info
128
+ col1, col2, col3 = st.columns(3)
129
+ with col1:
130
+ st.markdown(f"**Company Name:** {info.get('longName', 'N/A')}")
131
+ st.markdown(f"**Sector:** {info.get('sector', 'N/A')}")
132
+ with col2:
133
+ st.markdown(f"**Industry:** {info.get('industry', 'N/A')}")
134
+ st.markdown(f"**Country:** {info.get('country', 'N/A')}")
135
+ with col3:
136
+ st.markdown(f"**Current Price:** ${info.get('currentPrice', 'N/A')}")
137
+ st.markdown(f"**Market Cap:** ${info.get('marketCap', 'N/A')}")
138
+
139
+ # Display CrewAI result if available
140
+ if st.session_state.result_file_path:
141
+ st.markdown('<p class="medium-font">Analysis Result</p>', unsafe_allow_html=True)
142
+
143
+ # with open(st.session_state.result_file_path, 'r') as file:
144
+ # result = file.read()
145
+ st.markdown("---")
146
+
147
+ st.markdown(st.session_state.result_file_path)
148
+
149
+ # Display chart
150
+ if st.session_state.analyzed and st.session_state.stock_data is not None:
151
+ st.markdown('<p class="medium-font">Interactive Stock Chart</p>', unsafe_allow_html=True)
152
+ st.plotly_chart(plot_stock_chart(st.session_state.stock_data, indicators), use_container_width=True)
153
+
154
+
155
+ st.markdown("---")
156
+ st.markdown('<p class="small-font">Crafted by base234 </p>', unsafe_allow_html=True)
crew.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import warnings
3
+ from crewai import Agent, Task, Crew
4
+ from crewai_tools import ScrapeWebsiteTool, SerperDevTool
5
+ from crewai import Crew, Process
6
+ from langchain_openai import ChatOpenAI
7
+
8
+ from dotenv import load_dotenv
9
+ load_dotenv()
10
+ warnings.filterwarnings('ignore')
11
+
12
+ SERPER_API_KEY = os.getenv('SERPER_API_KEY')
13
+
14
+ SAMBAVERSE_API_KEY = os.getenv('SAMBANOVA_API_KEY')
15
+ SAMBANOVA_API_URL = "https://api.sambanova.ai/v1"
16
+
17
+ search_tool = SerperDevTool()
18
+ scrape_tool = ScrapeWebsiteTool()
19
+
20
+ llm = ChatOpenAI(
21
+ model="Meta-Llama-3.1-8B-Instruct-8k",
22
+ temperature=0.5,
23
+ max_retries=2,
24
+ base_url=SAMBANOVA_API_URL,
25
+ api_key=SAMBAVERSE_API_KEY,
26
+ )
27
+
28
+ def crew_creator(stock_selection):
29
+
30
+ # data_analyst_agent = Agent(
31
+ # role="Data Analyst",
32
+ # goal="Monitor and analyze market data in real-time "
33
+ # "to identify trends and predict market movements.",
34
+ # backstory="Specializing in financial markets, this agent "
35
+ # "uses statistical modeling and machine learning "
36
+ # "to provide crucial insights. With a knack for data, "
37
+ # "the Data Analyst Agent is the cornerstone for "
38
+ # "informing trading decisions.",
39
+ # verbose=True,
40
+ # allow_delegation=True,
41
+ # tools = [scrape_tool, search_tool],
42
+ # llm=llm,
43
+ # )
44
+
45
+ trading_strategy_agent = Agent(
46
+ role="Trading Strategy Developer",
47
+ goal="Develop and test various trading strategies based "
48
+ "on insights from the Data Analyst Agent.",
49
+ backstory="Equipped with a deep understanding of financial "
50
+ "markets and quantitative analysis, this agent "
51
+ "devises and refines trading strategies. It evaluates "
52
+ "the performance of different approaches to determine "
53
+ "the most profitable and risk-averse options.",
54
+ verbose=True,
55
+ allow_delegation=True,
56
+ tools = [scrape_tool, search_tool],
57
+ llm=llm,
58
+ )
59
+
60
+ # execution_agent = Agent(
61
+ # role="Trade Advisor",
62
+ # goal="Suggest optimal trade execution strategies "
63
+ # "based on approved trading strategies.",
64
+ # backstory="This agent specializes in analyzing the timing, price, "
65
+ # "and logistical details of potential trades. By evaluating "
66
+ # "these factors, it provides well-founded suggestions for "
67
+ # "when and how trades should be executed to maximize "
68
+ # "efficiency and adherence to strategy.",
69
+ # verbose=True,
70
+ # allow_delegation=True,
71
+ # tools = [scrape_tool, search_tool],
72
+ # llm=llm,
73
+ # )
74
+
75
+ # risk_management_agent = Agent(
76
+ # role="Risk Advisor",
77
+ # goal="Evaluate and provide insights on the risks "
78
+ # "associated with potential trading activities.",
79
+ # backstory="Armed with a deep understanding of risk assessment models "
80
+ # "and market dynamics, this agent scrutinizes the potential "
81
+ # "risks of proposed trades. It offers a detailed analysis of "
82
+ # "risk exposure and suggests safeguards to ensure that "
83
+ # "trading activities align with the firm’s risk tolerance.",
84
+ # verbose=True,
85
+ # allow_delegation=True,
86
+ # tools = [scrape_tool, search_tool],
87
+ # llm=llm,
88
+ # )
89
+
90
+ # Task for Data Analyst Agent: Analyze Market Data
91
+ # data_analysis_task = Task(
92
+ # description=(
93
+ # "Continuously monitor and analyze market data for "
94
+ # "the selected stock ({stock_selection}). "
95
+ # "Use statistical modeling and machine learning to "
96
+ # "identify trends and predict market movements."
97
+ # ),
98
+ # expected_output=(
99
+ # "Insights and alerts about significant market "
100
+ # "opportunities or threats for {stock_selection}."
101
+ # ),
102
+ # agent=data_analyst_agent,
103
+ # )
104
+
105
+ # Task for Trading Strategy Agent: Develop Trading Strategies
106
+ strategy_development_task = Task(
107
+ description=(
108
+ "Develop and refine trading strategies based on "
109
+ "the insights from the Data Analyst and "
110
+ # "user-defined risk tolerance ({risk_tolerance}). "
111
+ # "Consider trading preferences ({trading_strategy_preference})."
112
+ ),
113
+ expected_output=(
114
+ "A set of potential trading strategies for {stock_selection} "
115
+ "that align with the user's risk tolerance."
116
+ ),
117
+ agent=trading_strategy_agent,
118
+ )
119
+
120
+ # Task for Trade Advisor Agent: Plan Trade Execution
121
+ # execution_planning_task = Task(
122
+ # description=(
123
+ # "Analyze approved trading strategies to determine the "
124
+ # "best execution methods for {stock_selection}, "
125
+ # "considering current market conditions and optimal pricing."
126
+ # ),
127
+ # expected_output=(
128
+ # "Detailed execution plans suggesting how and when to "
129
+ # "execute trades for {stock_selection}."
130
+ # ),
131
+ # agent=execution_agent,
132
+ # )
133
+
134
+ # Task for Risk Advisor Agent: Assess Trading Risks
135
+ # risk_assessment_task = Task(
136
+ # description=(
137
+ # "Evaluate the risks associated with the proposed trading "
138
+ # "strategies and execution plans for {stock_selection}. "
139
+ # "Provide a detailed analysis of potential risks "
140
+ # "and suggest mitigation strategies."
141
+ # ),
142
+ # expected_output=(
143
+ # "A comprehensive risk analysis report detailing potential "
144
+ # "risks and mitigation recommendations for {stock_selection}."
145
+ # ),
146
+ # agent=risk_management_agent,
147
+ # )
148
+
149
+ # Define the crew with agents and tasks
150
+ financial_trading_crew = Crew(
151
+ agents=[
152
+ # data_analyst_agent,
153
+ trading_strategy_agent,
154
+ # execution_agent,
155
+ # risk_management_agent
156
+ ],
157
+
158
+ tasks=[
159
+ # data_analysis_task,
160
+ strategy_development_task,
161
+ # execution_planning_task,
162
+ # risk_assessment_task
163
+ ],
164
+
165
+ manager_llm = llm,
166
+ process=Process.sequential,
167
+ verbose=True,
168
+ )
169
+
170
+ result = financial_trading_crew.kickoff(inputs={
171
+ 'stock_selection': stock_selection,
172
+ # 'initial_capital': initial_capital,
173
+ # 'risk_tolerance': risk_tolerance,
174
+ # 'trading_strategy_preference': trading_strategy_preference,
175
+ # 'news_impact_consideration': news_impact_consideration
176
+ })
177
+ return str(result)
178
+
179
+ # print(result)