Regenerate all MDC rules with fresh Exa data and December 2025 best practices

- Refreshed all 241 library rules with current best practices
- Updated Exa search results for all libraries with 2025 content
- Fixed --regenerate-all flag logic to properly process all libraries
- Removed duplicate astro entry in rules.json (merged tags)
- Added missing docker.mdc and vim.mdc files
- All rules now include modern patterns and anti-patterns
- Updated with framework-specific recommendations for 2025

Technical improvements:
- Fixed retry_failed_only logic in generate_mdc_files.py
- Improved progress tracking for regeneration scenarios
- Ensured proper handling of --refresh-exa flag
This commit is contained in:
sanjeed5
2025-12-17 22:40:28 +05:30
parent 331fb6ffac
commit 8fbf269085
244 changed files with 66701 additions and 52708 deletions
+214 -227
View File
@@ -1,289 +1,276 @@
---
description: A comprehensive guide to best practices for using the statsmodels library in Python, covering code organization, performance, testing, and common pitfalls. These guidelines promote maintainable, reliable, and efficient statsmodels code.
globs: *.py
description: This guide provides opinionated, actionable best practices for using statsmodels in Python, focusing on code organization, common patterns, performance, and modern development workflows to ensure robust and reproducible statistical analysis.
globs: **/*.py
---
# Statsmodels Library Best Practices
# `statsmodels` Best Practices
This document outlines best practices and coding standards for effectively using the statsmodels library in Python for statistical modeling, machine learning, and data science applications. Following these guidelines will help ensure code that is readable, maintainable, efficient, and statistically sound.
`statsmodels` is the definitive library for rigorous statistical modeling and inference in our AI/ML pipelines. This guide ensures consistent, high-quality, and reproducible statistical analysis across our projects.
## Library Information:
- Name: statsmodels
- Tags: ai, ml, data-science, python, statistics
## 1. Code Organization and Imports
## 1. Code Organization and Structure
Always use the recommended import aliases for clarity and consistency. Keep model specifications in dedicated, well-named scripts or notebooks.
### 1.1 Directory Structure
### ✅ GOOD: Standardized Imports
Adopt a clear and organized directory structure for your projects:
```python
# For general models and datasets
import statsmodels.api as sm
import pandas as pd
import numpy as np
# For R-style formula interface
import statsmodels.formula.api as smf
```
project_root/
├── data/ # Raw and processed datasets
├── models/ # Saved model artifacts
├── scripts/ # Data processing, model training, evaluation scripts
├── notebooks/ # Exploratory data analysis and prototyping (use sparingly for final code)
├── tests/ # Unit, integration, and end-to-end tests
├── docs/ # Project documentation
├── requirements.txt # Project dependencies
└── main.py # Entry point for the application (if applicable)
### ❌ BAD: Inconsistent or Wildcard Imports
```python
from statsmodels.api import * # Pollutes namespace
import statsmodels as sm_lib # Non-standard alias
```
### 1.2 File Naming Conventions
## 2. Data Handling and Model Specification
- Use descriptive and consistent file names.
- Data files: `data_description.csv`, `data_description.parquet`
- Script files: `process_data.py`, `train_model.py`, `evaluate_model.py`
- Model files: `model_name.pkl` (if pickling, but consider other serialization methods)
- Test files: `test_module.py`
`statsmodels` excels with `pandas` DataFrames and R-style formulas. Leverage these for readability and robustness.
### 1.3 Module Organization
### 2.1. Use Pandas DataFrames
- Break down your code into reusable modules.
- `data_loading.py`: Functions for loading and preprocessing data.
- `model_definition.py`: Classes or functions for defining statsmodels models.
- `model_training.py`: Functions for training models.
- `model_evaluation.py`: Functions for evaluating model performance.
- `utils.py`: Utility functions used throughout the project.
Always prepare your data as `pandas.DataFrame` objects. This ensures clear column names and simplifies formula specification.
### 1.4 Component Architecture
### ✅ GOOD: Pandas DataFrame for Data
- Employ a modular architecture to separate concerns.
- **Data Layer:** Handles data loading, cleaning, and transformation.
- **Model Layer:** Defines and trains statsmodels models.
- **Evaluation Layer:** Assesses model performance using appropriate metrics.
- **Application Layer:** Integrates the model into an application (if applicable).
```python
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
### 1.5 Code Splitting Strategies
data = pd.DataFrame({
'y_response': np.random.rand(100),
'x_feature1': np.random.rand(100) * 10,
'x_feature2': np.random.randint(0, 2, 100),
'group': np.random.choice(['A', 'B'], 100)
})
- Split large files into smaller, more manageable modules.
- Group related functions and classes into separate modules.
- Use clear and concise function and class names to indicate their purpose.
- Consider a `config.py` file for global project settings.
# Use formula API for convenience
model = smf.ols('y_response ~ x_feature1 + C(x_feature2) + group', data=data).fit()
print(model.summary())
```
## 2. Common Patterns and Anti-patterns
### ❌ BAD: Raw NumPy Arrays (unless absolutely necessary)
### 2.1 Design Patterns
```python
# Avoid this unless you need fine-grained control or non-standard designs
X = np.random.rand(100, 2)
y = np.random.rand(100)
model = sm.OLS(y, X).fit() # Column names are lost in summary
```
- **Factory Pattern:** Use a factory pattern to create different statsmodels models based on configuration.
- **Strategy Pattern:** Implement different evaluation strategies using the strategy pattern.
- **Observer Pattern:** If changes in the underlying data need to trigger model retraining, consider the observer pattern.
### 2.2. Always Add a Constant (Intercept)
### 2.2 Recommended Approaches for Common Tasks
For most regression models, an intercept term is crucial. The formula API handles this automatically; for array-based models, explicitly add it.
- **Data Preprocessing:** Always use Pandas DataFrames for data manipulation before feeding data into statsmodels.
- **Model Selection:** Choose models based on the statistical properties of your data and the research question.
- **Model Fitting:** Use `statsmodels.api` to fit models, and carefully interpret the output.
- **Result Interpretation:** Focus on coefficients, p-values, confidence intervals, and model diagnostics.
- **Visualization:** Utilize Matplotlib and Seaborn to visualize data, model results, and diagnostics.
### ✅ GOOD: Explicitly Adding a Constant
### 2.3 Anti-patterns and Code Smells
- **Magic Numbers:** Avoid hardcoding constants directly in your code; define them with descriptive names.
- **Copy-Pasted Code:** Refactor duplicated code into reusable functions or classes.
- **Overly Long Functions:** Break down long functions into smaller, more manageable units.
- **Lack of Documentation:** Always document your code with docstrings to explain its purpose and usage.
- **Ignoring Warnings:** Pay attention to warnings generated by statsmodels; they often indicate potential issues.
### 2.4 State Management
- Avoid global state as much as possible. Pass data and model parameters explicitly.
- If you need to persist model state, use appropriate serialization techniques (e.g., pickling, but with caution due to security risks). Consider alternatives like ONNX or joblib.
- For complex applications, use dependency injection frameworks to manage dependencies and state.
### 2.5 Error Handling
- Use try-except blocks to handle potential errors gracefully.
- Log errors and warnings using the `logging` module.
- Raise exceptions with informative error messages to help with debugging.
- Consider custom exception classes for specific statsmodels-related errors.
python
import logging
logger = logging.getLogger(__name__)
try:
model = sm.OLS(y, X).fit()
except Exception as e:
logger.error(f"Error fitting model: {e}")
raise # Re-raise the exception for higher-level handling
## 3. Performance Considerations
### 3.1 Optimization Techniques
- **Vectorization:** Utilize NumPy's vectorized operations whenever possible to speed up computations.
- **Profiling:** Use profiling tools like `cProfile` to identify performance bottlenecks.
- **Caching:** Cache frequently used results to avoid redundant computations (use `functools.lru_cache` for example).
- **Algorithm Selection:** Choose the most efficient algorithms for your specific task (e.g., different optimization methods in statsmodels).
### 3.2 Memory Management
- **Data Types:** Use appropriate data types to minimize memory usage (e.g., `np.int32` instead of `np.int64` if possible).
- **Lazy Loading:** Load large datasets in chunks to avoid loading the entire dataset into memory at once.
- **Garbage Collection:** Explicitly release unused memory using `del` or `gc.collect()` if necessary.
### 3.3 Parallelization
- Explore parallelization options using libraries like `multiprocessing` or `joblib` for computationally intensive tasks.
- Statsmodels may leverage underlying NumPy and SciPy functions that support parallel execution.
## 4. Security Best Practices
### 4.1 Common Vulnerabilities
- **Pickle Deserialization:** Avoid deserializing untrusted pickle files, as they can execute arbitrary code. Use safer serialization formats like JSON or ONNX.
- **Injection Attacks:** Sanitize user inputs to prevent injection attacks if your application takes user-provided data and uses it in statsmodels models.
- **Denial of Service (DoS):** Implement rate limiting and resource constraints to prevent DoS attacks on your statsmodels-based services.
### 4.2 Input Validation
- Validate all input data to ensure it conforms to the expected format and range.
- Use schemas (e.g., using `jsonschema` or `pydantic`) to define and enforce data validation rules.
- Check for missing values, outliers, and inconsistencies in the data.
### 4.3 Authentication and Authorization
- Implement authentication and authorization mechanisms to control access to your statsmodels-based services.
- Use secure authentication protocols like OAuth 2.0 or JWT.
- Enforce role-based access control (RBAC) to restrict access to sensitive data and operations.
### 4.4 Data Protection
- Encrypt sensitive data at rest and in transit.
- Use secure communication protocols like HTTPS.
- Implement data masking and anonymization techniques to protect user privacy.
### 4.5 Secure API Communication
- Use secure APIs (e.g., REST APIs with HTTPS) to communicate with your statsmodels services.
- Implement input validation and output sanitization to prevent injection attacks.
- Use API keys or other authentication mechanisms to secure your APIs.
## 5. Testing Approaches
### 5.1 Unit Testing
- Write unit tests for individual functions and classes.
- Use the `unittest` or `pytest` framework.
- Test edge cases and boundary conditions.
- Mock external dependencies to isolate the code being tested.
python
import unittest
```python
import statsmodels.api as sm
import numpy as np
class TestOLS(unittest.TestCase):
def test_ols_fit(self):
# Create some sample data
X = np.array([[1, 1], [1, 2], [1, 3]])
y = np.array([2, 4, 5])
X_raw = np.random.rand(100, 2)
X = sm.add_constant(X_raw) # Adds a column of ones for the intercept
y = np.random.rand(100)
# Fit an OLS model
model = sm.OLS(y, X).fit()
model = sm.OLS(y, X).fit()
```
# Assert that the model converged
self.assertTrue(model.converged)
### ❌ BAD: Forgetting the Constant
# Assert that the coefficients are close to the expected values
expected_coefs = np.array([0.5, 1.5])
np.testing.assert_allclose(model.params, expected_coefs, rtol=1e-5)
```python
# This model will be fitted without an intercept, which is often incorrect
X = np.random.rand(100, 2)
y = np.random.rand(100)
model = sm.OLS(y, X).fit()
```
if __name__ == '__main__':
unittest.main()
## 3. Reproducibility and Debugging
Ensure your analyses are reproducible and easy to debug by including version information.
### 5.2 Integration Testing
### ✅ GOOD: Reporting Version Information
- Write integration tests to verify the interaction between different components.
- Test the data pipeline from data loading to model evaluation.
- Verify that the model produces correct results on sample datasets.
```python
import statsmodels.api as sm
### 5.3 End-to-End Testing
print(f"Statsmodels Version: {sm.version.full_version}")
sm.show_versions() # Crucial for dependency debugging
```
- Write end-to-end tests to simulate real-world usage scenarios.
- Test the entire application from start to finish.
- Use tools like Selenium or Cypress to automate browser-based testing (if applicable).
### ❌ BAD: Omitting Version Details
### 5.4 Test Organization
```python
# When reporting issues or sharing code, this makes debugging harder
# print("Model results...")
```
- Organize your tests in a separate `tests` directory.
- Use a consistent naming convention for test files (e.g., `test_module.py`).
- Group related tests into test classes.
## 4. Type Hints for Clarity
### 5.5 Mocking and Stubbing
Use type hints to improve code readability, maintainability, and enable static analysis.
- Use mocking libraries like `unittest.mock` or `pytest-mock` to isolate the code being tested.
- Mock external dependencies like databases or APIs.
- Stub out complex functions to simplify testing.
### ✅ GOOD: Using Type Hints
## 6. Common Pitfalls and Gotchas
```python
import pandas as pd
import statsmodels.api as sm
from statsmodels.regression.linear_model import RegressionResultsWrapper
### 6.1 Frequent Mistakes
def fit_linear_model(data: pd.DataFrame, formula: str) -> RegressionResultsWrapper:
"""Fits an OLS model and returns the results."""
model = sm.formula.ols(formula, data=data)
results = model.fit()
return results
- **Incorrect Model Specification:** Choosing the wrong model for the data.
- **Ignoring Data Assumptions:** Failing to check the assumptions of the statistical tests or models being used.
- **Overfitting:** Training a model that performs well on the training data but poorly on unseen data.
- **Misinterpreting Results:** Drawing incorrect conclusions from the model output.
- **Not Scaling Features**: Some models will perform poorly if the data is not scaled or normalized
# Usage
df = pd.DataFrame({'y': np.random.rand(10), 'x': np.random.rand(10)})
ols_results = fit_linear_model(df, 'y ~ x')
print(ols_results.summary())
```
### 6.2 Edge Cases
### ❌ BAD: Untyped Code
- **Multicollinearity:** Independent variables being highly correlated
- **Missing Data:** Handling missing values appropriately.
- **Outliers:** Identifying and handling outliers in the data.
- **Non-Normal Data:** Dealing with data that doesn't follow a normal distribution.
```python
def fit_linear_model(data, formula): # Lacks clarity on expected types
model = sm.formula.ols(formula, data=data)
results = model.fit()
return results
```
### 6.3 Version-Specific Issues
## 5. Virtual Environments and Packaging
- Be aware of changes in statsmodels API between versions.
- Check the release notes for any breaking changes or bug fixes.
- Use a virtual environment to manage dependencies and ensure compatibility.
Always isolate project dependencies using virtual environments and manage them explicitly.
### 6.4 Compatibility Concerns
### ✅ GOOD: Dedicated Virtual Environments and `pyproject.toml`
- Ensure compatibility between statsmodels and other libraries like NumPy, SciPy, and Pandas.
- Check the documentation for any known compatibility issues.
```bash
# Create and activate a virtual environment
python -m venv .venv
source .venv/bin/activate # Linux/macOS
.venv\Scripts\activate # Windows
### 6.5 Debugging Strategies
# Install dependencies
pip install pandas numpy statsmodels
- Use a debugger (e.g., `pdb`) to step through the code and inspect variables.
- Add logging statements to track the execution flow and identify potential issues.
- Use assertions to verify that the code is behaving as expected.
- Consult the statsmodels documentation and community forums for help.
# Manage dependencies with pyproject.toml (preferred) or requirements.txt
# pyproject.toml example:
# [project]
# name = "my-stats-project"
# dependencies = [
# "pandas>=2.0",
# "numpy>=1.24",
# "statsmodels>=0.15"
# ]
```
## 7. Tooling and Environment
### ❌ BAD: Global Package Installation
### 7.1 Recommended Development Tools
```bash
pip install pandas numpy statsmodels # Pollutes global Python environment
```
- **IDE:** VS Code, PyCharm, or other Python IDE.
- **Virtual Environment Manager:** `venv`, `conda`.
- **Package Manager:** `pip`, `conda`.
- **Debugger:** `pdb`, `ipdb`.
- **Profiler:** `cProfile`.
## 6. Testing Approaches
### 7.2 Build Configuration
Thorough testing is non-negotiable. Ensure statistical models are robust and produce expected outcomes.
- Use `setuptools` or `poetry` to manage project dependencies and build configurations.
- Create a `requirements.txt` file to specify project dependencies.
- Use a `setup.py` file to define the project metadata and build process.
### ✅ GOOD: Unit and Integration Tests with Fixed Seeds
### 7.3 Linting and Formatting
```python
import pandas as pd
import numpy as np
import statsmodels.api as sm
import statsmodels.formula.api as smf
- Use linters like `flake8` or `pylint` to enforce code style and identify potential errors.
- Use formatters like `black` or `autopep8` to automatically format your code.
- Configure your IDE to run linters and formatters automatically on save.
def test_ols_model_coefficients():
np.random.seed(42) # Fix seed for reproducibility
data = pd.DataFrame({
'y': 2 + 3 * np.random.rand(100) + np.random.normal(0, 0.5, 100),
'x': np.random.rand(100)
})
model = smf.ols('y ~ x', data=data).fit()
### 7.4 Deployment
# Assert expected coefficients within a tolerance
assert np.isclose(model.params['Intercept'], 2.0, atol=0.5)
assert np.isclose(model.params['x'], 3.0, atol=0.5)
- Containerize your application using Docker.
- Use a deployment platform like AWS, Azure, or Google Cloud.
- Monitor your application for performance and errors.
# Run tests as part of CI (e.g., pytest)
# Ensure CI pipeline includes ruff, isort, and other linters.
```
### 7.5 CI/CD
### ❌ BAD: Untested Models or Unreproducible Tests
- Use a CI/CD platform like GitHub Actions, Jenkins, or CircleCI to automate the build, test, and deployment process.
- Run unit tests, integration tests, and end-to-end tests as part of the CI/CD pipeline.
- Deploy your application automatically to a staging or production environment after successful testing.
```python
# No tests for model logic or coefficient validation
# Tests that rely on random data without a fixed seed will be flaky
```
## 7. Docstrings and Comments
Follow the NumPy/SciPy docstring standard and use concise, clear comments for complex logic.
### ✅ GOOD: NumPy-style Docstrings
```python
def analyze_sales_data(df: pd.DataFrame) -> sm.regression.linear_model.RegressionResultsWrapper:
"""
Analyzes sales data using Ordinary Least Squares (OLS).
Parameters
----------
df : pd.DataFrame
Input DataFrame containing 'sales', 'ad_spend', and 'promotions' columns.
Returns
-------
sm.regression.linear_model.RegressionResultsWrapper
The fitted OLS model results.
Raises
------
ValueError
If required columns are missing from the DataFrame.
"""
required_cols = ['sales', 'ad_spend', 'promotions']
if not all(col in df.columns for col in required_cols):
raise ValueError(f"DataFrame must contain columns: {required_cols}")
model = smf.ols('sales ~ ad_spend + promotions', data=df)
results = model.fit()
return results
```
### ❌ BAD: Missing or Poor Docstrings
```python
def analyze_sales_data(df): # What does it do? What are inputs/outputs?
model = smf.ols('sales ~ ad_spend + promotions', data=df)
results = model.fit()
return results
```
## 8. Git Workflow
Adhere to our standard Git practices for maintainability and clear history.
### ✅ GOOD: Focused Branches and Clear Commits
```bash
# Work on a single feature per branch
git checkout -b feature/add-robust-regression
# Write concise, descriptive commit messages
git commit -m "feat: Implement Huber-M-estimator for RLM" -m "Adds robust linear model with Huber loss function to handle outliers in financial data analysis."
```
### ❌ BAD: "Kitchen Sink" Branches and Vague Commits
```bash
git checkout -b dev # Generic branch
git commit -m "Update code" # Uninformative
```