Historical beta calculation via Python API

djp
djp Newcomer
edited May 23 in Eikon Data APIs

What would be the best way to replicate the historical beta calculation through the Python API (preferably via lseg-data)? As I understand, there is currently no example available in the Workspace Codebook library of such a historical beta calculation, as the API instead only allows for obtaining the latest available data points?

Specifically, I am looking for an efficient way of replicating the below Excel-based template file retrieving Company Historical Beta, provided to me by the support team.

image.png

Answers

  • Jirapongse
    Jirapongse ✭✭✭✭✭

    @djp

    Thank you for reaching out to us.

    You can check the Calculation sheet that show how to calculate those values. The sample code looks like this:

    def calculateBeta(ric, index, end, interval, datapoints, beta=''):
        stock_resp = historical_pricing.summaries.Definition(
            ric, 
            interval=interval,    
            end = end, 
            count = datapoints,
            fields=['TRDPRC_1'],
            extended_params={"includeTradeIndicator":"True"}
        ).get_data()
        stock_df = stock_resp.data.df.ffill()
        if 'TRADE_IND' in stock_df.columns:
                stock_df = stock_df.drop(['TRADE_IND'], axis=1)
        stock_reverse = stock_df.iloc[::-1]
        stock_reverse1 = stock_df.shift()[::-1]
        stock1 = np.log(stock_reverse / stock_reverse1)
        stock1 = stock1.dropna()
        #display(stock1)
    
        index_resp = historical_pricing.summaries.Definition(
            index, 
            interval=interval,    
            end = end, 
            count = datapoints,
            fields=['TRDPRC_1'],
            extended_params={"includeTradeIndicator":"True"}
        ).get_data()
        index_df = index_resp.data.df.ffill()
        if 'TRADE_IND' in index_df.columns:
                index_df = index_df.drop(['TRADE_IND'], axis=1)
        index_reverse = index_df.iloc[::-1]
        index_reverse1 = index_df.shift()[::-1]
        index1 = np.log(index_reverse / index_reverse1)
        index1 = index1.dropna()
    
        temp = pd.DataFrame()
    
        if beta=='up':
            temp['INDEX'] = index1.apply(lambda x: np.nan if x['TRDPRC_1'] <= 0 else x['TRDPRC_1'],axis=1)
            temp['STOCK'] = stock1['TRDPRC_1']
            temp = temp.dropna()
        elif beta=='down':
            temp['INDEX'] = index1.apply(lambda x: np.nan if x['TRDPRC_1'] >= 0 else x['TRDPRC_1'],axis=1)
            temp['STOCK'] = stock1['TRDPRC_1']
            temp = temp.dropna()
        else:
            temp['INDEX'] = index1['TRDPRC_1']
            temp['STOCK'] = stock1['TRDPRC_1']
       
        slope, _ = np.polyfit(temp['INDEX'].tolist(), temp['STOCK'].tolist(), 1)    
        return slope
    

    It can be used like this:

    _90_days_beta_daily = calculateBeta("PTT.BK",".SETI","2025-05-20",Intervals.DAILY,91)
    _180_days_beta_daily = calculateBeta("PTT.BK",".SETI","2025-05-20",Intervals.DAILY,181)
    _2_years_beta_weekly = calculateBeta("PTT.BK",".SETI","2025-05-20",Intervals.WEEKLY,105)
    _3_years_beta_weekly = calculateBeta("PTT.BK",".SETI","2025-05-20",Intervals.WEEKLY,157)
    _5_years_beta_monthly = calculateBeta("PTT.BK",".SETI","2025-05-20",Intervals.MONTHLY,61)
    
    _2_years_beta_up_weekly = calculateBeta("PTT.BK",".SETI","2025-05-20",Intervals.WEEKLY,105,'up')
    _3_years_beta_up_weekly = calculateBeta("PTT.BK",".SETI","2025-05-20",Intervals.WEEKLY,157,'up')
    _5_years_beta_up_weekly = calculateBeta("PTT.BK",".SETI","2025-05-20",Intervals.MONTHLY,61,'up')
    
    _2_years_beta_down_weekly = calculateBeta("PTT.BK",".SETI","2025-05-20",Intervals.WEEKLY,105,'down')
    _3_years_beta_down_weekly = calculateBeta("PTT.BK",".SETI","2025-05-20",Intervals.WEEKLY,157,'down')
    _5_years_beta_down_weekly = calculateBeta("PTT.BK",".SETI","2025-05-20",Intervals.MONTHLY,61,'down')
    
    

    The code is not fully tested. It may not support all use cases so feel free to modify it according to your requirement.