首页 > 解决方案 > Python 3:如何在 Python 中对 OLS 系数进行单边测试?

问题描述

import numpy as np
import statsmodels.api as sm

# Generate the data
X= np.random.normal(loc=0, scale=1, size=[50,2])
x=X[:,0]
y=X[:,1]

# Run the regression
X = sm.add_constant(x)
res = sm.OLS(y, X).fit()
print(res.summary())

在此处输入图像描述

如何检验以下零假设:

H_0: interecept=0.05
H_a: intercept<0.05

是否有代码或某些包允许您在 python 中执行此操作?

标签: python-3.xstatistics

解决方案


我回答这个特定问题的方法是使我自己的函数如下:

def ttest_OLS(res, numberofbeta, X, value=0, alternative='two-sided', level_of_sig = 0.05):
    results=np.zeros([2])
    # numberofbeta represent the coeffiecent you would like to test 0 standts for interecept
    results[0]=res.tvalues[numberofbeta]
    results[1]=res.pvalues[numberofbeta]
    if isinstance(X, pd.DataFrame):
        column=X.columns[numberofbeta]
    else:
        column=numberofbeta
    if alternative == 'two-sided':
        if results[1]<level_of_sig:
            print("We reject the null hypothesis that the Selected Coefficient: {} is equal to {} with a {} % significance level".format(column, value, level_of_sig*100))
        else: print("We accept the null hypothesis that the Selected Coefficient: {} is equal to {} with a {} % significance level".format(column, value, level_of_sig*100))
    elif alternative == 'larger':
        if (results[0] > 0) & (results[1]/2 < level_of_sig):
            print("We reject the null hypothesis that the Selected Coefficient: {} is less than {} with a {} % significance level".format(column, value, level_of_sig*100))
        else: print("We accept the null hypothesis that the Selected Coefficient: {} is less than {} with a {} % significance level".format(column, value, level_of_sig*100))

    elif alternative == 'smaller':
        if (results[0] < 0) & (results[1]/2 < level_of_sig):
            print("We reject the null hypothesis that the Selected Coefficient: {} is more than {} with a {} % significance level".format(column, value, level_of_sig*100))
        else: print("We accept the null hypothesis that the Selected Coefficient: {} is more than {} with a {} % significance level".format(column, value, level_of_sig*100))

我按照我的问题实施的方式如下:

import pandas as pd
ttest_OLS(res, 0, X, value=0.5, alternative='two-sided', level_of_sig = 0.02)

这将完成这项工作。但是,如果您有更好的方法,请告诉我。


推荐阅读