File size: 2,218 Bytes
1a2a035
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from alpaca_trade_api import REST
import os
from dotenv import load_dotenv


class AlpacaNewsFetcher:
    """

    A class for fetching news articles related to a specific stock from Alpaca API.



    Attributes:

    - api_key (str): Alpaca API key for authentication.

    - api_secret (str): Alpaca API secret for authentication.

    - rest_client (alpaca_trade_api.REST): Alpaca REST API client.

    """

    def __init__(self, api_key, api_secret):
        """

        Initializes the AlpacaNewsFetcher object.



        Args:

        - api_key (str): Alpaca API key for authentication.

        - api_secret (str): Alpaca API secret for authentication.

        """
        self.api_key = api_key
        self.api_secret = api_secret
        self.rest_client = REST(api_key, api_secret)

        load_dotenv()
        self.no_of_newsarticles_to_fetch = os.environ["NO_OF_NEWSARTICLES_TO_FETCH"]

    def fetch_news(self, symbol, start_date, end_date):
        """

        Fetches news articles for a given stock symbol within a specified date range.



        Args:

        - symbol (str): Stock symbol for which news articles are to be fetched (e.g., "AAPL").

        - start_date (str): Start date of the range in the format "YYYY-MM-DD".

        - end_date (str): End date of the range in the format "YYYY-MM-DD".



        Returns:

        - list: A list of dictionaries containing relevant information for each news article.

        """
        news_articles = self.rest_client.get_news(symbol, start_date, end_date, limit=self.no_of_newsarticles_to_fetch )
        formatted_news = []
        print("-----------------------------------------------------")
        print(len(news_articles))
        print("-----------------------------------------------------")

        for article in news_articles:
            summary = article.summary
            title = article.headline
            timestamp = article.created_at

            relevant_info = {
                'timestamp': timestamp,
                'title': title,
                'summary': summary
            }

            formatted_news.append(relevant_info)

        return formatted_news