Beta計算 Python notebook 程序來了,老虎幫忙看看

本帖於 2025-08-20 10:58:22 時間, 由普通用戶 slow_quick 編輯

這是對我 股票Beta的理解誤區 的補充

Anaconda installation Jupyter notebook


# *********************

import yfinance as yf   # pip install yfinance
import pandas as pd
import datetime
import dateutil
import xlwings as xw

# **********************

def get_adj_close_data(
    tickers: list[str],
    start_date: datetime.date, end_date: datetime.date,
    interval: str='1d'
) -> pd.DataFrame:
    return yf.download(tickers=tickers, start=start_date, end=end_date, interval=interval)['Close']


def get_monthly_return_data(
    tickers: list[str],
    start_date: datetime.date, end_date: datetime.date
) -> pd.DataFrame:
    p = get_adj_close_data(tickers=tickers, start_date=start_date, end_date=end_date)

    # pick the last day's price of each month, not necessarily month end
    p = p.groupby(p.index.to_period('M')).tail(1)
    
    return (p/p.shift(1) - 1)[tickers]


def calc_beta_etc(monthly_return_data: pd.DataFrame, benchmark: str) -> pd.DataFrame:
    """
    Input:
        monthly_return_data: DataFrame with timestamp index and stock/index ticker columns
                                including the benchmark
        benchmark: str of benchmark ticker

    Output:
        DataFrame with 
        
    """

    r_m = monthly_return_data[benchmark]
    
    def calc_one_beta_etc(r_s, r_m):
        """
            r_s: monthly stock returns
            r_m: monthly benchmark returns
        """
        rho = r_s.corr(r_m)  #  correlation
        sigma_s = r_s.std() * (12**0.5)  # annualized volatility
        sigma_m = r_m.std() * (12**0.5)  # annualized volatility
        beta = rho * sigma_s / sigma_m

        return pd.Series(
            data = {'beta': beta,
                    'rho': rho,
                    'sigma_s': sigma_s,
                    'sigma_m': sigma_m,
                    'vol ratio': sigma_s/sigma_m,
                   }
        )

    return monthly_return_data.apply(lambda c: calc_one_beta_etc(r_s=c, r_m=r_m), axis=0).T

# *********************************

end_date = datetime.date(2025, 7, 31)
start_date = end_date - dateutil.relativedelta.relativedelta(years=5, days=15)

tickers = [
    'AAPL',
    'AMZN',
    'GOOG',
    'GOOGL',
    'META',
    'MSFT',
    'NVDA',
    'TSLA',
    'T',
    '^GSPC'  # S&P500 Index, unfortunately the total return index isn't available from yfinance
]

monthly_return_data = get_monthly_return_data(tickers=tickers, start_date=start_date, end_date=end_date)

beta_etc = calc_beta_etc(monthly_return_data=monthly_return_data, benchmark='^GSPC')

# *********************************

wb = xw.Book()

ws1 = wb.sheets.add('monthly returns')
ws1.range('A1').options(index=True, header=True).value = monthly_return_data

ws2 = wb.sheets.add('beta etc')
ws2.range('A1').options(index=True, header=True).value = beta_etc
ws2.range('B:C,F:F').number_format = '0.0000'
ws2.range('D:E').number_format = '0.0000%'


所有跟帖: 

AI升成的和你的差不多啊,算出beta 也掙不了錢,牛頓把天體運行也算出了,哈哈哈 -Hightides- 給 Hightides 發送悄悄話 (2260 bytes) () 08/19/2025 postreply 23:02:24

所以大批程序員工作機會都受AI影響。。。 -slow_quick- 給 slow_quick 發送悄悄話 slow_quick 的博客首頁 (119 bytes) () 08/20/2025 postreply 06:37:32

牛啊 。。。 我曾經試著學了一下Python,但沒堅持下來,現在還是用matlab -老夏新生- 給 老夏新生 發送悄悄話 (0 bytes) () 08/19/2025 postreply 23:05:53

MATLAB 老貴啦,可以用免費的 GNU Octave -slow_quick- 給 slow_quick 發送悄悄話 slow_quick 的博客首頁 (106 bytes) () 08/20/2025 postreply 06:57:25

大頂。 雖然我的Python 都還給老師了 :) -薄利多收- 給 薄利多收 發送悄悄話 (0 bytes) () 08/19/2025 postreply 23:52:54

ChatGPT gives a thumb up to this -三心三意- 給 三心三意 發送悄悄話 三心三意 的博客首頁 (950 bytes) () 08/20/2025 postreply 06:02:27

But it gives you following sugegstion, LOL -三心三意- 給 三心三意 發送悄悄話 三心三意 的博客首頁 (3742 bytes) () 08/20/2025 postreply 06:03:00

我現在編程也常常讓AI過目一下,能查到不少漏洞或弱點。。。 -slow_quick- 給 slow_quick 發送悄悄話 slow_quick 的博客首頁 (5025 bytes) () 08/20/2025 postreply 06:51:45

too simple: remove outliers? rolling window regression? -IMM- 給 IMM 發送悄悄話 (74 bytes) () 08/20/2025 postreply 06:26:47

就靠你們這些專業的啦,我是三腳貓,Jack of all trades -slow_quick- 給 slow_quick 發送悄悄話 slow_quick 的博客首頁 (0 bytes) () 08/20/2025 postreply 06:52:57

professionals may not have good market sense as your guys -IMM- 給 IMM 發送悄悄話 (81 bytes) () 08/20/2025 postreply 08:11:38

哪位大俠能否解釋一下有啥用? -arewethereyet- 給 arewethereyet 發送悄悄話 (0 bytes) () 08/20/2025 postreply 10:20:37

這個就像趙本山的蟻力神,誰用誰知道 -slow_quick- 給 slow_quick 發送悄悄話 slow_quick 的博客首頁 (0 bytes) () 08/20/2025 postreply 11:35:22

請您先登陸,再發跟帖!