Untitled
unknown
python
2 years ago
2.3 kB
6
Indexable
import requests import csv # Define the URL and parameters url_template = 'https://www.settrade.com/api/set/stock/{stockName}/financialstatement' account_type = 'income_statement' fs_type = 'company' language = 'th' account_code = '480100' # Define the periods to retrieve data for periods = ['Q1', '6M', '9M', 'YE'] # Define a list of stock names stock_names = ['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'FB'] # Open a new CSV file for writing with open('output.csv', 'w', newline='') as csvfile: # Define the headers for the CSV file headers = ['stockName', 'period', 'accountCode', 'amount'] # Create a CSV writer object writer = csv.DictWriter(csvfile, fieldnames=headers) # Write the headers to the CSV file writer.writeheader() # Loop over the list of stock names and periods for stock_name in stock_names: for period in periods: # Construct the full URL with input variables full_url = url_template.format(stockName=stock_name) + f'?accountType={account_type}&fsType={fs_type}&period={period}_{year}&language={language}' # Send a GET request to the API response = requests.get(full_url) # Check that the request was successful if response.status_code == 200: # Parse the API response into a dictionary data = response.json() # Extract the data for account code 480100 amount_data = None for account in data['accounts']: if account['accountCode'] == account_code: amount_data = account['amount'] # Write the data for account code 480100 to the CSV file writer.writerow({ 'stockName': stock_name, 'period': period, 'accountCode': account_code, 'amount': amount_data }) # Print a success message for each stock print(f'{stock_name} {period} data added to CSV file.') else: # Print an error message for each stock print(f'Error retrieving {stock_name} {period} data. API request failed with status code {response.status_code}.')
Editor is loading...