File size: 6,839 Bytes
f63d7fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# modules/api_clients.py
import os
import aiohttp
import asyncio
from dotenv import load_dotenv
from twelvedata_api import TwelveDataAPI

# Load environment variables
load_dotenv()

# API Keys
ALPHA_VANTAGE_API_KEY = os.getenv("ALPHA_VANTAGE_API_KEY")
NEWS_API_KEY = os.getenv("NEWS_API_KEY")
MARKETAUX_API_KEY = os.getenv("MARKETAUX_API_KEY")
TWELVEDATA_API_KEY = os.getenv("TWELVEDATA_API_KEY")

# Initialize TwelveDataAPI for reuse
td_api = TwelveDataAPI(TWELVEDATA_API_KEY)

class AlphaVantageClient:
    """Client for interacting with the Alpha Vantage API"""
    BASE_URL = "https://www.alphavantage.co/query"
    
    @staticmethod
    async def get_company_overview(symbol):
        """Get company overview information"""
        params = {
            'function': 'OVERVIEW',
            'symbol': symbol,
            'apikey': ALPHA_VANTAGE_API_KEY
        }
        async with aiohttp.ClientSession() as session:
            async with session.get(AlphaVantageClient.BASE_URL, params=params) as response:
                return await response.json()
    
    @staticmethod
    async def get_income_statement(symbol):
        """Get company income statement"""
        params = {
            'function': 'INCOME_STATEMENT',
            'symbol': symbol,
            'apikey': ALPHA_VANTAGE_API_KEY
        }
        async with aiohttp.ClientSession() as session:
            async with session.get(AlphaVantageClient.BASE_URL, params=params) as response:
                return await response.json()
    
    @staticmethod
    async def get_balance_sheet(symbol):
        """Get company balance sheet"""
        params = {
            'function': 'BALANCE_SHEET',
            'symbol': symbol,
            'apikey': ALPHA_VANTAGE_API_KEY
        }
        async with aiohttp.ClientSession() as session:
            async with session.get(AlphaVantageClient.BASE_URL, params=params) as response:
                return await response.json()
    
    @staticmethod
    async def get_cash_flow(symbol):
        """Get company cash flow statement"""
        params = {
            'function': 'CASH_FLOW',
            'symbol': symbol,
            'apikey': ALPHA_VANTAGE_API_KEY
        }
        async with aiohttp.ClientSession() as session:
            async with session.get(AlphaVantageClient.BASE_URL, params=params) as response:
                return await response.json()
    
    @staticmethod
    async def get_news_sentiment(symbol):
        """Get news sentiment for a company"""
        params = {
            'function': 'NEWS_SENTIMENT',
            'tickers': symbol,
            'apikey': ALPHA_VANTAGE_API_KEY
        }
        async with aiohttp.ClientSession() as session:
            async with session.get(AlphaVantageClient.BASE_URL, params=params) as response:
                return await response.json()
                
    @staticmethod
    async def get_global_quote(symbol):
        """Get real-time quote information for a company"""
        params = {
            'function': 'GLOBAL_QUOTE',
            'symbol': symbol,
            'apikey': ALPHA_VANTAGE_API_KEY
        }
        async with aiohttp.ClientSession() as session:
            async with session.get(AlphaVantageClient.BASE_URL, params=params) as response:
                return await response.json()

class NewsAPIClient:
    """Client for interacting with the NewsAPI"""
    BASE_URL = "https://newsapi.org/v2/everything"
    
    @staticmethod
    async def get_company_news(company_name, days=7):
        """Get news about a specific company from the last N days"""
        params = {
            'q': company_name,
            'sortBy': 'publishedAt',
            'language': 'en',
            'pageSize': 25,
            'apiKey': NEWS_API_KEY
        }
        async with aiohttp.ClientSession() as session:
            async with session.get(NewsAPIClient.BASE_URL, params=params) as response:
                return await response.json()
    
    @staticmethod
    async def get_market_news(days=1):
        """Get general financial market news from the last N days"""
        params = {
            'q': 'stock market OR finance OR investing OR economy',
            'sortBy': 'publishedAt',
            'language': 'en',
            'pageSize': 30,
            'apiKey': NEWS_API_KEY
        }
        async with aiohttp.ClientSession() as session:
            async with session.get(NewsAPIClient.BASE_URL, params=params) as response:
                return await response.json()

class MarketauxClient:
    """Client for interacting with the Marketaux Financial News API"""
    BASE_URL = "https://api.marketaux.com/v1/news/all"
    
    @staticmethod
    async def get_company_news(symbol, days=7):
        """Get news about a specific company symbol from the last N days"""
        params = {
            'symbols': symbol,
            'filter_entities': 'true',
            'language': 'en',
            'api_token': MARKETAUX_API_KEY
        }
        async with aiohttp.ClientSession() as session:
            async with session.get(MarketauxClient.BASE_URL, params=params) as response:
                return await response.json()
    
    @staticmethod
    async def get_market_news(days=1):
        """Get general financial market news from the last N days"""
        params = {
            'industries': 'Financial Services,Technology',
            'language': 'en',
            'limit': 30,
            'api_token': MARKETAUX_API_KEY
        }
        async with aiohttp.ClientSession() as session:
            async with session.get(MarketauxClient.BASE_URL, params=params) as response:
                return await response.json()

# Helper functions that utilize TwelveDataAPI for price data
def get_price_history(symbol, time_period='1_year'):
    """
    Get price history using TwelveDataAPI (non-async function)
    This reuses the existing TwelveDataAPI implementation
    """
    # Map of time periods to appropriate parameters for TwelveDataAPI
    logic_map = {
        'intraday': {'interval': '15min', 'outputsize': 120}, 
        '1_week': {'interval': '1h', 'outputsize': 40}, 
        '1_month': {'interval': '1day', 'outputsize': 22},
        '3_months': {'interval': '1day', 'outputsize': 66},
        '6_months': {'interval': '1day', 'outputsize': 120},
        'year_to_date': {'interval': '1day', 'outputsize': 120},
        '1_year': {'interval': '1week', 'outputsize': 52},
        '5_years': {'interval': '1month', 'outputsize': 60},
        'max': {'interval': '1month', 'outputsize': 120}
    }
    
    params = logic_map.get(time_period)
    if not params:
        return {"error": f"Khoảng thời gian '{time_period}' không hợp lệ."}
    
    # Call TwelveDataAPI synchronously (it's already optimized internally)
    return td_api.get_time_series(symbol=symbol, **params)