Online Statsmodels Compiler

Online Statsmodels Compiler and Playground.

Python
# Performing simple linear regression with statsmodels

import numpy as np
import statsmodels.api as sm

# Sample data: Hours studied and Exam scores
hours_studied = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
exam_scores = np.array([51, 55, 60, 68, 72, 75, 78, 82, 85, 88, 90, 92, 94, 96, 97, 98, 99, 100, 101, 102])

# Adding a constant for the intercept term
X = sm.add_constant(hours_studied)

# Creating the model
model = sm.OLS(exam_scores, X)

# Fitting the model
results = model.fit()

# Making predictions
hours = 10  # Predicting the exam score for someone who studied 10 hours
predicted_score = results.predict([1, hours])  # The first element is the constant term
print(f"Predicted exam score for someone who studied {hours} hours: {predicted_score[0]}\n")

# Printing the summary of the model
print(results.summary())
Predicted exam score for someone who studied 10 hours: 82.85413533834586

                            OLS Regression Results                            
==============================================================================
Dep. Variable:                      y   R-squared:                       0.922
Model:                            OLS   Adj. R-squared:                  0.917
Method:                 Least Squares   F-statistic:                     211.8
Date:                Wed, 15 Apr 2026   Prob (F-statistic):           2.14e-11
Time:                        12:47:50   Log-Likelihood:                -57.815
No. Observations:                  20   AIC:                             119.6
Df Residuals:                      18   BIC:                             121.6
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const         56.9368      2.134     26.687      0.000      52.454      61.419
x1             2.5917      0.178     14.552      0.000       2.218       2.966
==============================================================================
Omnibus:                        3.416   Durbin-Watson:                   0.153
Prob(Omnibus):                  0.181   Jarque-Bera (JB):                2.165
Skew:                          -0.603   Prob(JB):                        0.339
Kurtosis:                       1.930   Cond. No.                         25.0
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.