61 lines
2.2 KiB
Python
61 lines
2.2 KiB
Python
import os
|
|
import logging
|
|
import json
|
|
import pandas as pd
|
|
from dotenv import load_dotenv
|
|
from src.api.client import Trading212Client
|
|
|
|
logging.basicConfig(level=logging.INFO)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
def fetch_and_save_tickers():
|
|
load_dotenv()
|
|
api_key_id = os.getenv("TRADING212_API_KEY_ID")
|
|
api_key = os.getenv("TRADING212_API_KEY")
|
|
base_url = os.getenv("TRADING212_BASE_URL", "https://demo.trading212.com/api/v0/")
|
|
|
|
if not api_key_id or not api_key:
|
|
logger.error("API Key ID or API Key is missing in .env")
|
|
return
|
|
|
|
client = Trading212Client(api_key_id, api_key, base_url)
|
|
|
|
try:
|
|
logger.info("Fetching available instruments from Trading212...")
|
|
instruments = client.get_instruments()
|
|
|
|
logger.info(f"Retrieved {len(instruments)} instruments.")
|
|
|
|
# Save raw JSON
|
|
with open("available_instruments.json", "w") as f:
|
|
json.dump(instruments, f, indent=4)
|
|
logger.info("Saved raw data to available_instruments.json")
|
|
|
|
# Convert to a DataFrame and save as CSV for easier viewing/filtering
|
|
df = pd.DataFrame(instruments)
|
|
|
|
# Select the most useful columns if they exist
|
|
expected_columns = ['ticker', 'name', 'type', 'currencyCode', 'exchange']
|
|
available_columns = [col for col in expected_columns if col in df.columns]
|
|
|
|
if available_columns:
|
|
df_filtered = df[available_columns]
|
|
|
|
# Print a quick summary of US Equities (which is what Touch & Turn trades)
|
|
if 'type' in df.columns and 'currencyCode' in df.columns:
|
|
us_stocks = df[(df['type'] == 'STOCK') & (df['currencyCode'] == 'USD')]
|
|
logger.info(f"Found {len(us_stocks)} US Stocks.")
|
|
logger.info("\nSample of US Stocks available:")
|
|
print(us_stocks.head(10).to_string(index=False))
|
|
else:
|
|
df_filtered = df
|
|
|
|
df_filtered.to_csv("available_tickers.csv", index=False)
|
|
logger.info("Saved structured list to available_tickers.csv")
|
|
|
|
except Exception as e:
|
|
logger.error(f"Failed to fetch instruments: {e}")
|
|
|
|
if __name__ == "__main__":
|
|
fetch_and_save_tickers()
|