The code does not run
The last part of this code does not run and I got errors like timeout, could you help me?
#Purpose: Download and install packages required for downloading data
import eikon as ek
import pandas as pd
import sklearn as sk
import numpy as np
import math
from datetime import datetime
from functools import reduce
#Setting Up the user key to acces Eikon data
ek.set_app_key('YOURAPIKEYGOESHERE')
#Purpose: Declare parameters for downloding price index data
#The indexes array contains the RIC of all of the equity indexes we wish to analyze
indexes = ['.SPX', '.STOXX','.SSMI','.FTSE','.SZSC','.TOPX','.HSI','.GSPTSE','.TRXFLDAUP','.MXX','.TRXFLDGEPU','.TRXFLDGEPU'] # United States, Eurozone, Switzerland, China, Japan, Hong Kong, Canada, Australia, Mexico, Emerging Markets
start_date = '20150206' #start_date parameter is a string in that encodes the first date that we wish to download data in the format YYYYMMDD
end_date = '20210216' #end_date parameter is a string in that encodes the last date that we wish to download data in the format YYYYMMDD
concepts = ['TR.CLOSEPRICE.date', 'TR.CLOSEPRICE'] #Concepts is an array that contains the fields that we wish to download
parametros = {'SDate':start_date, 'EDate': end_date, 'CH':'Fd', 'RH':'date', 'Frq':'D'} #Other function parameters
#Purpose: With this chunk of code, we create a pandas dataframe that cointains the following columns:
#Instrument: whose values are one of the elements in the indexes array.
#Date: That cointains the year, month, day and time that we extract the observation
#Close price: The closing price of the instrument.
#Return: This column contains the percentage rate of change between adjacent observations of the closing price.
index_price, err = ek.get_data(
instruments = indexes,
fields = concepts,
parameters = parametros)
index_price["Return"] = index_price.groupby("Instrument")["Close Price"].pct_change()
#Purpose: Create a new variable with index names in new format to get financial data of constituents
added_string = "0#"
indexes_priceindex = [added_string + s for s in indexes] #indexes_priceindex is an array that cointains the newly formated equity index names
#Purpose: Create a list of data frames that contains a pandas dataframe the financial data of index constituents at every point of in the time period established
empresas_indice = [] #empresas_indice is an array,in which every element is a pandas dataframe that cointains df
#df is a pandas nxm data frame organized in a tidy format, in which every row is an observation and every column is a feacture
#In this particular case,every row is an index constituent at a given point in time (within the period of time stablished in the parameters) and every column is the value of the financial feature. You can see descriptions on the right side of each feature downloaded or calculated
for i in indexes_priceindex:
df_tmp, err = ek.get_data(i,"TR.RIC")
instruments = df_tmp['RIC'].tolist()
concepts = ['TR.CLOSEPRICE.date', #Date
'TR.CLOSEPRICE', #Price
'TR.CompanyMarketCap', #Market Capitalization
'TR.FwdPE', #Forward PE
'TR.DividendYield', #Dividend Yield
'TR.EVToEBITDA', #EV to EBITDA
'TR.OrganicSalesGrowthActValue', #sales growth
'TR.F.DebtTot', #Total Debt
'TR.F.ComStockBuybackNet', #Buybacks
'TR.ShortInterest', #Short interest
'TR.Volume', # Volume
'TR.GICSSector',#Sector (for market concentration score)
"TR.PriceTargetMedian", #Median Target Price of consulted analysts
'TR.WACCBeta', #Beta (for ciclicity score)
'TR.ROEActValue', #Return on equity
'TR.RepEPSAvgRevisionPct',#Average revision on Earnings per share monthly (%)
'TR.EpsRepSmartEstF24MtoF12MGrowth' #EPS Growth (forward) (%)
]
df,err = ek.get_data(instruments,concepts, parametros)
df["Weight"] = df["Company Market Cap"]/df.groupby('Date')['Company Market Cap'].transform('sum') #Market cap weight of the index constituent
df["Daily Return"] = df.groupby("Instrument")["Close Price"].pct_change() #Percentage rate of change between adjacent observations of the closing price.
df["Price Momentum 1M"] = df.groupby("Instrument")["Close Price"].pct_change(periods = 21) # Price momentum 1m; Percentage rate of change between 1 month apart observations of the closing price.
df["Price Momentum 3M"] = df.groupby("Instrument")["Close Price"].pct_change(periods = 63) # Price momentum 3m; Percentage rate of change between 3 month apart observations of the closing price.
df["Price Momentum 6M"] = df.groupby("Instrument")["Close Price"].pct_change(periods = 126) #Price momentum 6m; Percentage rate of change between 6 month apart observations of the closing price.
df["Market Concentration"] = df.groupby(["Date","GICS Sector Name"])['Company Market Cap'].transform(lambda x: (x - x.mean()) / x.std()) #Market concentration score
df["Earnings Yield"] = 1/df["Forward P/E (Daily Time Series Ratio)"] #Earnings yield
df["Sigma 1M"] = df.groupby("Instrument")["Daily Return"].rolling(window = 21).std().apply(lambda x: x*math.sqrt(252)).reset_index(level=0, drop=True) #Rolling 1 month volatility
df["Sigma 3M"] = df.groupby("Instrument")["Daily Return"].rolling(window = 63).std().apply(lambda x: x*math.sqrt(252)).reset_index(level=0, drop=True) #Rolling 3 month volatility
df["Sigma 6M"] = df.groupby("Instrument")["Daily Return"].rolling(window = 126).std().apply(lambda x: x*math.sqrt(252)).reset_index(level=0, drop=True) #Rolling 6 month volatility
empresas_indice.append(df)
Best Answer
-
In your for loop:
for i in indexes_priceindex:
df_tmp, err = ek.get_data(i,"TR.RIC")
instruments = df_tmp['RIC'].tolist()
print(i + ' ' + str(len(instruments))) # I added this line of codeYou get a large number of instruments for each get_data() call. You can see the number of instruments in this output:
0#.SPX 505
0#.STOXX 600
0#.SSMI 20
0#.FTSE 101
0#.SZSC 2414
0#.TOPX 2191
0#.HSI 52
0#.GSPTSE 219
0#.TRXFLDAUP 359
0#.MXX 36
0#.TRXFLDGEPU 2681
0#.TRXFLDGEPU 2681Then you request the daily data for 6 years (around 1500 data points per instrument).
For example, 0#.SZSC has 2414 instruments, each instrument expects 1500 data points, so the total is 3,621,000 data points in a single API call.
The massive amount of data in a single API is not practical for Eikon Data API.
I suggest you review the API limitation guideline at https://developers.refinitiv.com/en/api-catalog/eikon/eikon-data-api/documentation
0
Categories
- All Categories
- 6 AHS
- 39 Alpha
- 161 App Studio
- 4 Block Chain
- 4 Bot Platform
- 16 Connected Risk APIs
- 47 Data Fusion
- 30 Data Model Discovery
- 608 Datastream
- 1.3K DSS
- 577 Eikon COM
- 4.9K Eikon Data APIs
- 7 Electronic Trading
- Generic FIX
- 7 Local Bank Node API
- Trading API
- 2.7K Elektron
- 1.3K EMA
- 236 ETA
- 519 WebSocket API
- 33 FX Venues
- 10 FX Market Data
- 1 FX Post Trade
- 1 FX Trading - Matching
- 12 FX Trading – RFQ Maker
- 5 Intelligent Tagging
- 2 Legal One
- 20 Messenger Bot
- 2 Messenger Side by Side
- 9 ONESOURCE
- 7 Indirect Tax
- 59 Open Calais
- 264 Open PermID
- 39 Entity Search
- 2 Org ID
- PAM
- PAM - Logging
- 8.4K Private Comments
- 6 Product Insight
- Project Tracking
- ProView
- ProView Internal
- 20 RDMS
- 1.4K Refinitiv Data Platform
- 370 Refinitiv Data Platform Libraries
- 3 Refinitiv Due Diligence
- LSEG Due Diligence Portal API
- 3 Refinitiv Due Dilligence Centre
- Rose's Space
- 1.1K Screening
- 18 Qual-ID API
- 13 Screening Deployed
- 23 Screening Online
- 10 World-Check Customer Risk Screener
- 990 World-Check One
- 44 World-Check One Zero Footprint
- 45 Side by Side Integration API
- Test Space
- 3 Thomson One Smart
- 1.2K TR Internal
- Global Hackathon 2015
- 2 Specialists Who Code
- 10 TR Knowledge Graph
- 150 Transactions
- 142 REDI API
- 1.7K TREP APIs
- 4 CAT
- 21 DACS Station
- 117 Open DACS
- 1.1K RFA
- 103 UPA
- 172 TREP Infrastructure
- 224 TRKD
- 886 TRTH
- 5 Velocity Analytics
- 5 Wealth Management Web Services
- 60 Workspace SDK
- 9 Element Framework
- 5 Grid
- 13 World-Check Data File
- Yield Book Analytics
- 46 中文论坛