cicboy commited on
Commit
adf3bae
·
1 Parent(s): 1c58375

Deploy updated Crypto Analyst Agent with Gradio UI

Browse files
Files changed (1) hide show
  1. app.py +242 -0
app.py CHANGED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # import libraries, APis and LLMs
2
+ from crewai import Agent, Task, Crew
3
+ import os
4
+ from dotenv import load_dotenv
5
+ from pathlib import Path
6
+ from tools.market_data import MarketDataTool
7
+ from tools.sentiment_tool import SentimentTool
8
+ from tools.historical_data_tool import HistoricalDataTool
9
+ from tools.analytics_tool import AnalyticsTool
10
+ import json
11
+ import gradio as gr
12
+ import warnings
13
+
14
+ warnings.filterwarnings("ignore")
15
+
16
+ # Load environment variables (from local .env or Hugging Face secrets)
17
+ load_dotenv()
18
+
19
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
20
+ SERPER_API_KEY = os.getenv("SERPER_API_KEY")
21
+
22
+ # Optional: set CHROMA_OPENAI_API_KEY for embedding compatibility
23
+ os.environ["CHROMA_OPENAI_API_KEY"] = OPENAI_API_KEY
24
+
25
+ os.environ["OPENAI_MODEL_NAME"] = "gpt-5-mini"
26
+
27
+ #Tools
28
+ market_data_tool = MarketDataTool()
29
+ sentiment_tool = SentimentTool()
30
+ historical_data_tool= HistoricalDataTool()
31
+ analytics_tool = AnalyticsTool()
32
+
33
+
34
+
35
+ # Define the agents
36
+ market_agent = Agent(
37
+ role="Crypto Market Analyst",
38
+ goal="Fetches live market prices using the CoinGecko API and summarize trends.",
39
+ backstory="A data-driven analyst who monitors cryptocurrency movements"
40
+ "and provides concise and accurate market insights",
41
+ verbose=False,
42
+ allow_delegations=True,
43
+ tools = [market_data_tool]
44
+ )
45
+
46
+ sentiment_agent = Agent(
47
+ role="Crypto Sentiment Analyst",
48
+ goal="Analyze public and media sentiment about cryptocurrencies to gauge market mood.",
49
+ backstory= "You are an expert at analyzing news headlines and social media chatter to assess whether sentiment is bullish or bearish.",
50
+ verbose = False,
51
+ allow_delegations=True,
52
+ tools=[sentiment_tool]
53
+ )
54
+
55
+ historical_agent = Agent(
56
+ role="Crypto Historical Analyst",
57
+ goal="Analyze past cryptocurrency trends using historical data.",
58
+ backstory=(
59
+ "An experienced quantitative analyst who studies long-term "
60
+ "price behavior, volatility, and trend strength using CoinGecko data."
61
+ ),
62
+ verbose=True,
63
+ allow_delegations=True,
64
+ tools=[historical_data_tool],
65
+ )
66
+
67
+ analytics_agent = Agent(
68
+ role="Cryptocurrency Analytics",
69
+ goal="Integrate metrics from the market agent, historical agent, and sentiment agent"
70
+ "and anlyze them to devise a coherent market view.",
71
+ backstory=(
72
+ "You are an expert quantitative strategist who synthesizes trend, sentiment and volatility data"
73
+ "to produce both structured metrics and qualitative market insights."
74
+ ),
75
+ verbose=True,
76
+ allow_delegations=False,
77
+ tools=[analytics_tool]
78
+ )
79
+
80
+ strategy_agent = Agent(
81
+ role="Crypto Strategy Analyst",
82
+ goal=(
83
+ "Transform analytical metrics and sentiment data into an actionable trading plan. "
84
+ "Determine directional bias, entry/exit strategies, and risk management guidance "
85
+ "based on risk, opportunity, and sentiment metrics."
86
+ ),
87
+ backstory=(
88
+ "A senior crypto strategist with a background in quantitative finance and "
89
+ "macro analysis. They integrate market structure, sentiment, and volatility "
90
+ "to form adaptive yet risk-aware trading stances."
91
+ ),
92
+ verbose=True,
93
+ )
94
+
95
+ reporting_agent = Agent(
96
+ role="Crypto Reporting Analyst",
97
+ goal=(
98
+ "Compile a concise, professional, and readable summary report "
99
+ "from all agents' outputs. The report should combine numerical analytics, "
100
+ "market context, sentiment, and trading strategy into one clear narrative."
101
+ ),
102
+ backstory=(
103
+ "You are a senior market strategist and financial writer who creates daily reports "
104
+ "for traders and institutional clients. You blend analytical data, sentiment, "
105
+ "and technical insight into clear, actionable narratives."
106
+ ),
107
+ verbose=True,
108
+ )
109
+
110
+ # Define the tasks
111
+
112
+ market_data_task = Task(
113
+ description=("Retrieve the live market price for {cryptocurrency_selection} in {currency_selection} and summarize briefly"),
114
+ expected_output=("Summary of the {cryptocurrency_selection} price in {currency_selection}"),
115
+ agent=market_agent
116
+ )
117
+
118
+ sentiment_task = Task(
119
+ description="Fetch sentiment for {cryptocurrency_selection} from Google News and Reddit, "
120
+ "then using expert intuition classify it as bullish, bearish or neutral.",
121
+ expected_output="Short summary with a sentiment classification.",
122
+ async_execution=True,
123
+ agent=sentiment_agent
124
+ )
125
+
126
+ historical_data_task = Task(
127
+ description="Fetch and summarize {cryptocurrency_selection}'s {currency_selection} price trend over the past {days_selection} days.",
128
+ expected_output="A short summary including start price, end price, percent change, volatility, and trend direction.",
129
+ agent=historical_agent,
130
+ )
131
+
132
+ analytics_task = Task(
133
+ description=(
134
+ "Combine the results of the Market, Historical and Sentiment agents for {cryptocurrency_selection}."
135
+ "First, use the 'analytics_tool' tool to compute structured metrics."
136
+ "Then, interpret those metrics into an analytical narrative summarizing the overall market condition, risks and opportunites for that cryptocurrency"
137
+ ),
138
+ expected_output=(
139
+ "A JSON object containing structured indicators from the tool"
140
+ "and an LLM-generated interpretation explaining what they mean."
141
+ ),
142
+ agent=analytics_agent,
143
+ inputs={
144
+ "market_data": "{output_of_market_data_task}",
145
+ "historical_data": "{output_of_historical_data_task}",
146
+ "sentiment_data": "{output_of_sentiment_data_task}"
147
+ }
148
+ )
149
+
150
+ strategy_task = Task(
151
+ description=(
152
+ "Based on the structured analytics output for {cryptocurrency_selection}, "
153
+ "derive a clear trading stance. Evaluate the metrics such as sentiment_confidence, "
154
+ "risk_score_out_of_10, opportunity_score_out_of_10, volatility, and RSI. "
155
+ "Formulate an actionable trading bias (e.g., long, neutral, short) with reasoning. "
156
+ "Provide position size guidance, entry/exit levels, and a brief risk management plan."
157
+ ),
158
+ expected_output=(
159
+ "JSON object with fields: bias, position_size, entry_strategy, exit_strategy, "
160
+ "risk_management, and reasoning."
161
+ ),
162
+ agent=strategy_agent,
163
+ )
164
+
165
+ reporting_task = Task(
166
+ description=(
167
+ "Generate a cohesive summary report for {cryptocurrency_selection}. "
168
+ "Combine data and insights from the Market, Historical, Sentiment, Analytics, "
169
+ "and Strategy agents. The report should read like a professional crypto analysis "
170
+ "briefing with structured Markdown sections."
171
+ ),
172
+ expected_output=(
173
+ "A Markdown-formatted report with sections:\n"
174
+ "1️⃣ Market Overview\n"
175
+ "2️⃣ Historical Performance\n"
176
+ "3️⃣ Sentiment Analysis\n"
177
+ "4️⃣ Analytical Summary\n"
178
+ "5️⃣ Strategy Outlook\n"
179
+ "6️⃣ Final Takeaways\n"
180
+ "Each section should contain concise, data-backed explanations and actionable insights."
181
+ ),
182
+ agent=reporting_agent,
183
+ )
184
+
185
+ # Create a crew
186
+ crypto_analysis_crew = Crew(
187
+ agents=[market_agent, historical_agent, sentiment_agent, analytics_agent, strategy_agent, reporting_agent],
188
+ tasks=[market_data_task, historical_data_task, sentiment_task, analytics_task, strategy_task, reporting_task],
189
+ process = "sequential",
190
+ verbose=True
191
+ )
192
+
193
+
194
+
195
+ # define the main gradio handler
196
+ def generate_report(crypto_name, currency, days):
197
+ crypto_trading_inputs={
198
+ "cryptocurrency_selection": crypto_name.lower(),
199
+ "currency_selection": currency.lower(),
200
+ "days_selection": int(days),
201
+ }
202
+
203
+ result = crypto_analysis_crew.kickoff(inputs=crypto_trading_inputs)
204
+
205
+ # Ensure Markdown rendering
206
+ if isinstance(result, dict) and "final_output" in result:
207
+ return result["final_output"]
208
+ return str(result)
209
+
210
+ #Gradio interface
211
+ with gr.Blocks(theme=gr.themes.Monochrome()) as app:
212
+ gr.Markdown("# 🪙 Crypto Intelligence Dashboard")
213
+ gr.Markdown("Run a full multi-agent analysis with adjustable lookback period.")
214
+
215
+ with gr.Row():
216
+ crypto = gr.Textbox(
217
+ label="Enter Cryptocurrency Name (e.g bitcoin, ethereum, cardano)",
218
+ placeholder="Type any crytocurrency name...",
219
+ value="bitcoin"
220
+ )
221
+ currency = gr.Dropdown(
222
+ ["usd", "eur", "gbp"],
223
+ label="Select Currency",
224
+ value="usd"
225
+ )
226
+ days = gr.Slider(
227
+ 30, 730, value=365, step=15,
228
+ label="Days to analyze (Historical Range)"
229
+ )
230
+
231
+ run_button = gr.Button("🚀 Run Full Analysis", variant="primary")
232
+ report_output = gr.Markdown(label="📊 Intelligence Report")
233
+
234
+ run_button.click(
235
+ generate_report,
236
+ inputs=[crypto, currency, days],
237
+ outputs=report_output,
238
+ show_progress=True
239
+ )
240
+
241
+ if __name__ == "__main__":
242
+ app.launch(server_name="0.0.0.0", server_port=7860, share=True)