Sufficient to keep an eye on numerous bonds traded on the exchange.
However, unlike the stock of a company that trades under single symbol on the exchange, bonds of a single company often have multiple series, each with their different yields and maturity-dates. Thus, even if one is interested in a single company, often one would need to monitor dozens of bonds of the same company to find one that has the desired yield and is also currently being traded.
To simplify this workflow, we can scrape the above NSE webpage and filter the bonds of interest to us. Here's one way we can do that using simple Python code...
#!/usr/bin/env python3 | |
import requests | |
from datetime import datetime | |
import json | |
def nse_headers(): | |
return {'Accept': '*/*', | |
'Accept-Language': 'en-US,en;q=0.5', | |
'Host': 'www.nseindia.com', | |
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0', | |
'X-Requested-With': 'XMLHttpRequest'} | |
# Create a browser session | |
s = requests.session() | |
print('Opened a session') | |
# Fetch the bonds page | |
print('Opening the NSE Bonds webpage...') | |
s.get('http://www.nseindia.com/market-data/bonds-traded-in-capital-market', headers=nse_headers()) | |
# Fetch the bonds data as a CSV | |
print('Downloading the bonds data as a CSV...') | |
response = s.get('http://www.nseindia.com/api/liveBonds-traded-on-cm?type=bonds&csv=true', headers=nse_headers()) | |
# Ensure we notice any failures / bad responses | |
response.raise_for_status() | |
# Extract filename from the header | |
# Sample Header = 'attachment; filename=MW-Bonds-on-CM-07-Jan-2022.csv' | |
name = response.raw.getheaders()['Content-disposition'].rsplit('filename=')[1][:-4] | |
timestamp = datetime.now().strftime('-%H-%M-%S') | |
filename = name + timestamp + '.csv' | |
# Write the bonds CSV data to a local file | |
with open(filename, 'wb') as file: | |
file.write(response.content) | |
print('Saved the NSE Bonds data as', filename) | |
# Fetch the bonds data as a JSON | |
print('Downloading the bonds data as a JSON...') | |
response = s.get('http://www.nseindia.com/api/liveBonds-traded-on-cm?type=bonds', headers=nse_headers()) | |
# Ensure we notice any failures / bad responses | |
response.raise_for_status() | |
# Prepare a json filename | |
filename = filename[:-4] + '.json' | |
# Write the bonds JSON data to a local file | |
with open(filename, 'w') as file: | |
json.dump(json.loads(response.content), file, indent=4) | |
print('Saved the NSE Bonds data as', filename) | |
Running the above script nse-bond-watch.py
on a system that has access to the internet,
we receive the data in CSV and JSON formats.
In subsequent posts in this series,
we will explore how we can maintain this data locally, as well as filter it.
No comments :
Post a Comment