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

请您先登陆,再发跟帖!