import requests
import time
import random
from datetime import datetime, timedelta
import xlrd
def excel_date_to_string(excel_date):
# The Excel base date is 1900-01-01
base_date = datetime(1899, 12, 30)
delta_days = timedelta(days=float(excel_date))
date_string = (base_date + delta_days).strftime("%Y-%m-%d")
return date_string
def make_api_call_with_retry(stock_name, excel_date):
api_keys = [
"6ppmZm9JKpqPLb5JHgNsENMZC6E6ORod",
"cDT6Z0uRbv3KS2ipbYRVhGdhflKHz3f9",
"pQ_3uhxDaH5KNpyZWYV60swl4vCom7Fa",
"ErxKKvFge8coIlOzlmHHe3IgIvU3BRdk"
]
base_url = "https://api.polygon.io/v1/open-close/{}/{}/?adjusted=true&apiKey={}"
# Convert Excel date to string
date_string = excel_date_to_string(excel_date)
# Randomly shuffle the API keys for the first attempt
random.shuffle(api_keys)
for api_key in api_keys:
url = base_url.format(stock_name, date_string, api_key)
try:
response = requests.get(url)
parsed_data = response.json()
high_value = parsed_data['high']
print("API request successful. High value:", high_value)
time.sleep(1) # Add a 1-second delay
return high_value
except Exception as e:
print(f"Failed to make API request for {url}. Error: {e}")
print("All API requests failed!")
return "Failure."
# Example usage with an Excel date (replace "your_excel_file.xlsx" and "A1" with the actual file and cell reference):
excel_file = "your_excel_file.xlsx"
cell_reference = "A1"
# Open the Excel file
workbook = xlrd.open_workbook(excel_file)
sheet = workbook.sheet_by_index(0)
# Get the numeric date from the Excel cell
excel_date = sheet.cell_value(0, 0)
# Example stock name
stock_name = "MSFT"
# Make API call with retry
make_api_call_with_retry(stock_name, excel_date)