如何使用Python獲取債券資訊? Part1

2023/10/11閱讀時間約 4 分鐘


raw-image

債券是發行者為籌集資金而發行、在約定時間支付一定比例的利息,並在到期時償還本金的一種有價證券。根據不同發行方,可分為政府債券、金融債券以及公司債券。投資者購入債券,就如借出資金予政府、大企業或其他債券發行機構。這三者中政府債券因為有政府稅收作為保障,因而風險最小,但收益也最小。公司債券風險最大,可能的收益也最大。債券持有者是債權人,發行者為債務人。債券不論何種形式,大都可以在市場上進行買賣,並因此形成了債券市場

本文我們將會探討如何使用Python於Markets Insider撈取債券資料,存成資料表並錄入SQLite資料庫。

You can check this for the English version!


首先,我們要先理解網址的資料結構,本文會以公司短債為例。

https://markets.businessinsider.com/bonds/finder
?p=1 (頁數)
&borrower= (發行者/公司)
&maturity= (shortterm: 0-3 yers / midterm: 3-10 years/ longterm: > 10 years)
&yield= (0: < 5% / 5:5%-10% / 10: 10%-20%)
&bondtype=(6%2c7%2c8%2c19: Corporate/ 2%2C3%2C4%2C16: Government, etc)
&coupon= (0: < 5% / 5:5%-10% / 10: >10%)
&currency= (333: USD / 534: JPY/ 846: SGD, etc)
&rating= (Moody's rating)
&country= (18: USA/ 33: China/ 27/ Singapore, etc)

Step 0: 匯入模組

from datetime import date
from datetime import timedelta
import pandas as pd
import requests
import sqlite3
from google.colab import drive

drive.mount('/content/drive')
today = date.today()
con = sqlite3.connect('/content/drive/MyDrive/data/Stock.db')

Step 1: 定義迴圈。

for i in range(1, 100):
url = 'https://markets.businessinsider.com/bonds/finder?p='+ str(i) +'&borrower=&maturity=shortterm&yield=5&bondtype=6%2c7%2c8%2c19&coupon=0&currency=333&rating=&country=18'

Step 2: 將url送出獲取每個頁面的資訊。

res = requests.get(url)
res.encoding = 'big5'
html_df = pd.read_html(res.text)
df = html_df [0]
df['As_Of'] = today

Step 3: 將獲取的資料表存入資料庫。

df.to_sql('Coporate_Bond_Markets_Insider', con, if_exists='append')
raw-image

此資訊並不包含債券的ISIN/ Coupon Payment Date等資訊,必須點擊每個項目的連結進入細項網頁,因此我們下一篇會討論如何結合BeautifulSoup獲取超連結。

謝謝您,如果覺得此篇文章有幫助到您,歡迎透過此連結贊助我們。


以行動支持創作者!付費即可解鎖
本篇內容共 1718 字、0 則留言,僅發佈於Informula你目前無法檢視以下內容,可能因為尚未登入,或沒有該房間的查看權限。
6會員
17內容數
Informula 作為上班族的臨時急救包,介紹一些簡單的程式工具、資料處理、數據分析、網路爬蟲應用等。
留言0
查看全部
發表第一個留言支持創作者!