使用Python 於valuesider網站爬取巴菲特(波克夏 海瑟威)13F報告,並製作成動態barchart,數據更新至FY24Q3。
▌Python 爬蟲細節
from bs4 import BeautifulSoup
import re
import requests
import pandas as pd
import numpy as np
page = range(1,4)
quarter = range(1,4)
year = range(2022,2025)
my_dict = {"year":[], "quarter":[], "ticker":[],"percent":[]};
for y in year:
for q in quarter:
for p in page:
url = 'https://valuesider.com/guru/warren-buffett-berkshire-hathaway/portfolio/{}/{}?sort=-percent_portfolio&sells_page=1&page={}'.format(y, q, p)
response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser')
ticker_list = soup.find_all('div', class_ = 'guru_table_column scroll-fix text-center', string=re.compile(".+"))
percent_list = soup.find_all('div', class_ = 'guru_table_column text-center', string=re.compile("%"))
for i in range(len(percent_list)):
my_dict["year"].append(y)
my_dict["quarter"].append(q)
my_dict["ticker"].append(ticker_list[i].get_text())
my_dict["percent"].append(percent_list[i].get_text())
df_data = pd.DataFrame(my_dict)# Convert 'percent' column to numeric before comparison
df_data['percent'] = df_data['percent'].str.rstrip('%').astype(float)
# Now you can perform the comparison
df_data['ticker_adj'] = np.where(df_data['percent']>= 3, df_data['ticker'], 'Other')
df_data = df_data.assign(year_quarter = df_data['year'].astype(str) + "-" + df_data['quarter'].astype(str))
df_data.sort_values('year_quarter', ascending=True, inplace = True)
df_final = df_data.groupby(['year_quarter' , 'ticker_adj']).agg(percentage = ('percent', 'sum')) # Changed 'percentage' to 'percent'
df_final.reset_index(inplace= True)
▌Python 視覺化
"year_quarter"
,表示按年份和季度動態顯示數據。import plotly.express as px
fig = px.bar(df_final, x="ticker_adj", y="percentage", color="ticker_adj",
animation_frame="year_quarter", animation_group="ticker_adj", range_y=[0,60])
fig.update_layout (xaxis={'categoryorder':'total descending'})
fig.show()
▌下載連結
以下為本 python 練習題 的程式碼(持續增加中),想拿資料作練習的朋友可以點下單連結,下載連結會寄至您提供的Email喔! 目前資源都是免費的,當然也歡迎您輸入金額小額贊助我們喔!
謝謝您花時間將此篇文章讀完,若覺得對您有幫助可以幫忙按個讚、分享來或是珍藏喔!也歡迎Follow我的Threads/ FB,持續追蹤生產力工具、商業分析、商業英文的實用範例,提升自己的職場力喔!