Untitled

mail@pastecode.io avatar
unknown
python
a year ago
2.4 kB
2
Indexable
Never
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'

# 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', '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
            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'}
            response = requests.get(full_url, headers=headers)

            # 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'] == '480100':
                        amount_data = account['amount']
                        break

                # Write the data to the CSV file
                writer.writerow({
                    'stockName': stock_name,
                    'period': period,
                    '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}.')