Untitled

 avatar
unknown
python
2 years ago
1.7 kB
2
Indexable
import requests
import json

# set the API endpoint URL
url = 'https://www.settrade.com/api/set/stock/{stockName}/financialstatement'

# set the parameters for the API call
stock_names = ['BBL', 'KBANK', 'SCB']
months = ['Q1', '6M', '9M', 'YE']
years = range(2000, 2023)
params = {
    'accountType': 'income_statement',
    'fsType': 'consolidate',
    'language': 'th'
}

# set the headers for the HTTP request to mimic a web browser
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299'
}

# make the API calls and store the responses in a list
responses = []
for stock_name in stock_names:
    for month in months:
        for year in years:
            # substitute the parameters into the URL
            api_url = url.format(stockName=stock_name)
            api_url += f'?period={month}_{year}'
            response = requests.get(api_url, params=params, headers=headers)
            if response.status_code == 200:
                # the API call was successful
                response_dict = {
                    'stock_name': stock_name,
                    'month': month,
                    'year': year,
                    'data': json.loads(response.text)
                }
                responses.append(response_dict)
            else:
                # the API call failed
                print(f'Error: {response.status_code} for {stock_name} {month} {year}')

# save the list of responses to a JSON file
with open('settrade_data.json', 'w', encoding='utf-8') as f:
    json.dump(responses, f, ensure_ascii=False, indent=4)