zerito commited on
Commit
719c679
·
verified ·
1 Parent(s): d42e59f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -92
app.py CHANGED
@@ -1,4 +1,5 @@
1
  import requests
 
2
  import numpy as np
3
  import yaml
4
  from smolagents import CodeAgent, HfApiModel, load_tool, tool
@@ -25,95 +26,99 @@ 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 ###
@@ -121,13 +126,12 @@ def btc_market_insights():
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"]
@@ -135,6 +139,7 @@ def btc_decision(news_analysis, market_insights):
135
  ma_1m = market_insights["ma_1m"]
136
  ma_1y = market_insights["ma_1y"]
137
 
 
138
  decision = {
139
  "5m-1H": "HODL 🤔",
140
  "1D": "HODL 🤔",
@@ -143,33 +148,23 @@ def btc_decision(news_analysis, market_insights):
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],
@@ -178,5 +173,5 @@ agent = CodeAgent(
178
  prompt_templates=prompt_templates
179
  )
180
 
181
- # ✅ Launch UI
182
  GradioUI(agent).launch()
 
1
  import requests
2
+ from typing import List, Dict
3
  import numpy as np
4
  import yaml
5
  from smolagents import CodeAgent, HfApiModel, load_tool, tool
 
26
  prompt_templates = yaml.safe_load(stream)
27
 
28
 
29
+ # --- Utility Functions ---
30
+
31
+ def fetch_data(url, params=None):
32
  """
33
+ Utility function to make GET requests and return the response as JSON.
34
  """
 
 
35
  try:
36
+ response = requests.get(url, params=params)
37
  response.raise_for_status()
38
+ return response.json()
 
 
 
 
39
  except requests.exceptions.RequestException as e:
40
  return {"error": str(e)}
41
 
42
 
43
+ def compute_moving_average(prices, window):
44
+ """
45
+ Computes the moving average for the given price data over a specified window.
46
+ """
47
+ return np.mean(prices[-window:]) if len(prices) >= window else np.mean(prices)
48
+
49
+
50
+ # --- Tools ---
51
+
52
+ ### 🔹 1. Fetch Latest BTC News ###
53
+ @tool
54
+
55
+ # --- Fetch BTC News ---
56
+ def fetch_btc_news() -> List[Dict[str, str]]:
57
+ """
58
+ Fetches the latest Bitcoin news from CryptoPanic API.
59
+ Returns a list of dictionaries containing 'title' and 'url' of the articles.
60
+ """
61
+ url = "https://cryptopanic.com/api/v1/posts/?auth_token=ccbeafb47d266a78086f76c3f547546f6b747e88&currencies=BTC"
62
+ data = fetch_data(url)
63
+ return [{"title": post["title"], "url": post["url"]} for post in data.get("results", [])[:5]]
64
+
65
+
66
  ### 🔹 2. Analyze News Sentiment ###
67
  @tool
68
  def analyze_btc_news(articles):
69
  """
70
  Analyzes sentiment of Bitcoin news articles using TextBlob.
71
  """
72
+ sentiments = [TextBlob(article["title"]).sentiment.polarity for article in articles]
 
 
 
 
 
 
 
73
  avg_sentiment = np.mean(sentiments) if sentiments else 0
74
  sentiment_label = "Positive 😊" if avg_sentiment > 0 else "Negative 😡" if avg_sentiment < 0 else "Neutral 😐"
75
+ keywords = list(set([word for article in articles for word in article["title"].split()[:5]]))
76
+ return {"sentiment_score": avg_sentiment, "sentiment_label": sentiment_label, "keywords": keywords}
77
 
 
78
 
79
+ ### 🔹 3. Get BTC Market Insights ###
 
80
  @tool
81
  def btc_market_insights():
82
  """
83
  Fetch BTC price, historical trends, moving averages, and Fear & Greed Index.
84
  """
85
+ # Fetch current BTC price
86
+ price_url = "https://api.coingecko.com/api/v3/simple/price"
87
+ price_data = fetch_data(price_url, {"ids": "bitcoin", "vs_currencies": "usd", "include_24hr_change": "true"})
88
+ btc_price = price_data["bitcoin"]["usd"]
89
+ btc_change = price_data["bitcoin"]["usd_24h_change"]
90
+
91
+ # Fetch historical price data (1 year)
92
+ hist_url = "https://api.coingecko.com/api/v3/coins/bitcoin/market_chart"
93
+ hist_data = fetch_data(hist_url, {"vs_currency": "usd", "days": "365", "interval": "minute"})
94
+ prices = [entry[1] for entry in hist_data.get("prices", [])]
95
+
96
+ # Compute moving averages for different timeframes
97
+ ma_5m = compute_moving_average(prices, 1) # 5-minute
98
+ ma_1h = compute_moving_average(prices, 12) # 1-hour
99
+ ma_1d = compute_moving_average(prices, 24) # 1-day
100
+ ma_7d = compute_moving_average(prices, 168) # 7-day
101
+ ma_1m = compute_moving_average(prices, 720) # 1-month
102
+ ma_1y = compute_moving_average(prices, 8760) # 1-year
103
+
104
+ # Fetch Fear & Greed Index
105
+ fgi_url = "https://api.alternative.me/fng/"
106
+ fgi_data = fetch_data(fgi_url)
107
+ fear_greed = fgi_data["data"][0]["value"]
108
+ fgi_text = fgi_data["data"][0]["value_classification"]
109
+
110
+ return {
111
+ "price": btc_price,
112
+ "24h_change": btc_change,
113
+ "ma_5m": ma_5m,
114
+ "ma_1h": ma_1h,
115
+ "ma_1d": ma_1d,
116
+ "ma_7d": ma_7d,
117
+ "ma_1m": ma_1m,
118
+ "ma_1y": ma_1y,
119
+ "fear_greed": fear_greed,
120
+ "fgi_text": fgi_text
121
+ }
 
 
 
 
 
 
122
 
123
 
124
  ### 🔹 4. Make Buy/Sell/HODL Decision ###
 
126
  def btc_decision(news_analysis, market_insights):
127
  """
128
  Aggregates news sentiment & market insights to suggest Buy, Sell, or HODL.
 
129
  """
130
  sentiment_score = news_analysis["sentiment_score"]
131
  fgi = int(market_insights["fear_greed"])
132
  btc_price = market_insights["price"]
133
 
134
+ # Moving averages for different timeframes
135
  ma_5m = market_insights["ma_5m"]
136
  ma_1h = market_insights["ma_1h"]
137
  ma_1d = market_insights["ma_1d"]
 
139
  ma_1m = market_insights["ma_1m"]
140
  ma_1y = market_insights["ma_1y"]
141
 
142
+ # Decision template
143
  decision = {
144
  "5m-1H": "HODL 🤔",
145
  "1D": "HODL 🤔",
 
148
  "1Y": "HODL 🤔"
149
  }
150
 
151
+ # Decision rules for each timeframe
152
+ def make_decision(timeframe, ma, price, sentiment, fear_greed):
153
+ if price > ma and fear_greed < 40 and sentiment > 0:
154
+ decision[timeframe] = "BUY 🚀"
155
+ elif price < ma and fear_greed > 60 and sentiment < 0:
156
+ decision[timeframe] = "SELL 📉"
157
+ return decision[timeframe]
158
+
159
+ decision["5m-1H"] = make_decision("5m-1H", ma_5m, btc_price, sentiment_score, fgi)
160
+ decision["1D"] = make_decision("1D", ma_1d, btc_price, sentiment_score, fgi)
161
+ decision["7D"] = make_decision("7D", ma_7d, btc_price, sentiment_score, fgi)
162
+ decision["1M"] = make_decision("1M", ma_1m, btc_price, sentiment_score, fgi)
 
 
 
 
 
 
 
 
 
 
163
 
164
  return decision
165
 
166
 
167
+ # --- Agent Setup ---
168
  agent = CodeAgent(
169
  model=model,
170
  tools=[final_answer, fetch_btc_news, analyze_btc_news, btc_market_insights, btc_decision],
 
173
  prompt_templates=prompt_templates
174
  )
175
 
176
+ # --- Launch UI ---
177
  GradioUI(agent).launch()