Skip to content

Instantly share code, notes, and snippets.

@ycytai
Created December 8, 2023 12:49
Show Gist options
  • Save ycytai/d942c66a9cb45ce4fd2dfeda3e2c8751 to your computer and use it in GitHub Desktop.
Save ycytai/d942c66a9cb45ce4fd2dfeda3e2c8751 to your computer and use it in GitHub Desktop.
import pandas as pd
import requests
# 設定目標日期
target_date = '20230928'
# 把 csv 檔抓下來
url = f'https://www.twse.com.tw/rwd/zh/afterTrading/MI_INDEX?date={target_date}&type=ALL&response=csv'
res = requests.get(url)
data = res.text
# 把爬下來的資料整理成需要的格式
s_data = data.split('\n')
output = []
for d in s_data:
_d = d.split('","')
length = len(_d)
symbol = _d[0]
if length == 16 and not symbol.startswith('='):
output.append([
ele.replace('",\r','').replace('"','')
for ele in _d
])
# 轉成 DataFrame 並存成 csv 檔
df = pd.DataFrame(output[1:], columns=output[0])
df.set_index('證券代號', inplace=True)
df.to_csv(f'stock_price_{target_date}.csv')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment