- I am writing a Python script that should take the ISINs of bonds from a CSV file located in the same directory. The task is to load X bonds and plot their YTMs as points on a graph. Bonds with YTMs below certain criteria should be highlighted with a different color. However, the program throws an error because it cannot retrieve data using ISINs and requires RICs, but not every bond has a RIC. How can I solve this issue?
- In addition, the bond portfolio is already set up in Refinitiv using the PAL function. Can I access this portfolio directly and extract the data from there, so I don’t need to keep a separate file with ISINs in the program’s directory?
import eikon as ek
import pandas as pd
import plotly.express as px
from datetime import datetime, timedelta
ek.set_app_key("API_KEY")
1. Read the list of bonds from a file.
It is assumed that the file contains a column 'ISIN'.
If your file is named 'bonds.scv', make sure that the name and extension are correct.
bonds_file = 'bonds.csv'bonds_df = pd.read_csv(bonds_file)
isin_list = bonds_df['ISIN'].tolist()
2. Request bond data.
Define the necessary fields. If the field names differ, replace them with the correct ones.
fields = ["TR.YieldToMaturity", "TR.Maturity", "InstrumentName"]
data, err = ek.get_data(isin_list, fields=fields)
if err:
print("Error retrieving data:", err)
else:
df = data.copy()
# 3. Convert the maturity date to datetime format.
df['TR.Maturity'] = pd.to_datetime(df['TR.Maturity'])
# Determine the date of the previous trading session.
# For simplicity, we use yesterday's date here.
prev_date = datetime.now() - timedelta(days=1)
# Calculate the time to maturity in years.
df['TimeToMaturity'] = (df['TR.Maturity'] - prev_date).dt.days / 365.25
# Rename columns for convenience.
df = df.rename(columns={"TR.YieldToMaturity": "YTM",
"InstrumentName": "BondName"})
# Filter bonds with positive time to maturity and available YTM values.
df = df[df['TimeToMaturity'] > 0].dropna(subset=['YTM'])
# 4. Define categories for color-coding the points.
def categorize_ytm(ytm):
if ytm < 4.80:
return "Ниже 4.80%"
elif 4.80 <= ytm <= 5.0:
return "От 4.80 до 5%"
else:
return "Выше 5%"
df['Category'] = df['YTM'].apply(categorize_ytm)
# Define a color map for the categories.
color_map = {
"Ниже 4.80%": "red",
"От 4.80 до 5%": "yellow",
"Выше 5%": "green"
}
# 5. Build an interactive chart using Plotly.
fig = px.scatter(df,
x="TimeToMaturity",
y="YTM",
color="Category",
hover_data=["BondName"],
color_discrete_map=color_map,
labels={"TimeToMaturity": "Tenor (years)",
"YTM": "YTM (%)"},
title="YTM on a bond")
fig.show()