File size: 2,304 Bytes
06ba83e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from agency_swarm.tools import BaseTool
from pydantic import Field
import requests
import pandas as pd
import os

# Define your Alpha Vantage API key as a global constant
ALPHA_VANTAGE_API_KEY = os.getenv("ALPHA_VANTAGE_API_KEY")

class MarketDataRetrievalTool(BaseTool):
    """
    This tool retrieves market data for a given stock symbol using the Alpha Vantage API.
    It returns the data in a format suitable for analysis with pandas.
    """

    symbol: str = Field(
        ..., description="The stock symbol for which to retrieve market data."
    )
    function: str = Field(
        ..., description="The type of data to retrieve (e.g., TIME_SERIES_DAILY, TIME_SERIES_INTRADAY)."
    )
    interval: str = Field(
        None, description="The interval between data points (e.g., 1min, 5min) for intraday data."
    )

    def run(self):
        """
        Retrieves market data for the specified stock symbol and function.
        Returns the data as a pandas DataFrame.
        """
        # Construct the API request URL
        base_url = "https://www.alphavantage.co/query"
        params = {
            "function": self.function,
            "symbol": self.symbol,
            "apikey": ALPHA_VANTAGE_API_KEY
        }
        
        if self.function == "TIME_SERIES_INTRADAY" and self.interval:
            params["interval"] = self.interval

        # Make the API request
        response = requests.get(base_url, params=params)
        data = response.json()

        # Parse the JSON response into a pandas DataFrame
        if self.function == "TIME_SERIES_DAILY":
            time_series_key = "Time Series (Daily)"
        elif self.function == "TIME_SERIES_INTRADAY":
            time_series_key = f"Time Series ({self.interval})"
        else:
            return "Unsupported function type."

        if time_series_key not in data:
            return f"Error retrieving data: {data.get('Error Message', 'Unknown error')}"

        df = pd.DataFrame.from_dict(data[time_series_key], orient='index')
        df.index = pd.to_datetime(df.index)
        df = df.sort_index()

        # Return the data as a pandas DataFrame
        return df

# Example usage:
# tool = MarketDataRetrievalTool(symbol="AAPL", function="TIME_SERIES_DAILY")
# result = tool.run()
# print(result)