churnkit 0.75.0a1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/00_start_here.ipynb +647 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01_data_discovery.ipynb +1165 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01a_a_temporal_text_deep_dive.ipynb +961 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01a_temporal_deep_dive.ipynb +1690 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01b_temporal_quality.ipynb +679 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01c_temporal_patterns.ipynb +3305 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/01d_event_aggregation.ipynb +1463 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/02_column_deep_dive.ipynb +1430 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/02a_text_columns_deep_dive.ipynb +854 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/03_quality_assessment.ipynb +1639 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/04_relationship_analysis.ipynb +1890 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/05_multi_dataset.ipynb +1457 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/06_feature_opportunities.ipynb +1624 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/07_modeling_readiness.ipynb +780 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/08_baseline_experiments.ipynb +979 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/09_business_alignment.ipynb +572 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/10_spec_generation.ipynb +1179 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/11_scoring_validation.ipynb +1418 -0
- churnkit-0.75.0a1.data/data/share/churnkit/exploration_notebooks/12_view_documentation.ipynb +151 -0
- churnkit-0.75.0a1.dist-info/METADATA +229 -0
- churnkit-0.75.0a1.dist-info/RECORD +302 -0
- churnkit-0.75.0a1.dist-info/WHEEL +4 -0
- churnkit-0.75.0a1.dist-info/entry_points.txt +2 -0
- churnkit-0.75.0a1.dist-info/licenses/LICENSE +202 -0
- customer_retention/__init__.py +37 -0
- customer_retention/analysis/__init__.py +0 -0
- customer_retention/analysis/auto_explorer/__init__.py +62 -0
- customer_retention/analysis/auto_explorer/exploration_manager.py +470 -0
- customer_retention/analysis/auto_explorer/explorer.py +258 -0
- customer_retention/analysis/auto_explorer/findings.py +291 -0
- customer_retention/analysis/auto_explorer/layered_recommendations.py +485 -0
- customer_retention/analysis/auto_explorer/recommendation_builder.py +148 -0
- customer_retention/analysis/auto_explorer/recommendations.py +418 -0
- customer_retention/analysis/business/__init__.py +26 -0
- customer_retention/analysis/business/ab_test_designer.py +144 -0
- customer_retention/analysis/business/fairness_analyzer.py +166 -0
- customer_retention/analysis/business/intervention_matcher.py +121 -0
- customer_retention/analysis/business/report_generator.py +222 -0
- customer_retention/analysis/business/risk_profile.py +199 -0
- customer_retention/analysis/business/roi_analyzer.py +139 -0
- customer_retention/analysis/diagnostics/__init__.py +20 -0
- customer_retention/analysis/diagnostics/calibration_analyzer.py +133 -0
- customer_retention/analysis/diagnostics/cv_analyzer.py +144 -0
- customer_retention/analysis/diagnostics/error_analyzer.py +107 -0
- customer_retention/analysis/diagnostics/leakage_detector.py +394 -0
- customer_retention/analysis/diagnostics/noise_tester.py +140 -0
- customer_retention/analysis/diagnostics/overfitting_analyzer.py +190 -0
- customer_retention/analysis/diagnostics/segment_analyzer.py +122 -0
- customer_retention/analysis/discovery/__init__.py +8 -0
- customer_retention/analysis/discovery/config_generator.py +49 -0
- customer_retention/analysis/discovery/discovery_flow.py +19 -0
- customer_retention/analysis/discovery/type_inferencer.py +147 -0
- customer_retention/analysis/interpretability/__init__.py +13 -0
- customer_retention/analysis/interpretability/cohort_analyzer.py +185 -0
- customer_retention/analysis/interpretability/counterfactual.py +175 -0
- customer_retention/analysis/interpretability/individual_explainer.py +141 -0
- customer_retention/analysis/interpretability/pdp_generator.py +103 -0
- customer_retention/analysis/interpretability/shap_explainer.py +106 -0
- customer_retention/analysis/jupyter_save_hook.py +28 -0
- customer_retention/analysis/notebook_html_exporter.py +136 -0
- customer_retention/analysis/notebook_progress.py +60 -0
- customer_retention/analysis/plotly_preprocessor.py +154 -0
- customer_retention/analysis/recommendations/__init__.py +54 -0
- customer_retention/analysis/recommendations/base.py +158 -0
- customer_retention/analysis/recommendations/cleaning/__init__.py +11 -0
- customer_retention/analysis/recommendations/cleaning/consistency.py +107 -0
- customer_retention/analysis/recommendations/cleaning/deduplicate.py +94 -0
- customer_retention/analysis/recommendations/cleaning/impute.py +67 -0
- customer_retention/analysis/recommendations/cleaning/outlier.py +71 -0
- customer_retention/analysis/recommendations/datetime/__init__.py +3 -0
- customer_retention/analysis/recommendations/datetime/extract.py +149 -0
- customer_retention/analysis/recommendations/encoding/__init__.py +3 -0
- customer_retention/analysis/recommendations/encoding/categorical.py +114 -0
- customer_retention/analysis/recommendations/pipeline.py +74 -0
- customer_retention/analysis/recommendations/registry.py +76 -0
- customer_retention/analysis/recommendations/selection/__init__.py +3 -0
- customer_retention/analysis/recommendations/selection/drop_column.py +56 -0
- customer_retention/analysis/recommendations/transform/__init__.py +4 -0
- customer_retention/analysis/recommendations/transform/power.py +94 -0
- customer_retention/analysis/recommendations/transform/scale.py +112 -0
- customer_retention/analysis/visualization/__init__.py +15 -0
- customer_retention/analysis/visualization/chart_builder.py +2619 -0
- customer_retention/analysis/visualization/console.py +122 -0
- customer_retention/analysis/visualization/display.py +171 -0
- customer_retention/analysis/visualization/number_formatter.py +36 -0
- customer_retention/artifacts/__init__.py +3 -0
- customer_retention/artifacts/fit_artifact_registry.py +146 -0
- customer_retention/cli.py +93 -0
- customer_retention/core/__init__.py +0 -0
- customer_retention/core/compat/__init__.py +193 -0
- customer_retention/core/compat/detection.py +99 -0
- customer_retention/core/compat/ops.py +48 -0
- customer_retention/core/compat/pandas_backend.py +57 -0
- customer_retention/core/compat/spark_backend.py +75 -0
- customer_retention/core/components/__init__.py +11 -0
- customer_retention/core/components/base.py +79 -0
- customer_retention/core/components/components/__init__.py +13 -0
- customer_retention/core/components/components/deployer.py +26 -0
- customer_retention/core/components/components/explainer.py +26 -0
- customer_retention/core/components/components/feature_eng.py +33 -0
- customer_retention/core/components/components/ingester.py +34 -0
- customer_retention/core/components/components/profiler.py +34 -0
- customer_retention/core/components/components/trainer.py +38 -0
- customer_retention/core/components/components/transformer.py +36 -0
- customer_retention/core/components/components/validator.py +37 -0
- customer_retention/core/components/enums.py +33 -0
- customer_retention/core/components/orchestrator.py +94 -0
- customer_retention/core/components/registry.py +59 -0
- customer_retention/core/config/__init__.py +39 -0
- customer_retention/core/config/column_config.py +95 -0
- customer_retention/core/config/experiments.py +71 -0
- customer_retention/core/config/pipeline_config.py +117 -0
- customer_retention/core/config/source_config.py +83 -0
- customer_retention/core/utils/__init__.py +28 -0
- customer_retention/core/utils/leakage.py +85 -0
- customer_retention/core/utils/severity.py +53 -0
- customer_retention/core/utils/statistics.py +90 -0
- customer_retention/generators/__init__.py +0 -0
- customer_retention/generators/notebook_generator/__init__.py +167 -0
- customer_retention/generators/notebook_generator/base.py +55 -0
- customer_retention/generators/notebook_generator/cell_builder.py +49 -0
- customer_retention/generators/notebook_generator/config.py +47 -0
- customer_retention/generators/notebook_generator/databricks_generator.py +48 -0
- customer_retention/generators/notebook_generator/local_generator.py +48 -0
- customer_retention/generators/notebook_generator/project_init.py +174 -0
- customer_retention/generators/notebook_generator/runner.py +150 -0
- customer_retention/generators/notebook_generator/script_generator.py +110 -0
- customer_retention/generators/notebook_generator/stages/__init__.py +19 -0
- customer_retention/generators/notebook_generator/stages/base_stage.py +86 -0
- customer_retention/generators/notebook_generator/stages/s01_ingestion.py +100 -0
- customer_retention/generators/notebook_generator/stages/s02_profiling.py +95 -0
- customer_retention/generators/notebook_generator/stages/s03_cleaning.py +180 -0
- customer_retention/generators/notebook_generator/stages/s04_transformation.py +165 -0
- customer_retention/generators/notebook_generator/stages/s05_feature_engineering.py +115 -0
- customer_retention/generators/notebook_generator/stages/s06_feature_selection.py +97 -0
- customer_retention/generators/notebook_generator/stages/s07_model_training.py +176 -0
- customer_retention/generators/notebook_generator/stages/s08_deployment.py +81 -0
- customer_retention/generators/notebook_generator/stages/s09_monitoring.py +112 -0
- customer_retention/generators/notebook_generator/stages/s10_batch_inference.py +642 -0
- customer_retention/generators/notebook_generator/stages/s11_feature_store.py +348 -0
- customer_retention/generators/orchestration/__init__.py +23 -0
- customer_retention/generators/orchestration/code_generator.py +196 -0
- customer_retention/generators/orchestration/context.py +147 -0
- customer_retention/generators/orchestration/data_materializer.py +188 -0
- customer_retention/generators/orchestration/databricks_exporter.py +411 -0
- customer_retention/generators/orchestration/doc_generator.py +311 -0
- customer_retention/generators/pipeline_generator/__init__.py +26 -0
- customer_retention/generators/pipeline_generator/findings_parser.py +727 -0
- customer_retention/generators/pipeline_generator/generator.py +142 -0
- customer_retention/generators/pipeline_generator/models.py +166 -0
- customer_retention/generators/pipeline_generator/renderer.py +2125 -0
- customer_retention/generators/spec_generator/__init__.py +37 -0
- customer_retention/generators/spec_generator/databricks_generator.py +433 -0
- customer_retention/generators/spec_generator/generic_generator.py +373 -0
- customer_retention/generators/spec_generator/mlflow_pipeline_generator.py +685 -0
- customer_retention/generators/spec_generator/pipeline_spec.py +298 -0
- customer_retention/integrations/__init__.py +0 -0
- customer_retention/integrations/adapters/__init__.py +13 -0
- customer_retention/integrations/adapters/base.py +10 -0
- customer_retention/integrations/adapters/factory.py +25 -0
- customer_retention/integrations/adapters/feature_store/__init__.py +6 -0
- customer_retention/integrations/adapters/feature_store/base.py +57 -0
- customer_retention/integrations/adapters/feature_store/databricks.py +94 -0
- customer_retention/integrations/adapters/feature_store/feast_adapter.py +97 -0
- customer_retention/integrations/adapters/feature_store/local.py +75 -0
- customer_retention/integrations/adapters/mlflow/__init__.py +6 -0
- customer_retention/integrations/adapters/mlflow/base.py +32 -0
- customer_retention/integrations/adapters/mlflow/databricks.py +54 -0
- customer_retention/integrations/adapters/mlflow/experiment_tracker.py +161 -0
- customer_retention/integrations/adapters/mlflow/local.py +50 -0
- customer_retention/integrations/adapters/storage/__init__.py +5 -0
- customer_retention/integrations/adapters/storage/base.py +33 -0
- customer_retention/integrations/adapters/storage/databricks.py +76 -0
- customer_retention/integrations/adapters/storage/local.py +59 -0
- customer_retention/integrations/feature_store/__init__.py +47 -0
- customer_retention/integrations/feature_store/definitions.py +215 -0
- customer_retention/integrations/feature_store/manager.py +744 -0
- customer_retention/integrations/feature_store/registry.py +412 -0
- customer_retention/integrations/iteration/__init__.py +28 -0
- customer_retention/integrations/iteration/context.py +212 -0
- customer_retention/integrations/iteration/feedback_collector.py +184 -0
- customer_retention/integrations/iteration/orchestrator.py +168 -0
- customer_retention/integrations/iteration/recommendation_tracker.py +341 -0
- customer_retention/integrations/iteration/signals.py +212 -0
- customer_retention/integrations/llm_context/__init__.py +4 -0
- customer_retention/integrations/llm_context/context_builder.py +201 -0
- customer_retention/integrations/llm_context/prompts.py +100 -0
- customer_retention/integrations/streaming/__init__.py +103 -0
- customer_retention/integrations/streaming/batch_integration.py +149 -0
- customer_retention/integrations/streaming/early_warning_model.py +227 -0
- customer_retention/integrations/streaming/event_schema.py +214 -0
- customer_retention/integrations/streaming/online_store_writer.py +249 -0
- customer_retention/integrations/streaming/realtime_scorer.py +261 -0
- customer_retention/integrations/streaming/trigger_engine.py +293 -0
- customer_retention/integrations/streaming/window_aggregator.py +393 -0
- customer_retention/stages/__init__.py +0 -0
- customer_retention/stages/cleaning/__init__.py +9 -0
- customer_retention/stages/cleaning/base.py +28 -0
- customer_retention/stages/cleaning/missing_handler.py +160 -0
- customer_retention/stages/cleaning/outlier_handler.py +204 -0
- customer_retention/stages/deployment/__init__.py +28 -0
- customer_retention/stages/deployment/batch_scorer.py +106 -0
- customer_retention/stages/deployment/champion_challenger.py +299 -0
- customer_retention/stages/deployment/model_registry.py +182 -0
- customer_retention/stages/deployment/retraining_trigger.py +245 -0
- customer_retention/stages/features/__init__.py +73 -0
- customer_retention/stages/features/behavioral_features.py +266 -0
- customer_retention/stages/features/customer_segmentation.py +505 -0
- customer_retention/stages/features/feature_definitions.py +265 -0
- customer_retention/stages/features/feature_engineer.py +551 -0
- customer_retention/stages/features/feature_manifest.py +340 -0
- customer_retention/stages/features/feature_selector.py +239 -0
- customer_retention/stages/features/interaction_features.py +160 -0
- customer_retention/stages/features/temporal_features.py +243 -0
- customer_retention/stages/ingestion/__init__.py +9 -0
- customer_retention/stages/ingestion/load_result.py +32 -0
- customer_retention/stages/ingestion/loaders.py +195 -0
- customer_retention/stages/ingestion/source_registry.py +130 -0
- customer_retention/stages/modeling/__init__.py +31 -0
- customer_retention/stages/modeling/baseline_trainer.py +139 -0
- customer_retention/stages/modeling/cross_validator.py +125 -0
- customer_retention/stages/modeling/data_splitter.py +205 -0
- customer_retention/stages/modeling/feature_scaler.py +99 -0
- customer_retention/stages/modeling/hyperparameter_tuner.py +107 -0
- customer_retention/stages/modeling/imbalance_handler.py +282 -0
- customer_retention/stages/modeling/mlflow_logger.py +95 -0
- customer_retention/stages/modeling/model_comparator.py +149 -0
- customer_retention/stages/modeling/model_evaluator.py +138 -0
- customer_retention/stages/modeling/threshold_optimizer.py +131 -0
- customer_retention/stages/monitoring/__init__.py +37 -0
- customer_retention/stages/monitoring/alert_manager.py +328 -0
- customer_retention/stages/monitoring/drift_detector.py +201 -0
- customer_retention/stages/monitoring/performance_monitor.py +242 -0
- customer_retention/stages/preprocessing/__init__.py +5 -0
- customer_retention/stages/preprocessing/transformer_manager.py +284 -0
- customer_retention/stages/profiling/__init__.py +256 -0
- customer_retention/stages/profiling/categorical_distribution.py +269 -0
- customer_retention/stages/profiling/categorical_target_analyzer.py +274 -0
- customer_retention/stages/profiling/column_profiler.py +527 -0
- customer_retention/stages/profiling/distribution_analysis.py +483 -0
- customer_retention/stages/profiling/drift_detector.py +310 -0
- customer_retention/stages/profiling/feature_capacity.py +507 -0
- customer_retention/stages/profiling/pattern_analysis_config.py +513 -0
- customer_retention/stages/profiling/profile_result.py +212 -0
- customer_retention/stages/profiling/quality_checks.py +1632 -0
- customer_retention/stages/profiling/relationship_detector.py +256 -0
- customer_retention/stages/profiling/relationship_recommender.py +454 -0
- customer_retention/stages/profiling/report_generator.py +520 -0
- customer_retention/stages/profiling/scd_analyzer.py +151 -0
- customer_retention/stages/profiling/segment_analyzer.py +632 -0
- customer_retention/stages/profiling/segment_aware_outlier.py +265 -0
- customer_retention/stages/profiling/target_level_analyzer.py +217 -0
- customer_retention/stages/profiling/temporal_analyzer.py +388 -0
- customer_retention/stages/profiling/temporal_coverage.py +488 -0
- customer_retention/stages/profiling/temporal_feature_analyzer.py +692 -0
- customer_retention/stages/profiling/temporal_feature_engineer.py +703 -0
- customer_retention/stages/profiling/temporal_pattern_analyzer.py +636 -0
- customer_retention/stages/profiling/temporal_quality_checks.py +278 -0
- customer_retention/stages/profiling/temporal_target_analyzer.py +241 -0
- customer_retention/stages/profiling/text_embedder.py +87 -0
- customer_retention/stages/profiling/text_processor.py +115 -0
- customer_retention/stages/profiling/text_reducer.py +60 -0
- customer_retention/stages/profiling/time_series_profiler.py +303 -0
- customer_retention/stages/profiling/time_window_aggregator.py +376 -0
- customer_retention/stages/profiling/type_detector.py +382 -0
- customer_retention/stages/profiling/window_recommendation.py +288 -0
- customer_retention/stages/temporal/__init__.py +166 -0
- customer_retention/stages/temporal/access_guard.py +180 -0
- customer_retention/stages/temporal/cutoff_analyzer.py +235 -0
- customer_retention/stages/temporal/data_preparer.py +178 -0
- customer_retention/stages/temporal/point_in_time_join.py +134 -0
- customer_retention/stages/temporal/point_in_time_registry.py +148 -0
- customer_retention/stages/temporal/scenario_detector.py +163 -0
- customer_retention/stages/temporal/snapshot_manager.py +259 -0
- customer_retention/stages/temporal/synthetic_coordinator.py +66 -0
- customer_retention/stages/temporal/timestamp_discovery.py +531 -0
- customer_retention/stages/temporal/timestamp_manager.py +255 -0
- customer_retention/stages/transformation/__init__.py +13 -0
- customer_retention/stages/transformation/binary_handler.py +85 -0
- customer_retention/stages/transformation/categorical_encoder.py +245 -0
- customer_retention/stages/transformation/datetime_transformer.py +97 -0
- customer_retention/stages/transformation/numeric_transformer.py +181 -0
- customer_retention/stages/transformation/pipeline.py +257 -0
- customer_retention/stages/validation/__init__.py +60 -0
- customer_retention/stages/validation/adversarial_scoring_validator.py +205 -0
- customer_retention/stages/validation/business_sense_gate.py +173 -0
- customer_retention/stages/validation/data_quality_gate.py +235 -0
- customer_retention/stages/validation/data_validators.py +511 -0
- customer_retention/stages/validation/feature_quality_gate.py +183 -0
- customer_retention/stages/validation/gates.py +117 -0
- customer_retention/stages/validation/leakage_gate.py +352 -0
- customer_retention/stages/validation/model_validity_gate.py +213 -0
- customer_retention/stages/validation/pipeline_validation_runner.py +264 -0
- customer_retention/stages/validation/quality_scorer.py +544 -0
- customer_retention/stages/validation/rule_generator.py +57 -0
- customer_retention/stages/validation/scoring_pipeline_validator.py +446 -0
- customer_retention/stages/validation/timeseries_detector.py +769 -0
- customer_retention/transforms/__init__.py +47 -0
- customer_retention/transforms/artifact_store.py +50 -0
- customer_retention/transforms/executor.py +157 -0
- customer_retention/transforms/fitted.py +92 -0
- customer_retention/transforms/ops.py +148 -0
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
from dataclasses import dataclass, field
|
|
2
|
+
from enum import Enum
|
|
3
|
+
from typing import Any, Dict, List, Optional
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
|
|
8
|
+
from customer_retention.core.compat import Series, ensure_pandas_series
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class TemporalGranularity(Enum):
|
|
12
|
+
DAY = "day"
|
|
13
|
+
WEEK = "week"
|
|
14
|
+
MONTH = "month"
|
|
15
|
+
QUARTER = "quarter"
|
|
16
|
+
YEAR = "year"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class SeasonalityResult:
|
|
21
|
+
has_seasonality: bool
|
|
22
|
+
dominant_period: Optional[str] = None # 'weekly', 'monthly', 'yearly'
|
|
23
|
+
peak_periods: List[str] = field(default_factory=list)
|
|
24
|
+
trough_periods: List[str] = field(default_factory=list)
|
|
25
|
+
monthly_pattern: Optional[pd.DataFrame] = None # year x month heatmap data
|
|
26
|
+
weekly_pattern: Optional[pd.Series] = None # day of week counts
|
|
27
|
+
confidence: float = 0.0
|
|
28
|
+
seasonal_strength: float = 0.0
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class TemporalRecommendationType(Enum):
|
|
32
|
+
FEATURE_ENGINEERING = "feature_engineering" # Create new feature from date
|
|
33
|
+
MODELING_STRATEGY = "modeling_strategy" # How to handle in train/test
|
|
34
|
+
DATA_QUALITY = "data_quality" # Quality issue to address
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass
|
|
38
|
+
class TemporalRecommendation:
|
|
39
|
+
feature_name: str
|
|
40
|
+
recommendation_type: TemporalRecommendationType
|
|
41
|
+
category: str # 'recency', 'duration', 'cyclical', 'extraction', 'tenure', 'split', 'filter'
|
|
42
|
+
reason: str
|
|
43
|
+
priority: str # 'high', 'medium', 'low'
|
|
44
|
+
code_hint: Optional[str] = None
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def action_description(self) -> str:
|
|
48
|
+
if self.recommendation_type == TemporalRecommendationType.FEATURE_ENGINEERING:
|
|
49
|
+
return f"Create feature: {self.feature_name}"
|
|
50
|
+
elif self.recommendation_type == TemporalRecommendationType.MODELING_STRATEGY:
|
|
51
|
+
return f"Modeling: {self.feature_name}"
|
|
52
|
+
else:
|
|
53
|
+
return f"Data quality: {self.feature_name}"
|
|
54
|
+
|
|
55
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
56
|
+
return {
|
|
57
|
+
"feature_name": self.feature_name,
|
|
58
|
+
"recommendation_type": self.recommendation_type.value,
|
|
59
|
+
"category": self.category,
|
|
60
|
+
"reason": self.reason,
|
|
61
|
+
"priority": self.priority,
|
|
62
|
+
"code_hint": self.code_hint,
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass
|
|
67
|
+
class TemporalAnalysis:
|
|
68
|
+
granularity: TemporalGranularity
|
|
69
|
+
min_date: pd.Timestamp
|
|
70
|
+
max_date: pd.Timestamp
|
|
71
|
+
span_days: int
|
|
72
|
+
total_count: int
|
|
73
|
+
null_count: int
|
|
74
|
+
period_counts: pd.DataFrame
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def null_percentage(self) -> float:
|
|
78
|
+
return (self.null_count / self.total_count * 100) if self.total_count > 0 else 0.0
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class TemporalAnalyzer:
|
|
82
|
+
GRANULARITY_THRESHOLDS = {
|
|
83
|
+
90: TemporalGranularity.DAY, # <= 90 days: daily
|
|
84
|
+
365: TemporalGranularity.WEEK, # <= 1 year: weekly
|
|
85
|
+
730: TemporalGranularity.MONTH, # <= 2 years: monthly
|
|
86
|
+
1825: TemporalGranularity.QUARTER, # <= 5 years: quarterly
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
def detect_granularity(self, dates: Series) -> TemporalGranularity:
|
|
90
|
+
dates = ensure_pandas_series(dates)
|
|
91
|
+
clean_dates = pd.to_datetime(dates, errors="coerce").dropna()
|
|
92
|
+
if len(clean_dates) == 0:
|
|
93
|
+
return TemporalGranularity.MONTH
|
|
94
|
+
|
|
95
|
+
span_days = (clean_dates.max() - clean_dates.min()).days
|
|
96
|
+
for threshold, granularity in self.GRANULARITY_THRESHOLDS.items():
|
|
97
|
+
if span_days <= threshold:
|
|
98
|
+
return granularity
|
|
99
|
+
return TemporalGranularity.YEAR
|
|
100
|
+
|
|
101
|
+
def aggregate_by_granularity(
|
|
102
|
+
self, dates: Series, granularity: TemporalGranularity
|
|
103
|
+
) -> pd.DataFrame:
|
|
104
|
+
dates = ensure_pandas_series(dates)
|
|
105
|
+
clean_dates = pd.to_datetime(dates, errors="coerce").dropna()
|
|
106
|
+
if len(clean_dates) == 0:
|
|
107
|
+
return pd.DataFrame({"period": [], "count": []})
|
|
108
|
+
|
|
109
|
+
period_series = self._extract_period(clean_dates, granularity)
|
|
110
|
+
counts = period_series.value_counts().sort_index().reset_index()
|
|
111
|
+
counts.columns = ["period", "count"]
|
|
112
|
+
return counts
|
|
113
|
+
|
|
114
|
+
def _extract_period(
|
|
115
|
+
self, dates: pd.Series, granularity: TemporalGranularity
|
|
116
|
+
) -> pd.Series:
|
|
117
|
+
if granularity == TemporalGranularity.DAY:
|
|
118
|
+
return dates.dt.strftime("%Y-%m-%d")
|
|
119
|
+
elif granularity == TemporalGranularity.WEEK:
|
|
120
|
+
return dates.dt.to_period("W").astype(str)
|
|
121
|
+
elif granularity == TemporalGranularity.MONTH:
|
|
122
|
+
return dates.dt.to_period("M").astype(str)
|
|
123
|
+
elif granularity == TemporalGranularity.QUARTER:
|
|
124
|
+
return dates.dt.to_period("Q").astype(str)
|
|
125
|
+
else: # YEAR
|
|
126
|
+
return dates.dt.year
|
|
127
|
+
|
|
128
|
+
def analyze(
|
|
129
|
+
self,
|
|
130
|
+
dates: Series,
|
|
131
|
+
granularity: Optional[TemporalGranularity] = None,
|
|
132
|
+
) -> TemporalAnalysis:
|
|
133
|
+
dates = ensure_pandas_series(dates)
|
|
134
|
+
total_count = len(dates)
|
|
135
|
+
parsed_dates = pd.to_datetime(dates, errors="coerce")
|
|
136
|
+
null_count = parsed_dates.isna().sum()
|
|
137
|
+
clean_dates = parsed_dates.dropna()
|
|
138
|
+
|
|
139
|
+
if len(clean_dates) == 0:
|
|
140
|
+
return TemporalAnalysis(
|
|
141
|
+
granularity=granularity or TemporalGranularity.MONTH,
|
|
142
|
+
min_date=pd.NaT,
|
|
143
|
+
max_date=pd.NaT,
|
|
144
|
+
span_days=0,
|
|
145
|
+
total_count=total_count,
|
|
146
|
+
null_count=null_count,
|
|
147
|
+
period_counts=pd.DataFrame({"period": [], "count": []}),
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
detected_granularity = granularity or self.detect_granularity(clean_dates)
|
|
151
|
+
period_counts = self.aggregate_by_granularity(clean_dates, detected_granularity)
|
|
152
|
+
|
|
153
|
+
return TemporalAnalysis(
|
|
154
|
+
granularity=detected_granularity,
|
|
155
|
+
min_date=clean_dates.min(),
|
|
156
|
+
max_date=clean_dates.max(),
|
|
157
|
+
span_days=(clean_dates.max() - clean_dates.min()).days,
|
|
158
|
+
total_count=total_count,
|
|
159
|
+
null_count=null_count,
|
|
160
|
+
period_counts=period_counts,
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
def analyze_seasonality(self, dates: Series) -> SeasonalityResult:
|
|
164
|
+
"""Analyze seasonality patterns in datetime data."""
|
|
165
|
+
dates = ensure_pandas_series(dates)
|
|
166
|
+
parsed = pd.to_datetime(dates, errors="coerce").dropna()
|
|
167
|
+
|
|
168
|
+
if len(parsed) < 30:
|
|
169
|
+
return SeasonalityResult(has_seasonality=False, confidence=0.0)
|
|
170
|
+
|
|
171
|
+
# Weekly pattern (day of week)
|
|
172
|
+
dow_counts = parsed.dt.dayofweek.value_counts().sort_index()
|
|
173
|
+
dow_names = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
|
|
174
|
+
weekly_pattern = pd.Series(
|
|
175
|
+
[dow_counts.get(i, 0) for i in range(7)], index=dow_names
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
# Monthly pattern (year x month heatmap)
|
|
179
|
+
monthly_df = parsed.to_frame(name="date")
|
|
180
|
+
monthly_df["year"] = parsed.dt.year
|
|
181
|
+
monthly_df["month"] = parsed.dt.month
|
|
182
|
+
monthly_pivot = monthly_df.groupby(["year", "month"]).size().unstack(fill_value=0)
|
|
183
|
+
monthly_pivot.columns = [
|
|
184
|
+
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
|
|
185
|
+
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
|
|
186
|
+
][:len(monthly_pivot.columns)]
|
|
187
|
+
|
|
188
|
+
# Detect seasonality strength
|
|
189
|
+
weekly_cv = weekly_pattern.std() / weekly_pattern.mean() if weekly_pattern.mean() > 0 else 0
|
|
190
|
+
|
|
191
|
+
# Find peaks and troughs
|
|
192
|
+
monthly_totals = parsed.dt.month.value_counts().sort_index()
|
|
193
|
+
month_names = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
|
|
194
|
+
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
|
|
195
|
+
|
|
196
|
+
if len(monthly_totals) >= 3:
|
|
197
|
+
peak_months = monthly_totals.nlargest(3).index.tolist()
|
|
198
|
+
trough_months = monthly_totals.nsmallest(3).index.tolist()
|
|
199
|
+
peak_periods = [month_names[m - 1] for m in peak_months if m <= 12]
|
|
200
|
+
trough_periods = [month_names[m - 1] for m in trough_months if m <= 12]
|
|
201
|
+
else:
|
|
202
|
+
peak_periods = []
|
|
203
|
+
trough_periods = []
|
|
204
|
+
|
|
205
|
+
# Determine dominant pattern
|
|
206
|
+
has_seasonality = weekly_cv > 0.15
|
|
207
|
+
dominant_period = "weekly" if weekly_cv > 0.2 else None
|
|
208
|
+
|
|
209
|
+
return SeasonalityResult(
|
|
210
|
+
has_seasonality=has_seasonality,
|
|
211
|
+
dominant_period=dominant_period,
|
|
212
|
+
peak_periods=peak_periods,
|
|
213
|
+
trough_periods=trough_periods,
|
|
214
|
+
monthly_pattern=monthly_pivot,
|
|
215
|
+
weekly_pattern=weekly_pattern,
|
|
216
|
+
confidence=min(1.0, weekly_cv * 2) if has_seasonality else 0.0,
|
|
217
|
+
seasonal_strength=float(weekly_cv),
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
def year_over_year_comparison(self, dates: Series) -> pd.DataFrame:
|
|
221
|
+
"""Compare record counts year-over-year by month."""
|
|
222
|
+
dates = ensure_pandas_series(dates)
|
|
223
|
+
parsed = pd.to_datetime(dates, errors="coerce").dropna()
|
|
224
|
+
|
|
225
|
+
if len(parsed) == 0:
|
|
226
|
+
return pd.DataFrame()
|
|
227
|
+
|
|
228
|
+
df = parsed.to_frame(name="date")
|
|
229
|
+
df["year"] = parsed.dt.year
|
|
230
|
+
df["month"] = parsed.dt.month
|
|
231
|
+
|
|
232
|
+
pivot = df.groupby(["year", "month"]).size().unstack(fill_value=0)
|
|
233
|
+
pivot.columns = [
|
|
234
|
+
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
|
|
235
|
+
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
|
|
236
|
+
][:len(pivot.columns)]
|
|
237
|
+
|
|
238
|
+
return pivot
|
|
239
|
+
|
|
240
|
+
def calculate_growth_rate(self, dates: Series) -> Dict[str, Any]:
|
|
241
|
+
"""Calculate growth metrics over time."""
|
|
242
|
+
dates = ensure_pandas_series(dates)
|
|
243
|
+
parsed = pd.to_datetime(dates, errors="coerce").dropna()
|
|
244
|
+
|
|
245
|
+
if len(parsed) < 2:
|
|
246
|
+
return {"has_data": False}
|
|
247
|
+
|
|
248
|
+
# Monthly counts
|
|
249
|
+
monthly = parsed.dt.to_period("M").value_counts().sort_index()
|
|
250
|
+
|
|
251
|
+
if len(monthly) < 2:
|
|
252
|
+
return {"has_data": False}
|
|
253
|
+
|
|
254
|
+
# Calculate month-over-month growth
|
|
255
|
+
mom_growth = monthly.pct_change().dropna()
|
|
256
|
+
|
|
257
|
+
# Calculate cumulative
|
|
258
|
+
cumulative = monthly.cumsum()
|
|
259
|
+
|
|
260
|
+
# Linear trend
|
|
261
|
+
x = np.arange(len(monthly))
|
|
262
|
+
y = monthly.values
|
|
263
|
+
slope, intercept = np.polyfit(x, y, 1)
|
|
264
|
+
trend_direction = "growing" if slope > 0 else "declining"
|
|
265
|
+
|
|
266
|
+
# Overall growth rate
|
|
267
|
+
overall_growth = ((monthly.iloc[-1] - monthly.iloc[0]) / monthly.iloc[0] * 100) if monthly.iloc[0] > 0 else 0
|
|
268
|
+
|
|
269
|
+
return {
|
|
270
|
+
"has_data": True,
|
|
271
|
+
"monthly_counts": monthly,
|
|
272
|
+
"cumulative": cumulative,
|
|
273
|
+
"avg_monthly_growth": float(mom_growth.mean() * 100),
|
|
274
|
+
"overall_growth_pct": float(overall_growth),
|
|
275
|
+
"trend_direction": trend_direction,
|
|
276
|
+
"trend_slope": float(slope),
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
def recommend_features(
|
|
280
|
+
self, dates: Series, column_name: str, other_date_columns: Optional[List[str]] = None
|
|
281
|
+
) -> List[TemporalRecommendation]:
|
|
282
|
+
dates = ensure_pandas_series(dates)
|
|
283
|
+
parsed = pd.to_datetime(dates, errors="coerce")
|
|
284
|
+
valid_dates = parsed.dropna()
|
|
285
|
+
recommendations = []
|
|
286
|
+
|
|
287
|
+
if len(valid_dates) == 0:
|
|
288
|
+
return recommendations
|
|
289
|
+
|
|
290
|
+
analysis = self.analyze(dates)
|
|
291
|
+
seasonality = self.analyze_seasonality(dates)
|
|
292
|
+
growth = self.calculate_growth_rate(dates)
|
|
293
|
+
|
|
294
|
+
# FEATURE ENGINEERING: Recency - always useful for dates
|
|
295
|
+
recommendations.append(TemporalRecommendation(
|
|
296
|
+
feature_name=f"days_since_{column_name}",
|
|
297
|
+
recommendation_type=TemporalRecommendationType.FEATURE_ENGINEERING,
|
|
298
|
+
category="recency",
|
|
299
|
+
reason="Recency captures how recent an event occurred - useful for predicting behavior",
|
|
300
|
+
priority="medium",
|
|
301
|
+
code_hint=f"(reference_date - df['{column_name}']).dt.days",
|
|
302
|
+
))
|
|
303
|
+
|
|
304
|
+
# FEATURE ENGINEERING: Duration between dates
|
|
305
|
+
if other_date_columns:
|
|
306
|
+
for other_col in other_date_columns:
|
|
307
|
+
recommendations.append(TemporalRecommendation(
|
|
308
|
+
feature_name=f"days_between_{column_name}_and_{other_col}",
|
|
309
|
+
recommendation_type=TemporalRecommendationType.FEATURE_ENGINEERING,
|
|
310
|
+
category="duration",
|
|
311
|
+
reason="Duration between events captures behavioral patterns (e.g., time to convert)",
|
|
312
|
+
priority="medium",
|
|
313
|
+
code_hint=f"(df['{other_col}'] - df['{column_name}']).dt.days",
|
|
314
|
+
))
|
|
315
|
+
|
|
316
|
+
# FEATURE ENGINEERING: Cyclical encoding for seasonality
|
|
317
|
+
if seasonality.has_seasonality and seasonality.seasonal_strength > 0.15:
|
|
318
|
+
priority = "high" if seasonality.seasonal_strength > 0.3 else "medium"
|
|
319
|
+
recommendations.append(TemporalRecommendation(
|
|
320
|
+
feature_name=f"{column_name}_month_sin_cos",
|
|
321
|
+
recommendation_type=TemporalRecommendationType.FEATURE_ENGINEERING,
|
|
322
|
+
category="cyclical",
|
|
323
|
+
reason=f"Seasonality detected (strength: {seasonality.seasonal_strength:.2f}) - cyclical encoding preserves month proximity (Dec near Jan)",
|
|
324
|
+
priority=priority,
|
|
325
|
+
code_hint=f"np.sin(2 * np.pi * df['{column_name}'].dt.month / 12)",
|
|
326
|
+
))
|
|
327
|
+
|
|
328
|
+
# MODELING STRATEGY: Time-based split for trends
|
|
329
|
+
if growth.get("has_data") and abs(growth.get("overall_growth_pct", 0)) > 50:
|
|
330
|
+
direction = growth["trend_direction"]
|
|
331
|
+
pct = growth["overall_growth_pct"]
|
|
332
|
+
recommendations.append(TemporalRecommendation(
|
|
333
|
+
feature_name="time_based_train_test_split",
|
|
334
|
+
recommendation_type=TemporalRecommendationType.MODELING_STRATEGY,
|
|
335
|
+
category="split",
|
|
336
|
+
reason=f"Significant {direction} trend ({pct:+.0f}%) detected - random splits would leak future patterns into training",
|
|
337
|
+
priority="high",
|
|
338
|
+
))
|
|
339
|
+
elif growth.get("has_data") and abs(growth.get("overall_growth_pct", 0)) > 20:
|
|
340
|
+
recommendations.append(TemporalRecommendation(
|
|
341
|
+
feature_name="time_aware_validation",
|
|
342
|
+
recommendation_type=TemporalRecommendationType.MODELING_STRATEGY,
|
|
343
|
+
category="split",
|
|
344
|
+
reason="Moderate trend detected - time-aware validation ensures model generalizes to future data",
|
|
345
|
+
priority="medium",
|
|
346
|
+
))
|
|
347
|
+
|
|
348
|
+
# FEATURE ENGINEERING: Tenure for long histories
|
|
349
|
+
if analysis.span_days > 365 * 2:
|
|
350
|
+
years = analysis.span_days / 365
|
|
351
|
+
recommendations.append(TemporalRecommendation(
|
|
352
|
+
feature_name=f"tenure_from_{column_name}",
|
|
353
|
+
recommendation_type=TemporalRecommendationType.FEATURE_ENGINEERING,
|
|
354
|
+
category="tenure",
|
|
355
|
+
reason=f"Long history ({years:.1f} years) enables tenure feature - captures customer maturity/loyalty",
|
|
356
|
+
priority="medium",
|
|
357
|
+
code_hint=f"(reference_date - df['{column_name}']).dt.days / 365",
|
|
358
|
+
))
|
|
359
|
+
|
|
360
|
+
# DATA QUALITY: Placeholder dates
|
|
361
|
+
placeholder_count = (valid_dates < "2000-01-01").sum()
|
|
362
|
+
if placeholder_count > 0:
|
|
363
|
+
pct = placeholder_count / len(valid_dates) * 100
|
|
364
|
+
recommendations.append(TemporalRecommendation(
|
|
365
|
+
feature_name=f"{column_name}_placeholder_flag",
|
|
366
|
+
recommendation_type=TemporalRecommendationType.DATA_QUALITY,
|
|
367
|
+
category="filter",
|
|
368
|
+
reason=f"Found {placeholder_count:,} dates before 2000 ({pct:.1f}%) - likely system defaults, not real dates",
|
|
369
|
+
priority="high",
|
|
370
|
+
code_hint=f"df['{column_name}'] < '2000-01-01'",
|
|
371
|
+
))
|
|
372
|
+
|
|
373
|
+
# FEATURE ENGINEERING: Weekend indicator
|
|
374
|
+
dow_counts = valid_dates.dt.dayofweek.value_counts()
|
|
375
|
+
if len(dow_counts) == 7:
|
|
376
|
+
dow_imbalance = dow_counts.max() / dow_counts.min() if dow_counts.min() > 0 else 1
|
|
377
|
+
if dow_imbalance > 1.5:
|
|
378
|
+
weekday_pct = dow_counts[dow_counts.index < 5].sum() / len(valid_dates) * 100
|
|
379
|
+
recommendations.append(TemporalRecommendation(
|
|
380
|
+
feature_name=f"{column_name}_is_weekend",
|
|
381
|
+
recommendation_type=TemporalRecommendationType.FEATURE_ENGINEERING,
|
|
382
|
+
category="extraction",
|
|
383
|
+
reason=f"Weekday/weekend imbalance ({weekday_pct:.0f}% weekday) suggests behavior differs by day type",
|
|
384
|
+
priority="low",
|
|
385
|
+
code_hint=f"df['{column_name}'].dt.dayofweek >= 5",
|
|
386
|
+
))
|
|
387
|
+
|
|
388
|
+
return recommendations
|