Skip to content

Commit fd8fd94

Browse files
authored
Merge pull request #151 from keetrap/Catalyst_example_files
Added example files
2 parents 1bb309c + 34cf1af commit fd8fd94

File tree

2 files changed

+802
-0
lines changed

2 files changed

+802
-0
lines changed
Lines changed: 311 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,311 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "markdown",
5+
"metadata": {},
6+
"source": [
7+
"# Financial Analysis System with RagaAI Catalyst Integration\n",
8+
"\n",
9+
"This Jupyter notebook demonstrates the integration of Catalyst, a powerful tracing and monitoring tool, with a financial analysis system. Catalyst provides seamless tracing capabilities for both function calls and AI model interactions, allowing for comprehensive analysis and debugging of complex systems."
10+
]
11+
},
12+
{
13+
"cell_type": "markdown",
14+
"metadata": {},
15+
"source": [
16+
"## Setup and Imports\n",
17+
"\n",
18+
"First, let's import the necessary libraries and set up our environment."
19+
]
20+
},
21+
{
22+
"cell_type": "code",
23+
"execution_count": 1,
24+
"metadata": {},
25+
"outputs": [
26+
{
27+
"name": "stderr",
28+
"output_type": "stream",
29+
"text": [
30+
"INFO:httpx:HTTP Request: GET https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json \"HTTP/1.1 200 OK\"\n"
31+
]
32+
}
33+
],
34+
"source": [
35+
"from ragaai_catalyst.tracers import Tracer\n",
36+
"from ragaai_catalyst import RagaAICatalyst\n",
37+
"from textblob import TextBlob\n",
38+
"from dotenv import load_dotenv\n",
39+
"import os\n",
40+
"import openai\n",
41+
"import random\n"
42+
]
43+
},
44+
{
45+
"cell_type": "code",
46+
"execution_count": 2,
47+
"metadata": {},
48+
"outputs": [],
49+
"source": [
50+
"# Load environment variables\n",
51+
"load_dotenv()\n",
52+
"\n",
53+
"# Initialize OpenAI API\n",
54+
"openai.api_key = os.getenv(\"OPENAI_API_KEY\")"
55+
]
56+
},
57+
{
58+
"cell_type": "code",
59+
"execution_count": 3,
60+
"metadata": {},
61+
"outputs": [
62+
{
63+
"name": "stdout",
64+
"output_type": "stream",
65+
"text": [
66+
"Token(s) set successfully\n"
67+
]
68+
}
69+
],
70+
"source": [
71+
"# Initialize providers\n",
72+
"catalyst = RagaAICatalyst(\n",
73+
" access_key=\"*****\",\n",
74+
" secret_key=\"*****\",\n",
75+
" base_url=\"https://catalyst.raga.ai/api\",\n",
76+
")"
77+
]
78+
},
79+
{
80+
"cell_type": "markdown",
81+
"metadata": {},
82+
"source": [
83+
"## FinancialAnalysisSystem Class\n",
84+
"\n",
85+
"Now, let's define our `FinancialAnalysisSystem` class with Catalyst integration."
86+
]
87+
},
88+
{
89+
"cell_type": "code",
90+
"execution_count": 4,
91+
"metadata": {},
92+
"outputs": [
93+
{
94+
"data": {
95+
"text/plain": [
96+
"<ragaai_catalyst.tracers.tracer.Tracer at 0x20dc23c0710>"
97+
]
98+
},
99+
"execution_count": 4,
100+
"metadata": {},
101+
"output_type": "execute_result"
102+
}
103+
],
104+
"source": [
105+
"tracer = Tracer(\n",
106+
" project_name=\"tracer\",\n",
107+
" dataset_name=\"testing\",\n",
108+
" tracer_type=\"anything\",\n",
109+
" metadata={\n",
110+
" \"model\": \"gpt-4o-mini\",\n",
111+
" \"environment\": \"production\"\n",
112+
" },\n",
113+
" pipeline={\n",
114+
" \"llm_model\": \"gpt-4o-mini\",\n",
115+
" \"vector_store\": \"faiss\",\n",
116+
" \"embed_model\": \"text-embedding-ada-002\",\n",
117+
" }\n",
118+
")\n",
119+
"tracer.start()"
120+
]
121+
},
122+
{
123+
"cell_type": "code",
124+
"execution_count": 5,
125+
"metadata": {},
126+
"outputs": [],
127+
"source": [
128+
"class FinancialAnalysisSystem:\n",
129+
" def __init__(self):\n",
130+
" self.stock_data = {}\n",
131+
" self.news_sentiment = {}\n",
132+
" self.economic_indicators = {}\n",
133+
"\n",
134+
" @tracer.trace_tool(name=\"fetch_stock_data\")\n",
135+
" def fetch_stock_data(self, symbol):\n",
136+
" return {\n",
137+
" \"symbol\": symbol,\n",
138+
" \"price\": round(random.uniform(50, 500), 2),\n",
139+
" \"change\": round(random.uniform(-5, 5), 2),\n",
140+
" }\n",
141+
"\n",
142+
" @tracer.trace_tool(name=\"fetch_news_articles\")\n",
143+
" def fetch_news_articles(self, company):\n",
144+
" return [\n",
145+
" f\"{company} announces new product line\",\n",
146+
" f\"{company} reports quarterly earnings\",\n",
147+
" f\"{company} faces regulatory scrutiny\",\n",
148+
" ]\n",
149+
"\n",
150+
" @tracer.trace_tool(name=\"analyze_sentiment\")\n",
151+
" def analyze_sentiment(self, text):\n",
152+
" return TextBlob(text).sentiment.polarity\n",
153+
"\n",
154+
" @tracer.trace_tool(name=\"fetch_economic_indicators\")\n",
155+
" def fetch_economic_indicators(self):\n",
156+
" return {\n",
157+
" \"gdp_growth\": round(random.uniform(-2, 5), 2),\n",
158+
" \"unemployment_rate\": round(random.uniform(3, 10), 2),\n",
159+
" \"inflation_rate\": round(random.uniform(0, 5), 2),\n",
160+
" }\n",
161+
"\n",
162+
" @tracer.trace_llm(name=\"analyze_market_conditions\")\n",
163+
" def analyze_market_conditions(self, stock_data, sentiment, economic_indicators):\n",
164+
" prompt = f\"\"\"\n",
165+
" Analyze the following market conditions and provide a brief market outlook:\n",
166+
" Stock: {stock_data['symbol']} at ${stock_data['price']} (change: {stock_data['change']}%)\n",
167+
" News Sentiment: {sentiment}\n",
168+
" Economic Indicators:\n",
169+
" - GDP Growth: {economic_indicators['gdp_growth']}%\n",
170+
" - Unemployment Rate: {economic_indicators['unemployment_rate']}%\n",
171+
" - Inflation Rate: {economic_indicators['inflation_rate']}%\n",
172+
" \"\"\"\n",
173+
" response = openai.chat.completions.create(\n",
174+
" model=\"gpt-4-0125-preview\",\n",
175+
" messages=[{\"role\": \"user\", \"content\": prompt}],\n",
176+
" max_tokens=150,\n",
177+
" )\n",
178+
" return response.choices[0].message.content.strip()\n",
179+
"\n",
180+
" @tracer.trace_llm(name=\"generate_investment_recommendation\")\n",
181+
" def generate_investment_recommendation(self, market_outlook, risk_tolerance):\n",
182+
" prompt = f\"\"\"\n",
183+
" Based on the following market outlook and investor risk tolerance,\n",
184+
" provide a specific investment recommendation:\n",
185+
" Market Outlook: {market_outlook}\n",
186+
" Investor Risk Tolerance: {risk_tolerance}\n",
187+
" \"\"\"\n",
188+
" response = openai.chat.completions.create(\n",
189+
" model=\"gpt-4-0125-preview\",\n",
190+
" messages=[{\"role\": \"user\", \"content\": prompt}],\n",
191+
" max_tokens=200,\n",
192+
" )\n",
193+
" return response.choices[0].message.content.strip()\n",
194+
"\n",
195+
" @tracer.trace_agent(name=\"FinancialAdvisorAgent\")\n",
196+
" def financial_advisor_agent(self, stock_symbol, risk_tolerance):\n",
197+
" self.stock_data = self.fetch_stock_data(stock_symbol)\n",
198+
" news_articles = self.fetch_news_articles(stock_symbol)\n",
199+
" sentiment_scores = [self.analyze_sentiment(article) for article in news_articles]\n",
200+
" self.news_sentiment = sum(sentiment_scores) / len(sentiment_scores)\n",
201+
" self.economic_indicators = self.fetch_economic_indicators()\n",
202+
" market_outlook = self.analyze_market_conditions(\n",
203+
" self.stock_data, self.news_sentiment, self.economic_indicators\n",
204+
" )\n",
205+
" recommendation = self.generate_investment_recommendation(market_outlook, risk_tolerance)\n",
206+
" return recommendation\n",
207+
"\n",
208+
" def run_analysis(self, stock_symbol, risk_tolerance):\n",
209+
" recommendation = self.financial_advisor_agent(stock_symbol, risk_tolerance)\n",
210+
" print(f\"\\nAnalysis for {stock_symbol}:\")\n",
211+
" print(f\"Stock Data: {self.stock_data}\")\n",
212+
" print(f\"News Sentiment: {self.news_sentiment}\")\n",
213+
" print(f\"Economic Indicators: {self.economic_indicators}\")\n",
214+
" print(f\"\\nInvestment Recommendation:\\n{recommendation}\")\n",
215+
" if \"buy\" in recommendation.lower():\n",
216+
" self.execute_buy_order(stock_symbol)\n",
217+
" elif \"sell\" in recommendation.lower():\n",
218+
" self.execute_sell_order(stock_symbol)\n",
219+
" else:\n",
220+
" print(\"No action taken based on the current recommendation.\")\n",
221+
"\n",
222+
" @tracer.trace_tool(name=\"execute_buy_order\")\n",
223+
" def execute_buy_order(self, symbol):\n",
224+
" print(f\"Executing buy order for {symbol}\")\n",
225+
"\n",
226+
" @tracer.trace_tool(name=\"execute_sell_order\")\n",
227+
" def execute_sell_order(self, symbol):\n",
228+
" print(f\"Executing sell order for {symbol}\")"
229+
]
230+
},
231+
{
232+
"cell_type": "markdown",
233+
"metadata": {},
234+
"source": [
235+
"## Running the Analysis\n",
236+
"\n",
237+
"Now let's create an instance of our `FinancialAnalysisSystem` and run an analysis."
238+
]
239+
},
240+
{
241+
"cell_type": "code",
242+
"execution_count": 6,
243+
"metadata": {},
244+
"outputs": [
245+
{
246+
"name": "stderr",
247+
"output_type": "stream",
248+
"text": [
249+
"INFO:httpx:HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n",
250+
"INFO:httpx:HTTP Request: POST https://api.openai.com/v1/chat/completions \"HTTP/1.1 200 OK\"\n"
251+
]
252+
},
253+
{
254+
"name": "stdout",
255+
"output_type": "stream",
256+
"text": [
257+
"\n",
258+
"Analysis for AAPL:\n",
259+
"Stock Data: {'symbol': 'AAPL', 'price': 259.58, 'change': -0.48}\n",
260+
"News Sentiment: 0.04545454545454545\n",
261+
"Economic Indicators: {'gdp_growth': -1.33, 'unemployment_rate': 9.91, 'inflation_rate': 0.73}\n",
262+
"\n",
263+
"Investment Recommendation:\n",
264+
"Based on the described market outlook for AAPL stock and considering a moderate investor risk tolerance, a nuanced investment recommendation would be warranted. Given that AAPL has experienced a slight decrease in stock price, this suggests a potentially favorable buying opportunity, especially if the dip is viewed as a minor adjustment rather than part of a downtrend. The slightly positive news sentiment indicates there is somewhat positive coverage or views from analysts, which, combined with a moderate risk tolerance, hints at the potential for growth or at least stability.\n",
265+
"\n",
266+
"### Investment Recommendation: Buy and Hold Strategy with Diversification\n",
267+
"\n",
268+
"1. **Buy AAPL Stock:** Given the slight decrease and assuming the fundamentals of Apple Inc. remain strong (which would require further analysis of their earnings reports, product launches, market share, etc.), buying AAPL stock at a minor dip presents an opportunity to acquire shares at a slightly lower price. The slight positive news sentiment supports the idea that there may not be significant underlying issues with the company, but rather temporary factors affecting\n",
269+
"Executing buy order for AAPL\n",
270+
"Warning: Could not process Error retrieving notebook name: Can't identify the notebook name.: [Errno 2] No such file or directory: \"c:\\\\Users\\\\parte\\\\Desktop\\\\AgentNeo\\\\examples\\\\Error retrieving notebook name: Can't identify the notebook name\"\n",
271+
"Trace saved to C:\\Users\\parte\\AppData\\Local\\Temp/594f4f8f-bd5d-4504-bad7-05bc031f7612.json\n",
272+
"Uploading agentic traces...\n",
273+
"Agentic Traces uploaded\n",
274+
"Code already exists\n"
275+
]
276+
}
277+
],
278+
"source": [
279+
"# Create an instance of FinancialAnalysisSystem\n",
280+
"analysis_system = FinancialAnalysisSystem()\n",
281+
"\n",
282+
"# Run an analysis for Apple stock with moderate risk tolerance\n",
283+
"analysis_system.run_analysis(\"AAPL\", \"moderate\")\n",
284+
"\n",
285+
"# Stop the tracer when analysis is complete\n",
286+
"tracer.stop()"
287+
]
288+
}
289+
],
290+
"metadata": {
291+
"kernelspec": {
292+
"display_name": "cat",
293+
"language": "python",
294+
"name": "python3"
295+
},
296+
"language_info": {
297+
"codemirror_mode": {
298+
"name": "ipython",
299+
"version": 3
300+
},
301+
"file_extension": ".py",
302+
"mimetype": "text/x-python",
303+
"name": "python",
304+
"nbconvert_exporter": "python",
305+
"pygments_lexer": "ipython3",
306+
"version": "3.11.11"
307+
}
308+
},
309+
"nbformat": 4,
310+
"nbformat_minor": 2
311+
}

0 commit comments

Comments
 (0)