Hello all
I am reaching out to try to solve an API problem, i am trying to retrieve a unique list of RIC/CUSIPS for multiple indexes using Chains. However i am getting different errors for different methods, could you help me with understanding of the feasibility of retrieving data through such methods?
import lseg.data as ld
import pandas as pd
from lseg.data.discovery import Chain
import datetime
from IPython.display import display, clear_output
from lseg.data.content import symbol_conversion
try:
ld.open_session()
print("Session opened successfully.")
except Exception as e:
print(f"Error opening session: {e}")
exit(1) # Exit if the session cannot be established
Retrieve data for each index
NASDAQ=Chain("0#.IXIC")
SP500=Chain("0#.SPX")
NYSE = ld.get_data(NYSE, fields=['TR.REVENUE']) # NYSE
NASDAQ = ld.get_data(NASDAQ, fields=['TR.REVENUE']) # NASDAQ
SP500 = ld.get_data(SP500, fields=['TR.REVENUE']) # S&P 500
DOWJONES = ld.get_data(DOWJONES, fields=['TR.REVENUE']) # Dow Jones
csv_file_path=r"xxxx"
Combine all data into a single DataFrame
rics_df = pd.concat([NYSE, NASDAQ, SP500, DOWJONES], ignore_index=True)
Remove duplicates
rics_df.drop_duplicates(subset=['CUSIP'], inplace=True)
Convert to list
rics = rics_df['CUSIP'].tolist()
Extract the first two and last two RICs
first_two = rics[:2]
last_two = rics[-2:]
Print the number of items and the first and last two RICs
print(f"Number of items in the rics list: {len(rics)}")
print(f"First two items: {first_two}")
print(f"Last two items: {last_two}")
#Save the complete DataFrame as a CSV file at the end
rics_df.to_csv(csv_file_path, index=False)
print(f"Final data saved successfully to {csv_file_path}")
2nd try :
import pandas as pd
import lseg.data as ld
from lseg.data.discovery import Chain
Set the output CSV file pathInitialize chains
NYSE = Chain("0#.NYA")
NASDAQ = Chain("0#.IXIC")
SP500 = Chain("0#.SPX")
DOWJONES = Chain("0#.DJA")
Function to fetch chain constituents
def fetch_chain_constituents(chain):
# If the Chain object is iterable
constituents = []
for item in chain: # Assuming Chain
is iterable
constituents.append(item)
return constituents
Fetch chain constituents
nyse_constituents = fetch_chain_constituents(NYSE)
nasdaq_constituents = fetch_chain_constituents(NASDAQ)
sp500_constituents = fetch_chain_constituents(SP500)
dowjones_constituents = fetch_chain_constituents(DOWJONES)
Combine all constituent symbols into a single list
all_constituents = (
nyse_constituents +
nasdaq_constituents +
sp500_constituents +
dowjones_constituents
)
Create a DataFrame from the constituents
stocks_df = pd.DataFrame(all_constituents, columns=["Symbol"])
Save to CSV
stocks_df.to_csv
print(f"Stocks data saved successfully to {csv_file_path}")
3rd try:
Define the chains
NYSE = Chain("0#.NYA")
NASDAQ = Chain("0#.IXIC")
SP500 = Chain("0#.SPX")
DOWJONES = Chain("0#.DJA")
Fetch data from chains (example assumes Chain is iterable)
def fetch_chain_constituents(chain):
constituents = [item for item in chain] # If Chain is iterable
return constituents
try:
nyse_constituents = fetch_chain_constituents(NYSE)
nasdaq_constituents = fetch_chain_constituents(NASDAQ)
sp500_constituents = fetch_chain_constituents(SP500)
dowjones_constituents = fetch_chain_constituents(DOWJONES)
all_constituents = (
nyse_constituents +
nasdaq_constituents +
sp500_constituents +
dowjones_constituents
)
# Convert to DataFrame and save
stocks_df = pd.DataFrame(all_constituents, columns=["Symbol"])
csv_file_path = r"C:\Users\r_cas\OneDrive\Ambiente de Trabalho\green\thesis\data_and_code\stocks_data.csv"
stocks_df.to_csv(csv_file_path, index=False)
print(f"Stocks data saved to {csv_file_path}")
except Exception as e:
print(f"Error fetching data: {e}")
Close the session when done
ld.close_session()