← Back to case study

PROJECT 015 · PYTHON SOURCE

Daily peak concentration

Study-specific code. Shared modules, dependency versions, and reproduction instructions are included in all project files.

Download Python file ↓
from pathlib import Path
import sys
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT))
import numpy as np
import pandas as pd
from scipy.stats import spearmanr
from sklearn.decomposition import PCA
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix, precision_score, recall_score
from portfolio.data import load
from portfolio.constants import *
from portfolio.methods import result, sql, rates, associations, distribution, regression, classification, cluster
from portfolio.engine import execute

META = {'id': 15, 'dataset': 'bikes', 'title': 'Daily peak concentration', 'question': 'What share of a complete day’s rentals occurs in its four busiest hours?', 'method': 'Daily concentration restricted to dates with all 24 observed hours.', 'action': 'Evaluate peak service requirements with actual fleet and station constraints.', 'limitations': 'Historical system rentals measure realized use, not unmet demand or station inventory. Missing hours are unknown. Weather associations do not establish causal effects. '}

def analyze():
    df = load('bikes').copy()
    rows=[]
    for date,g in df.groupby('dteday'):
        if len(g)==24:
            rows.append({'month':str(date)[:7],'workingday':g.workingday.iloc[0],'top_four_share':g.cnt.nlargest(4).sum()/g.cnt.sum()})
    days=pd.DataFrame(rows)
    t=days.groupby('month').top_four_share.agg(complete_days='size',mean_peak_share='mean',median_peak_share='median').reset_index()
    out=result(t,'month','mean_peak_share','Share of daily rentals','Busiest hours are selected retrospectively for each day. This is not an advance peak-hour forecast.',extra={'daily_concentration':days})
    return out

if __name__ == "__main__":
    execute(Path(__file__).parent, META, analyze)