riu-rd commited on
Commit
72162a4
·
verified ·
1 Parent(s): 2d8595b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -7
app.py CHANGED
@@ -4,19 +4,72 @@ import requests
4
  import pytz
5
  import yaml
6
  from tools.final_answer import FinalAnswerTool
 
7
 
8
  from Gradio_UI import GradioUI
9
 
10
  # Below is an example of a tool that does nothing. Amaze us with your creativity !
11
  @tool
12
- def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
13
- #Keep this format for the description / args / args description but feel free to modify the tool
14
- """A tool that does nothing yet
 
15
  Args:
16
- arg1: the first argument
17
- arg2: the second argument
18
  """
19
- return "What magic will you build ?"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  @tool
22
  def get_current_time_in_timezone(timezone: str) -> str:
@@ -57,7 +110,7 @@ with open("prompts.yaml", 'r') as stream:
57
 
58
  agent = CodeAgent(
59
  model=model,
60
- tools=[final_answer, image_generation_tool, get_current_time_in_timezone, search_tool], ## add your tools here (don't remove final answer)
61
  max_steps=6,
62
  verbosity_level=1,
63
  grammar=None,
 
4
  import pytz
5
  import yaml
6
  from tools.final_answer import FinalAnswerTool
7
+ import pandas as pd
8
 
9
  from Gradio_UI import GradioUI
10
 
11
  # Below is an example of a tool that does nothing. Amaze us with your creativity !
12
  @tool
13
+ def get_stock_signal(symbol: str, interval: str) -> str:
14
+ """
15
+ Retrieves intraday stock data for the given symbol using the Alpha Vantage API, computes exponential moving averages (EMA),
16
+ and generates a trading signal based on an EMA crossover strategy.
17
  Args:
18
+ symbol (str): Stock symbol to analyze (e.g., "AAPL", "GOOG", "MSFT", "TSLA").
19
+ interval (str): Time interval between data points (e.g., "1min", "5min", "15min", "60min").
20
  """
21
+ API_KEY = 'RG9XKRIYBL2EV3V3'
22
+
23
+ url = (
24
+ f'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY'
25
+ f'&symbol={symbol}&interval={interval}&outputsize=full&apikey={API_KEY}'
26
+ )
27
+
28
+ response = requests.get(url)
29
+ data = response.json()
30
+
31
+ time_series_key = f"Time Series ({interval})"
32
+ time_series = data.get(time_series_key, {})
33
+ if not time_series:
34
+ raise ValueError("Failed to retrieve data. Check your API key, symbol, and interval.")
35
+
36
+ # Create a DataFrame from the time series data
37
+ df = pd.DataFrame.from_dict(time_series, orient='index')
38
+ df = df.rename(columns={
39
+ '1. open': 'open',
40
+ '2. high': 'high',
41
+ '3. low': 'low',
42
+ '4. close': 'close',
43
+ '5. volume': 'volume'
44
+ })
45
+ df.index = pd.to_datetime(df.index)
46
+ df = df.sort_index()
47
+ df['close'] = pd.to_numeric(df['close'])
48
+
49
+ # Ensure there is enough data to calculate the EMAs
50
+ if len(df) < 26:
51
+ return f"Insufficient data to calculate the required EMAs for {symbol} at a {interval} interval."
52
+
53
+ # Improved Strategy: Using Exponential Moving Averages (EMA) for a more responsive indicator.
54
+ # Short-term EMA (e.g., 12 periods) and Long-term EMA (e.g., 26 periods)
55
+ df['EMA_short'] = df['close'].ewm(span=12, adjust=False).mean()
56
+ df['EMA_long'] = df['close'].ewm(span=26, adjust=False).mean()
57
+
58
+ # Get the latest two data points to check for a crossover
59
+ latest = df.iloc[-1]
60
+ prev = df.iloc[-2]
61
+
62
+ # Determine buy/sell signal based on EMA crossover
63
+ signal = "Hold"
64
+ if prev['EMA_short'] < prev['EMA_long'] and latest['EMA_short'] > latest['EMA_long']:
65
+ signal = "Buy"
66
+ elif prev['EMA_short'] > prev['EMA_long'] and latest['EMA_short'] < latest['EMA_long']:
67
+ signal = "Sell"
68
+
69
+ # Return a complete sentence with the decision
70
+ decision = (f"The latest closing price for {symbol.upper()} at a {interval} interval is "
71
+ f"${latest['close']:.2f}, and the recommended action is to {signal}.")
72
+ return decision
73
 
74
  @tool
75
  def get_current_time_in_timezone(timezone: str) -> str:
 
110
 
111
  agent = CodeAgent(
112
  model=model,
113
+ tools=[final_answer, get_stock_signal, image_generation_tool, get_current_time_in_timezone, search_tool], ## add your tools here (don't remove final answer)
114
  max_steps=6,
115
  verbosity_level=1,
116
  grammar=None,