zerito commited on
Commit
ec0e12a
·
verified ·
1 Parent(s): af62050

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +157 -51
app.py CHANGED
@@ -1,57 +1,15 @@
1
- from smolagents import CodeAgent, HfApiModel, load_tool, tool
2
- import datetime
3
- import pytz
4
  import yaml
5
- import random
 
6
  from tools.final_answer import FinalAnswerTool
7
  from Gradio_UI import GradioUI
8
- import os
9
-
10
-
11
- @tool
12
- def time_traveling_fortune_teller(timezone: str) -> str:
13
- """A fun tool that tells the current time in a given timezone and provides a random fortune.
14
- Args:
15
- timezone: A string representing a valid timezone (e.g., 'America/New_York').
16
- """
17
- try:
18
- tz = pytz.timezone(timezone)
19
- current_time = datetime.datetime.now(tz).strftime('%Y-%m-%d %H:%M:%S')
20
- current_hour = datetime.datetime.now(tz).hour
21
-
22
- # Fun fortunes based on time of day
23
- morning_fortunes = [
24
- "☀️ Rise and shine! Today is a blank canvas, so go paint your masterpiece!",
25
- "🌅 A surprise awaits you this morning… maybe it's coffee, maybe it's chaos. Who knows?",
26
- "🍩 Today might be sweet! Maybe a donut is in your future? (Or at least a snack!)"
27
- ]
28
-
29
- afternoon_fortunes = [
30
- "🌞 Power through! Your afternoon holds the promise of success (or at least a good nap).",
31
- "🍕 Lunchtime decisions determine your fate—choose wisely!",
32
- "🚀 Something unexpected will happen soon. Could be good, could be hilarious!"
33
- ]
34
-
35
- evening_fortunes = [
36
- "🌙 The stars say… it's time to relax! Or binge-watch your favorite show.",
37
- "🔥 A late-night snack might be calling your name. The universe approves.",
38
- "🌌 Your dreams tonight will hold a secret message. If you remember them!"
39
- ]
40
-
41
- # Choose fortune based on time of day
42
- if 5 <= current_hour < 12:
43
- fortune = random.choice(morning_fortunes)
44
- elif 12 <= current_hour < 18:
45
- fortune = random.choice(afternoon_fortunes)
46
- else:
47
- fortune = random.choice(evening_fortunes)
48
-
49
- return f"⏳ The local time in {timezone} is {current_time}.\n🔮 Your fortune: {fortune}"
50
-
51
- except Exception as e:
52
- return f"⚠️ Oops! The time-traveling fortune teller got lost in another dimension. Error: {str(e)}"
53
 
 
54
  final_answer = FinalAnswerTool()
 
 
55
  model = HfApiModel(
56
  max_tokens=2096,
57
  temperature=0.5,
@@ -59,18 +17,166 @@ model = HfApiModel(
59
  custom_role_conversions=None,
60
  )
61
 
62
- # Import tool from Hub
63
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
64
 
 
65
  with open("prompts.yaml", 'r') as stream:
66
  prompt_templates = yaml.safe_load(stream)
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  agent = CodeAgent(
69
  model=model,
70
- tools=[final_answer, time_traveling_fortune_teller],
71
  max_steps=6,
72
  verbosity_level=1,
73
  prompt_templates=prompt_templates
74
  )
75
 
 
76
  GradioUI(agent).launch()
 
1
+ import requests
2
+ import numpy as np
 
3
  import yaml
4
+ from smolagents import CodeAgent, HfApiModel, load_tool, tool
5
+ from textblob import TextBlob
6
  from tools.final_answer import FinalAnswerTool
7
  from Gradio_UI import GradioUI
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
+ # ✅ Final Answer Tool
10
  final_answer = FinalAnswerTool()
11
+
12
+ # ✅ AI Model
13
  model = HfApiModel(
14
  max_tokens=2096,
15
  temperature=0.5,
 
17
  custom_role_conversions=None,
18
  )
19
 
20
+ # ✅ Import Tool from Hub
21
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
22
 
23
+ # ✅ Load Prompt Templates
24
  with open("prompts.yaml", 'r') as stream:
25
  prompt_templates = yaml.safe_load(stream)
26
 
27
+
28
+ ### 🔹 1. Fetch Latest BTC News ###
29
+ @tool
30
+ def fetch_btc_news():
31
+ """
32
+ Fetches the latest Bitcoin news from CryptoPanic API.
33
+ """
34
+ url = "https://cryptopanic.com/api/v1/posts/?auth_token=ccbeafb47d266a78086f76c3f547546f6b747e88&currencies=BTC"
35
+
36
+ try:
37
+ response = requests.get(url)
38
+ response.raise_for_status()
39
+ data = response.json()
40
+
41
+ articles = [{"title": post["title"], "url": post["url"]} for post in data["results"][:5]]
42
+ return articles
43
+
44
+ except requests.exceptions.RequestException as e:
45
+ return {"error": str(e)}
46
+
47
+
48
+ ### 🔹 2. Analyze News Sentiment ###
49
+ @tool
50
+ def analyze_btc_news(articles):
51
+ """
52
+ Analyzes sentiment of Bitcoin news articles using TextBlob.
53
+ """
54
+ sentiments = []
55
+ keywords = []
56
+
57
+ for article in articles:
58
+ analysis = TextBlob(article["title"])
59
+ sentiments.append(analysis.sentiment.polarity)
60
+ keywords.extend(article["title"].split()[:5])
61
+
62
+ avg_sentiment = np.mean(sentiments) if sentiments else 0
63
+ sentiment_label = "Positive 😊" if avg_sentiment > 0 else "Negative 😡" if avg_sentiment < 0 else "Neutral 😐"
64
+
65
+ return {"sentiment_score": avg_sentiment, "sentiment_label": sentiment_label, "keywords": list(set(keywords))}
66
+
67
+
68
+ ### 🔹 3. Get BTC Market Insights (5m, 1H, 1D, 7D, 1M, 1Y) ###
69
+ @tool
70
+ def btc_market_insights():
71
+ """
72
+ Fetch BTC price, historical trends, moving averages, and Fear & Greed Index.
73
+ """
74
+ try:
75
+ # ✅ Fetch BTC price & 24h change
76
+ price_url = "https://api.coingecko.com/api/v3/simple/price"
77
+ price_params = {"ids": "bitcoin", "vs_currencies": "usd", "include_24hr_change": "true"}
78
+ price_data = requests.get(price_url, params=price_params).json()
79
+ btc_price = price_data["bitcoin"]["usd"]
80
+ btc_change = price_data["bitcoin"]["usd_24h_change"]
81
+
82
+ # ✅ Fetch historical price data (1 year)
83
+ hist_url = "https://api.coingecko.com/api/v3/coins/bitcoin/market_chart"
84
+ hist_params = {"vs_currency": "usd", "days": "365", "interval": "minute"}
85
+ hist_data = requests.get(hist_url, params=hist_params).json()
86
+ prices = [entry[1] for entry in hist_data["prices"]]
87
+
88
+ # ✅ Compute moving averages
89
+ ma_5m = np.mean(prices[-1:]) # 5-minute
90
+ ma_1h = np.mean(prices[-12:]) # 1-hour
91
+ ma_1d = np.mean(prices[-24:]) # 1-day
92
+ ma_7d = np.mean(prices[-168:]) # 7-day
93
+ ma_1m = np.mean(prices[-720:]) # 1-month
94
+ ma_1y = np.mean(prices[-8760:]) # 1-year
95
+
96
+ # ✅ Fetch Fear & Greed Index
97
+ fgi_url = "https://api.alternative.me/fng/"
98
+ fgi_data = requests.get(fgi_url).json()
99
+ fear_greed = fgi_data["data"][0]["value"]
100
+ fgi_text = fgi_data["data"][0]["value_classification"]
101
+
102
+ return {
103
+ "price": btc_price,
104
+ "24h_change": btc_change,
105
+ "ma_5m": ma_5m,
106
+ "ma_1h": ma_1h,
107
+ "ma_1d": ma_1d,
108
+ "ma_7d": ma_7d,
109
+ "ma_1m": ma_1m,
110
+ "ma_1y": ma_1y,
111
+ "fear_greed": fear_greed,
112
+ "fgi_text": fgi_text
113
+ }
114
+
115
+ except requests.exceptions.RequestException as e:
116
+ return {"error": str(e)}
117
+
118
+
119
+ ### 🔹 4. Make Buy/Sell/HODL Decision ###
120
+ @tool
121
+ def btc_decision(news_analysis, market_insights):
122
+ """
123
+ Aggregates news sentiment & market insights to suggest Buy, Sell, or HODL.
124
+ Evaluates ultra short-term (5m-1H), short-term (1D), weekly (7D), monthly (1M), and yearly (1Y) trends.
125
+ """
126
+ sentiment_score = news_analysis["sentiment_score"]
127
+ fgi = int(market_insights["fear_greed"])
128
+ btc_price = market_insights["price"]
129
+
130
+ # ✅ Moving Averages
131
+ ma_5m = market_insights["ma_5m"]
132
+ ma_1h = market_insights["ma_1h"]
133
+ ma_1d = market_insights["ma_1d"]
134
+ ma_7d = market_insights["ma_7d"]
135
+ ma_1m = market_insights["ma_1m"]
136
+ ma_1y = market_insights["ma_1y"]
137
+
138
+ decision = {
139
+ "5m-1H": "HODL 🤔",
140
+ "1D": "HODL 🤔",
141
+ "7D": "HODL 🤔",
142
+ "1M": "HODL 🤔",
143
+ "1Y": "HODL 🤔"
144
+ }
145
+
146
+ # ✅ Ultra Short-Term Decision (5m - 1H)
147
+ if btc_price > ma_5m and btc_price > ma_1h and fgi < 40 and sentiment_score > 0:
148
+ decision["5m-1H"] = "BUY 🚀 (Short pump)"
149
+ elif btc_price < ma_5m and btc_price < ma_1h and fgi > 60 and sentiment_score < 0:
150
+ decision["5m-1H"] = "SELL 📉 (Short dump)"
151
+
152
+ # ✅ Short-Term Decision (1 Day)
153
+ if btc_price > ma_1d and fgi < 40 and sentiment_score > 0:
154
+ decision["1D"] = "BUY 📈 (Daily uptrend)"
155
+ elif btc_price < ma_1d and fgi > 60 and sentiment_score < 0:
156
+ decision["1D"] = "SELL 📉 (Daily downtrend)"
157
+
158
+ # ✅ Weekly, Monthly, Yearly decisions...
159
+ if btc_price > ma_7d and fgi < 40 and sentiment_score > 0:
160
+ decision["7D"] = "BUY 📈 (Weekly bullish)"
161
+ elif btc_price < ma_7d and fgi > 60 and sentiment_score < 0:
162
+ decision["7D"] = "SELL 📉 (Weekly bearish)"
163
+
164
+ if btc_price > ma_1m and fgi < 40 and sentiment_score > 0:
165
+ decision["1M"] = "BUY 📈 (Mid-term bullish)"
166
+ elif btc_price < ma_1m and fgi > 60 and sentiment_score < 0:
167
+ decision["1M"] = "SELL 📉 (Mid-term bearish)"
168
+
169
+ return decision
170
+
171
+
172
+ # ✅ Agent Setup
173
  agent = CodeAgent(
174
  model=model,
175
+ tools=[final_answer, fetch_btc_news, analyze_btc_news, btc_market_insights, btc_decision],
176
  max_steps=6,
177
  verbosity_level=1,
178
  prompt_templates=prompt_templates
179
  )
180
 
181
+ # ✅ Launch UI
182
  GradioUI(agent).launch()