itsJB commited on
Commit
897b38c
1 Parent(s): 9856c9e

Upload 3 files

Browse files
Files changed (3) hide show
  1. app_groq.py +165 -0
  2. crew_groq.py +184 -0
  3. requirements.txt +11 -0
app_groq.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_groq 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
+ </p>
30
+ <p class="divider-content">
31
+ ----------------------------------------------------------------------------------------------------------------------------
32
+ </p>
33
+ </div>
34
+ """, unsafe_allow_html=True)
35
+
36
+ # Model selection
37
+ # model_option = st.sidebar.selectbox("Select LLM Model", ['Llama 3 8B', 'Llama 3.1 70B', 'Llama 3.1 8B'])
38
+ # groq_api_key = st.sidebar.text_input("Enter Groq API Key", type="password")
39
+
40
+ stock_symbol = st.sidebar.text_input("Enter Stock Symbol", value="AAPL")
41
+ time_period = st.sidebar.selectbox("Select Time Period", ['1mo', '3mo', '6mo', '1y', '2y', '5y', 'max'])
42
+ indicators = st.sidebar.multiselect("Select Indicators", ['Moving Averages', 'Volume', 'RSI', 'MACD'])
43
+ analyze_button = st.sidebar.button("📊 Analyze Stock", help="Click to start the stock analysis")
44
+
45
+ # Initialize session state
46
+ if 'analyzed' not in st.session_state:
47
+ st.session_state.analyzed = False
48
+ st.session_state.stock_info = None
49
+ st.session_state.stock_data = None
50
+ st.session_state.result_file_path = None
51
+
52
+ def get_stock_data(stock_symbol, period='1y'):
53
+ return yf.download(stock_symbol, period=period)
54
+
55
+ def plot_stock_chart(stock_data, indicators):
56
+ fig = make_subplots(rows=3, cols=1, shared_xaxes=True, vertical_spacing=0.05, row_heights=[0.6, 0.2, 0.2])
57
+
58
+ # Main price chart
59
+ fig.add_trace(go.Candlestick(x=stock_data.index,
60
+ open=stock_data['Open'],
61
+ high=stock_data['High'],
62
+ low=stock_data['Low'],
63
+ close=stock_data['Close'],
64
+ name='Price'),
65
+ row=1, col=1)
66
+
67
+ # Add selected indicators
68
+ if 'Moving Averages' in indicators:
69
+ 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)
70
+ 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)
71
+
72
+ if 'Volume' in indicators:
73
+ fig.add_trace(go.Bar(x=stock_data.index, y=stock_data['Volume'], name='Volume'), row=2, col=1)
74
+
75
+ if 'RSI' in indicators:
76
+ delta = stock_data['Close'].diff()
77
+ gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
78
+ loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()
79
+ rs = gain / loss
80
+ rsi = 100 - (100 / (1 + rs))
81
+ fig.add_trace(go.Scatter(x=stock_data.index, y=rsi, name='RSI'), row=3, col=1)
82
+
83
+ if 'MACD' in indicators:
84
+ ema12 = stock_data['Close'].ewm(span=12, adjust=False).mean()
85
+ ema26 = stock_data['Close'].ewm(span=26, adjust=False).mean()
86
+ macd = ema12 - ema26
87
+ signal = macd.ewm(span=9, adjust=False).mean()
88
+ fig.add_trace(go.Scatter(x=stock_data.index, y=macd, name='MACD'), row=3, col=1)
89
+ fig.add_trace(go.Scatter(x=stock_data.index, y=signal, name='Signal'), row=3, col=1)
90
+
91
+ fig.update_layout(
92
+ title='Stock Analysis',
93
+ yaxis_title='Price',
94
+ xaxis_rangeslider_visible=False,
95
+ height=800,
96
+ showlegend=True
97
+ )
98
+
99
+ fig.update_xaxes(
100
+ rangeselector=dict(
101
+ buttons=list([
102
+ dict(count=1, label="1m", step="month", stepmode="backward"),
103
+ dict(count=6, label="6m", step="month", stepmode="backward"),
104
+ dict(count=1, label="YTD", step="year", stepmode="todate"),
105
+ dict(count=1, label="1y", step="year", stepmode="backward"),
106
+ dict(step="all")
107
+ ])
108
+ ),
109
+ rangeslider=dict(visible=False),
110
+ type="date"
111
+ )
112
+
113
+ return fig
114
+
115
+ if analyze_button:
116
+ st.session_state.analyzed = False # Reset analyzed state
117
+ st.snow()
118
+
119
+ # Fetch stock info and data
120
+ with st.spinner(f"Fetching data for {stock_symbol}..."):
121
+ stock = yf.Ticker(stock_symbol)
122
+ st.session_state.stock_info = stock.info
123
+ st.session_state.stock_data = get_stock_data(stock_symbol, period=time_period)
124
+
125
+ # Create and run the crew
126
+ with st.spinner("Running analysis, please wait..."):
127
+
128
+ st.session_state.result_file_path = crew_creator(stock_symbol,
129
+ # model_option, groq_api_key
130
+ )
131
+
132
+ st.session_state.analyzed = True
133
+
134
+ # Display stock info if available
135
+ if st.session_state.stock_info:
136
+ st.markdown('<p class="medium-font">Stock Information</p>', unsafe_allow_html=True)
137
+ info = st.session_state.stock_info
138
+ col1, col2, col3 = st.columns(3)
139
+ with col1:
140
+ st.markdown(f"**Company Name:** {info.get('longName', 'N/A')}")
141
+ st.markdown(f"**Sector:** {info.get('sector', 'N/A')}")
142
+ with col2:
143
+ st.markdown(f"**Industry:** {info.get('industry', 'N/A')}")
144
+ st.markdown(f"**Country:** {info.get('country', 'N/A')}")
145
+ with col3:
146
+ st.markdown(f"**Current Price:** ${info.get('currentPrice', 'N/A')}")
147
+ st.markdown(f"**Market Cap:** ${info.get('marketCap', 'N/A')}")
148
+
149
+ # Display CrewAI result if available
150
+ if st.session_state.result_file_path:
151
+ st.markdown('<p class="medium-font">Analysis Result</p>', unsafe_allow_html=True)
152
+
153
+ # with open(st.session_state.result_file_path, 'r') as file:
154
+ # result = file.read()
155
+
156
+ st.markdown(st.session_state.result_file_path)
157
+
158
+ # Display chart
159
+ if st.session_state.analyzed and st.session_state.stock_data is not None:
160
+ st.markdown('<p class="medium-font">Interactive Stock Chart</p>', unsafe_allow_html=True)
161
+ st.plotly_chart(plot_stock_chart(st.session_state.stock_data, indicators), use_container_width=True)
162
+
163
+
164
+ st.markdown("---")
165
+ st.markdown('<p class="small-font">Crafted by base234 </p>', unsafe_allow_html=True)
crew_groq.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_groq import ChatGroq
7
+ from dotenv import load_dotenv
8
+ load_dotenv()
9
+ warnings.filterwarnings('ignore')
10
+
11
+ SERPER_API_KEY = os.getenv('SERPER_API_KEY')
12
+
13
+ # Model Selection
14
+ # def initialize_llm(model_option, groq_api_key):
15
+ # if model_option == 'Llama 3 8B':
16
+ # return ChatGroq(groq_api_key=groq_api_key, model='llama3-8b-8192', temperature=0.1)
17
+ # elif model_option == 'Llama 3.1 70B':
18
+ # return ChatGroq(groq_api_key=groq_api_key, model='llama-3.1-70b-versatile', temperature=0.1)
19
+ # elif model_option == 'Llama 3.1 8B':
20
+ # return ChatGroq(groq_api_key=groq_api_key, model='llama-3.1-8b-instant', temperature=0.1)
21
+ # else:
22
+ # raise ValueError("Invalid model option selected")
23
+
24
+ llm = ChatGroq(groq_api_key=os.getenv('GROQ_API_KEY'), model='llama-3.1-70b-versatile', temperature=0.1)
25
+
26
+ search_tool = SerperDevTool()
27
+ scrape_tool = ScrapeWebsiteTool()
28
+
29
+ def crew_creator(stock_selection,
30
+ # model_option, groq_api_key
31
+ ):
32
+
33
+ # llm = initialize_llm(model_option, groq_api_key)
34
+
35
+ data_analyst_agent = Agent(
36
+ role="Data Analyst",
37
+ goal="Monitor and analyze market data in real-time "
38
+ "to identify trends and predict market movements.",
39
+ backstory="Specializing in financial markets, this agent "
40
+ "uses statistical modeling and machine learning "
41
+ "to provide crucial insights. With a knack for data, "
42
+ "the Data Analyst Agent is the cornerstone for "
43
+ "informing trading decisions.",
44
+ verbose=True,
45
+ allow_delegation=True,
46
+ tools = [scrape_tool, search_tool],
47
+ llm=llm,
48
+ )
49
+
50
+ trading_strategy_agent = Agent(
51
+ role="Trading Strategy Developer",
52
+ goal="Develop and test various trading strategies based "
53
+ "on insights from the Data Analyst Agent.",
54
+ backstory="Equipped with a deep understanding of financial "
55
+ "markets and quantitative analysis, this agent "
56
+ "devises and refines trading strategies. It evaluates "
57
+ "the performance of different approaches to determine "
58
+ "the most profitable and risk-averse options.",
59
+ verbose=True,
60
+ allow_delegation=True,
61
+ tools = [scrape_tool, search_tool],
62
+ llm=llm,
63
+ )
64
+
65
+ # execution_agent = Agent(
66
+ # role="Trade Advisor",
67
+ # goal="Suggest optimal trade execution strategies "
68
+ # "based on approved trading strategies.",
69
+ # backstory="This agent specializes in analyzing the timing, price, "
70
+ # "and logistical details of potential trades. By evaluating "
71
+ # "these factors, it provides well-founded suggestions for "
72
+ # "when and how trades should be executed to maximize "
73
+ # "efficiency and adherence to strategy.",
74
+ # verbose=True,
75
+ # allow_delegation=True,
76
+ # tools = [scrape_tool, search_tool],
77
+ # llm=llm,
78
+ # )
79
+
80
+ # risk_management_agent = Agent(
81
+ # role="Risk Advisor",
82
+ # goal="Evaluate and provide insights on the risks "
83
+ # "associated with potential trading activities.",
84
+ # backstory="Armed with a deep understanding of risk assessment models "
85
+ # "and market dynamics, this agent scrutinizes the potential "
86
+ # "risks of proposed trades. It offers a detailed analysis of "
87
+ # "risk exposure and suggests safeguards to ensure that "
88
+ # "trading activities align with the firm’s risk tolerance.",
89
+ # verbose=True,
90
+ # allow_delegation=True,
91
+ # tools = [scrape_tool, search_tool],
92
+ # llm=llm,
93
+ # )
94
+
95
+ # Task for Data Analyst Agent: Analyze Market Data
96
+ data_analysis_task = Task(
97
+ description=(
98
+ "Continuously monitor and analyze market data for "
99
+ "the selected stock ({stock_selection}). "
100
+ "Use statistical modeling and machine learning to "
101
+ "identify trends and predict market movements."
102
+ ),
103
+ expected_output=(
104
+ "Insights and alerts about significant market "
105
+ "opportunities or threats for {stock_selection}."
106
+ ),
107
+ agent=data_analyst_agent,
108
+ )
109
+
110
+ # Task for Trading Strategy Agent: Develop Trading Strategies
111
+ strategy_development_task = Task(
112
+ description=(
113
+ "Develop and refine trading strategies based on "
114
+ "the insights from the Data Analyst and "
115
+ # "user-defined risk tolerance ({risk_tolerance}). "
116
+ # "Consider trading preferences ({trading_strategy_preference})."
117
+ ),
118
+ expected_output=(
119
+ "A set of potential trading strategies for {stock_selection} "
120
+ "that align with the user's risk tolerance."
121
+ ),
122
+ agent=trading_strategy_agent,
123
+ )
124
+
125
+ # Task for Trade Advisor Agent: Plan Trade Execution
126
+ # execution_planning_task = Task(
127
+ # description=(
128
+ # "Analyze approved trading strategies to determine the "
129
+ # "best execution methods for {stock_selection}, "
130
+ # "considering current market conditions and optimal pricing."
131
+ # ),
132
+ # expected_output=(
133
+ # "Detailed execution plans suggesting how and when to "
134
+ # "execute trades for {stock_selection}."
135
+ # ),
136
+ # agent=execution_agent,
137
+ # )
138
+
139
+ # Task for Risk Advisor Agent: Assess Trading Risks
140
+ # risk_assessment_task = Task(
141
+ # description=(
142
+ # "Evaluate the risks associated with the proposed trading "
143
+ # "strategies and execution plans for {stock_selection}. "
144
+ # "Provide a detailed analysis of potential risks "
145
+ # "and suggest mitigation strategies."
146
+ # ),
147
+ # expected_output=(
148
+ # "A comprehensive risk analysis report detailing potential "
149
+ # "risks and mitigation recommendations for {stock_selection}."
150
+ # ),
151
+ # agent=risk_management_agent,
152
+ # )
153
+
154
+ # Define the crew with agents and tasks
155
+ financial_trading_crew = Crew(
156
+ agents=[
157
+ data_analyst_agent,
158
+ trading_strategy_agent,
159
+ # execution_agent,
160
+ # risk_management_agent
161
+ ],
162
+
163
+ tasks=[
164
+ data_analysis_task,
165
+ strategy_development_task,
166
+ # execution_planning_task,
167
+ # risk_assessment_task
168
+ ],
169
+
170
+ manager_llm = llm,
171
+ process=Process.sequential,
172
+ verbose=True,
173
+ )
174
+
175
+ result = financial_trading_crew.kickoff(inputs={
176
+ 'stock_selection': stock_selection,
177
+ # 'initial_capital': initial_capital,
178
+ # 'risk_tolerance': risk_tolerance,
179
+ # 'trading_strategy_preference': trading_strategy_preference,
180
+ # 'news_impact_consideration': news_impact_consideration
181
+ })
182
+ return str(result)
183
+
184
+ # print(result)
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ crewai==0.55.2
2
+ crewai_tools==0.4.26
3
+ langchain==0.2.16
4
+ langchain-core==0.2.40
5
+ langchain-community==0.2.10
6
+ langchain-groq==0.1.9
7
+ python-dotenv==1.0.1
8
+ groq==0.11.0
9
+ streamlit==1.38.0
10
+ yfinance==0.2.43
11
+ plotly==5.24.0