zerito commited on
Commit
327f60d
·
verified ·
1 Parent(s): 502af5c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -22
app.py CHANGED
@@ -2,7 +2,9 @@ from smolagents import CodeAgent, HfApiModel, load_tool, tool
2
  import requests
3
  from tools.final_answer import FinalAnswerTool
4
  from Gradio_UI import GradioUI
 
5
 
 
6
  @tool
7
  def get_btc_price() -> str:
8
  """Fetches the current Bitcoin price in USD using the CoinGecko API."""
@@ -16,26 +18,33 @@ def get_btc_price() -> str:
16
  return '{"error": "Bitcoin price not found"}'
17
  return f"The current Bitcoin price is ${price:.2f} USD."
18
 
19
- @tool
20
- def get_fear_and_greed_index() -> str:
21
- """Fetches the current Fear and Greed Index."""
22
- url = "https://api.alternative.me/fng/?limit=1"
23
  response = requests.get(url)
24
- if response.status_code != 200:
25
- return '{"error": "Failed to fetch Fear and Greed Index"}'
26
  data = response.json()
27
- if not data or 'data' not in data[0]:
28
- return '{"error": "Fear and Greed Index data not found"}'
29
-
30
- index_value = data[0]['value']
31
- index_description = data[0]['value_classification']
32
-
33
- return f"The current Fear and Greed Index is {index_value} ({index_description})."
 
 
 
 
 
 
 
 
 
 
34
 
35
  # Initialize the FinalAnswerTool
36
  final_answer = FinalAnswerTool()
37
 
38
- # Initialize the model
39
  model = HfApiModel(
40
  max_tokens=2096,
41
  temperature=0.5,
@@ -43,22 +52,51 @@ model = HfApiModel(
43
  custom_role_conversions=None,
44
  )
45
 
46
- # Load additional tools if needed
47
- # For example, to load an image generation tool:
48
- # image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
  # Create the agent
51
  agent = CodeAgent(
52
  model=model,
53
- tools=[get_btc_price, get_fear_and_greed_index, final_answer], # Added the Fear and Greed tool here
54
  max_steps=6,
55
  verbosity_level=1,
56
  grammar=None,
57
  planning_interval=None,
58
- name=None,
59
- description=None,
60
- prompt_templates=None # Set to None if not using prompt templates
61
  )
62
 
63
- # Launch the Gradio interface
64
  GradioUI(agent).launch()
 
2
  import requests
3
  from tools.final_answer import FinalAnswerTool
4
  from Gradio_UI import GradioUI
5
+ import numpy as np
6
 
7
+ # Tool to fetch Bitcoin price from CoinGecko
8
  @tool
9
  def get_btc_price() -> str:
10
  """Fetches the current Bitcoin price in USD using the CoinGecko API."""
 
18
  return '{"error": "Bitcoin price not found"}'
19
  return f"The current Bitcoin price is ${price:.2f} USD."
20
 
21
+ # Fetch Bitcoin price data from CoinGecko for calculating fear and greed
22
+ def fetch_btc_price_data():
23
+ url = 'https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=usd&days=30'
 
24
  response = requests.get(url)
 
 
25
  data = response.json()
26
+ prices = [item[1] for item in data['prices']]
27
+ volumes = [item[1] for item in data['total_volumes']]
28
+ return np.array(prices), np.array(volumes)
29
+
30
+ # Function to calculate price volatility
31
+ def calculate_volatility(prices):
32
+ returns = np.diff(prices) / prices[:-1]
33
+ volatility = np.std(returns) * np.sqrt(len(returns))
34
+ return volatility
35
+
36
+ # Function to calculate trading volume average
37
+ def calculate_volume_average(volumes):
38
+ return np.mean(volumes)
39
+
40
+ # Function to normalize values to 0-100 range
41
+ def normalize(value, min_value, max_value):
42
+ return (value - min_value) / (max_value - min_value) * 100
43
 
44
  # Initialize the FinalAnswerTool
45
  final_answer = FinalAnswerTool()
46
 
47
+ # Initialize the model for the agent
48
  model = HfApiModel(
49
  max_tokens=2096,
50
  temperature=0.5,
 
52
  custom_role_conversions=None,
53
  )
54
 
55
+ # Creating the agent to run the calculations
56
+ @tool
57
+ def calculate_fear_and_greed() -> str:
58
+ # Fetch BTC price and volume data
59
+ prices, volumes = fetch_btc_price_data()
60
+
61
+ # Calculate metrics
62
+ volatility = calculate_volatility(prices)
63
+ volume_avg = calculate_volume_average(volumes)
64
+
65
+ # Normalize the values
66
+ volatility_normalized = normalize(volatility, 0, 0.1)
67
+ volume_normalized = normalize(volume_avg, 0, 1000000000)
68
+
69
+ # Calculate sub-indices
70
+ volatility_index = 100 - volatility_normalized
71
+ volume_index = volume_normalized
72
+
73
+ # Aggregate Fear and Greed Index
74
+ fear_greed_index = np.mean([volatility_index, volume_index])
75
+
76
+ # Interpretation of the Fear and Greed Index
77
+ if fear_greed_index <= 24:
78
+ sentiment = "Extreme Fear"
79
+ elif 25 <= fear_greed_index <= 49:
80
+ sentiment = "Fear"
81
+ elif 50 <= fear_greed_index <= 74:
82
+ sentiment = "Neutral"
83
+ elif 75 <= fear_greed_index <= 100:
84
+ sentiment = "Greed"
85
+
86
+ return f"Fear and Greed Index: {fear_greed_index:.2f} ({sentiment})"
87
 
88
  # Create the agent
89
  agent = CodeAgent(
90
  model=model,
91
+ tools=[get_btc_price, final_answer, calculate_fear_and_greed],
92
  max_steps=6,
93
  verbosity_level=1,
94
  grammar=None,
95
  planning_interval=None,
96
+ name="Crypto Sentiment Agent",
97
+ description="An agent that fetches BTC data and calculates the Fear and Greed index.",
98
+ prompt_templates=None
99
  )
100
 
101
+ # Launch the Gradio interface for interaction
102
  GradioUI(agent).launch()