到證交所網站的臺灣50指數歷史資料(https://www.twse.com.tw/en/indices/ftse/tai50i.html)抓取,裡面有「臺灣50指數」和「臺灣50報酬指數」兩種指數,Python程式碼如下:
import requests
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime
from time import sleep
from dateutil.relativedelta import relativedelta
def get_month_index_TAI50I(date: str):
# from "https://www.twse.com.tw/en/indices/ftse/tai50i.html"
url = "https://www.twse.com.tw/rwd/en/FTSE/TAI50I?date={}&response=json".format(date.replace("-", ""))
response = requests.get(url)
df = pd.DataFrame(response.json()['data'], columns=['Date', 'FTSE TWSE Taiwan 50 Index','FTSE TWSE Taiwan 50 Total Return Index'])
df['FTSE TWSE Taiwan 50 Total Return Index'] = pd.to_numeric(df['FTSE TWSE Taiwan 50 Total Return Index'].str.replace(',', ''))
df['FTSE TWSE Taiwan 50 Index'] = pd.to_numeric(df['FTSE TWSE Taiwan 50 Index'].str.replace(',', ''))
df['Date'] = pd.to_datetime(df['Date'])
# Set 'Date' as the index
df.set_index('Date', inplace=True)
return df
# 起始年
start_year = 2014
# 起始月
start_month = 11
query_date = datetime(start_year, start_month, 1).date()
today = datetime.now().date()
df = pd.DataFrame(columns=['Date', 'FTSE TWSE Taiwan 50 Index','FTSE TWSE Taiwan 50 Total Return Index'])
df = df.dropna(axis=1, how='all')
while today >= query_date:
date_str = f'{query_date.year}-{query_date.month:02d}-01'
#print("抓取資料:" + date_str)
new = get_month_index_TAI50I(date_str)
df = pd.concat([df,new], axis=0, sort=False)
query_date = query_date + relativedelta(months=1)
sleep(1) # 避免被擋
# 繪製兩個指數在一個圖中
plt.figure(figsize=(10, 6))
plt.plot(df.index, df['FTSE TWSE Taiwan 50 Index'], label='FTSE TWSE Taiwan 50 Index')
plt.plot(df.index, df['FTSE TWSE Taiwan 50 Total Return Index'], label='FTSE TWSE Taiwan 50 Total Return Index')
plt.xlabel('Date')
plt.ylabel('Index Value')
plt.title('FTSE TWSE Taiwan 50 Index vs Total Return Index')
plt.legend()
plt.grid(True)
plt.show()
用ffn Package分析「臺灣50指數」和「臺灣50報酬指數」兩種指數績效
import ffn
perf = df['FTSE TWSE Taiwan 50 Index'].calc_stats()
print(perf.display())
perf = df['FTSE TWSE Taiwan 50 Total Return Index'].calc_stats()
print(perf.display())
「臺灣50指數」績效:
10年指數成長了189%,最大回檔約-36%。
「臺灣50報酬指數」績效:
10年指數成長了316%,最大回檔約-33%。