个股和股票池的beta系数的估算

个股的beta系数的估算

代码


def test_gg_beta(symbol='000895.sz', 
                 start='2018-01-01',
                 plot_price=True,
                 align_to='gg',
                 plot_k=True,
                 ):
    '''
    align_to: str, ['gg', 'dp'], 数据对齐的方式
        'gg': 表示对齐到个股, 改变大盘的数据, 以对齐到个股上
        'dp': 表示对齐到大盘, 改变个股的数据, 以对齐到大盘上
    
    
    >>> symbol='000895.sz'
    >>> start='2018-01-01'
    
    >>> beta, df = test_gg_beta(align_to='gg', plot_k=False)
    >>> beta2, df2 = test_gg_beta(align_to='dp', plot_k=False)
    
    >>> beta, df, plots = test_gg_beta('000933.sz')
    >>> beta, df = test_gg_beta('000933.sz', plot_price=False, plot_k=False)
    
    结果是: 
        0.83(双汇发展 @ 2018年)
        1.64(神火股份 @ 2018年)

    '''    
    _date = datetime.datetime.now().date().isoformat()
    title='QC图件: 用于计算个股的Beta系数(DP:399317)  
   制作日期: {}'.format(_date)
    
    c=Context(symbol)
    stk = Stock(c,start)
    stk.grab_data_from_tdxhq()
    stk.qfq()
    stk.grab_index_from_tdxhq()
    stk.indicator()
    
    # 个股通常会有停牌的时候, 所以需要对齐
    # 比如以个股为准, 把大盘对齐到个股是时间戳里: 
    # 将大盘的收盘线, 插入到个股的ohlc数据框里(用assign方法)
    if align_to == 'gg':
        f = stk.ohlc.close[0] / stk.aindex.close[0]
        df=stk.ohlc.assign(dp=stk.aindex.close * f)
        df=df.loc[:, ['close', 'dp']]
        beta = ttr.estimateBeta(df.close, df.dp)
        title += '
{:s}({:s})的Beta系数: {:.4f}(数据对齐到个股)'.format(stk.context.name,stk.context.code, beta) 
        if plot_price: 
            plt.figure()
            df.plot(title=title)
    elif align_to == 'dp':
        f = stk.aindex.close[0] / stk.ohlc.close[0]
        df2 = stk.aindex.assign(gg=stk.ohlc.close * f)
        df2 = df2.loc[:, ['close', 'gg']]
        df2 = df2.fillna(method='ffill') # 向未来填充 (用老数据向下填充)
        beta2 = ttr.estimateBeta(df2.gg, df2.close)
        title += '
{:s}({:s})的Beta系数: {:.4f}(数据对齐到大盘)'.format(stk.context.name,stk.context.code, beta2) 
        if plot_price: 
            plt.figure()
            df2.plot(title=title)
    
    if plot_k: 
#        fig,ax = plt.subplots(1,1)
        #stk.mycandlestick_ohlc(ax, [20,60])
        #stk.mycandlestick_ohlc(ax, with_raw_quotes=True)
#        stk.mycandlestick_ohlc(ax, with_raw_quotes=False)
        
        subset = slice(-120*3,None) # '2017-07'  '2017'
        subset = None
        plots = pl.Plotter(stk.context, stk, subset) #plot stk data
#        plots.plot_candle_only( 'lday')
        plots.plot_candle_vol('lday')
        #plots.plot_candle_vol('lday', savefig=True)
        
    if align_to=='gg':
        return beta, df
    else:
        return beta2, df2

结果图

结论

用276天大盘交易日(同期个股是271个交易日)的数据, 采用两种方法, 得到的beta值为:
0.833 vs 0.830
非常接近.

小于1的beta, 揭示了该股在大盘下跌阶段的优异表现.

股票池的beta

代码


def study_block_beta(subset=(8,18,1),show=False):
    '''
    
    >>> beta, res = study_block_beta()
    >>> beta, res = study_block_beta(show=True)
    '''
    syms_, syms = read_zxg(subset)
    
    betas, names, codes=[],[],[]
    for enum, sym in enumerate(syms):
        stk=load_data(sym)
        sname = stk.context.name
        code  = stk.context.code        
        names.append(sname)
        codes.append(code)
        pw=sname_print_width(sname)
        sdt = str(stk.sdt)[:10]
        edt = str(stk.edt)[:10]
        prompt = 'loaded data: {:<{pw}} {} {} {}'.format(sname, 
              code, 
              sdt, edt,
              pw=pw)
        print(prompt)
        beta=ttr.estimateBeta(stk.ohlc.close, stk.aindex.close)
        betas.append(beta)
        if show:
            #make plot
            close = stk.ohlc.close
            close = close/close[0] * 10.0
            #if not isinstance(fig, plt.Figure):
            if enum==0:
                fig=plt.figure(); type(fig)
                aindex = stk.aindex.close/stk.aindex.close[0] * 10.
                ax = aindex.plot(label='国证A指', lw=4, logy=True, ) #use_index=)
                close.plot(axes=ax, label=sname, logy=True,)
            else:
                if enum< len(syms) - 1:
                    close.plot(axes=ax, label=sname,logy=True,)
                else:
                    close.plot(axes=ax, label=sname,logy=True, title='池子里的收盘线')
                    ax.legend()
        
    resS = '{} {:8} {:6} {:6} 
'.format('Num','name', 'code', 'Beta')
    resS += '-' * 33 + '
'
    for i in range(len(names)):
        pw=sname_print_width(names[i])
        resS += '{:3d} {:{pw}} {} {:.3f} 
'.format(i, names[i], codes[i], betas[i], pw=pw)
    print( resS)
    
    return betas, resS

结果:

Num name code Beta

0 深圳燃气 601139 0.732
1 分众传媒 002027 1.392
2 海康威视 002415 1.378
3 双汇发展 000895 0.839
4 柳 工 000528 1.336
5 上海银行 601229 0.561
6 华兰生物 002007 0.880
7 兖州煤业 600188 1.251
8 云铝股份 000807 1.586
9 神火股份 000933 1.627

300个交易日: 2017-11-28 -- 2019-02-22 时间段的数据:

520个交易日: 2017-01-03 -- 2019-02-22 时间段的数据:

原文地址:https://www.cnblogs.com/duan-qs/p/10424497.html