import argparse
import os
import json
import pandas as pd
import numpy as np
import statsmodels.api as sm
from statsmodels.stats.stattools import durbin_watson
def convert_categorical_to_numeric(data, dataset_name):
non_numeric_cols = data.select_dtypes(exclude=[np.number]).columns.tolist()
if not non_numeric_cols:
return []
print(f"INFO: Dataset '{dataset_name}' contains non-numeric columns: {non_numeric_cols}")
print(f"Converting categorical variables to numeric representations...")
for col in non_numeric_cols:
data[col], uniques = pd.factorize(data[col])
print(f" {col}: {len(uniques)} unique values -> integer level encoding")
return non_numeric_cols
def main():
parser = argparse.ArgumentParser(
description="Durbin-Watson Test - Check autocorrelation using statsmodels"
)
parser.add_argument(
"--csv",
default="../../datasets/csv/mtcars.csv",
help="Path to CSV file (first column = response, rest = predictors)"
)
parser.add_argument(
"--output-dir",
default="../../results/python",
help="Path to output directory"
)
args = parser.parse_args()
if not os.path.exists(args.csv):
raise FileNotFoundError(f"CSV file not found: {args.csv}")
dataset_name = os.path.splitext(os.path.basename(args.csv))[0]
data = pd.read_csv(args.csv)
non_numeric_cols = data.select_dtypes(exclude=[np.number]).columns.tolist()
if non_numeric_cols:
convert_categorical_to_numeric(data, dataset_name)
remaining_non_numeric = data.select_dtypes(exclude=[np.number]).columns.tolist()
if remaining_non_numeric:
raise ValueError(f"Could not convert the following non-numeric columns to numeric: {remaining_non_numeric}")
response_col = data.columns[0]
predictor_cols = data.columns[1:]
X = data[predictor_cols]
X = sm.add_constant(X)
y = data[response_col]
formula_str = f"{response_col} ~ {' + '.join(predictor_cols)}"
model = sm.OLS(y, X).fit()
dw_stat = durbin_watson(model.resid)
if dw_stat > 2:
interpretation = "No positive autocorrelation"
elif dw_stat < 2:
interpretation = "Possible positive autocorrelation"
else:
interpretation = "Inconclusive"
print("Durbin-Watson Test (Python - statsmodels)")
print("=" * 42)
print(f"Dataset: {dataset_name}")
print(f"Formula: {formula_str}")
print(f"DW-statistic: {dw_stat}")
print(f"Interpretation: {interpretation}")
print(f"Passed (1.5 < d < 2.5): {1.5 < dw_stat < 2.5}")
print()
output = {
"test_name": "Durbin-Watson Test (Python - statsmodels)",
"dataset": dataset_name,
"formula": formula_str,
"statistic": float(dw_stat),
"p_value": None, "passed": bool(1.5 < dw_stat < 2.5),
"interpretation": interpretation,
"description": "Tests for autocorrelation in residuals. Values near 2 indicate no autocorrelation, values near 0 suggest positive autocorrelation, and values near 4 suggest negative autocorrelation. Uses statsmodels.stats.stattools.durbin_watson."
}
os.makedirs(args.output_dir, exist_ok=True)
output_file = os.path.join(args.output_dir, f"{dataset_name}_durbin_watson.json")
with open(output_file, 'w') as f:
json.dump(output, f, indent=2)
print(f"Results saved to: {output_file}")
if __name__ == "__main__":
main()