Repository navigation
Expand file tree
/
Copy pathbuild_data.py
More file actions
211 lines (183 loc) · 8.48 KB
/
Copy pathbuild_data.py
File metadata and controls
211 lines (183 loc) · 8.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
#!/usr/bin/env python3
"""Build an interview-ready airline operations scorecard from BTS flight data.
The script streams the official monthly CSV directly from the BTS zip archive,
aggregates operational KPIs, and writes compact JSON/JavaScript consumed by the
static dashboard. It intentionally keeps raw flight records out of the repo.
"""
from __future__ import annotations
import argparse
import csv
import json
import urllib.request
import zipfile
from collections import defaultdict
from datetime import date, datetime
from pathlib import Path
DATA_URL = (
"https://transtats.bts.gov/PREZIP/"
"On_Time_Marketing_Carrier_On_Time_Performance_"
"Beginning_January_2018_2026_7.zip"
)
REGIONS = {
"CT": "Northeast", "ME": "Northeast", "MA": "Northeast", "NH": "Northeast",
"RI": "Northeast", "VT": "Northeast", "NJ": "Northeast", "NY": "Northeast",
"PA": "Northeast", "IL": "Midwest", "IN": "Midwest", "MI": "Midwest",
"OH": "Midwest", "WI": "Midwest", "IA": "Midwest", "KS": "Midwest",
"MN": "Midwest", "MO": "Midwest", "NE": "Midwest", "ND": "Midwest",
"SD": "Midwest", "DE": "South", "FL": "South", "GA": "South",
"MD": "South", "NC": "South", "SC": "South", "VA": "South",
"DC": "South", "WV": "South", "AL": "South", "KY": "South",
"MS": "South", "TN": "South", "AR": "South", "LA": "South",
"OK": "South", "TX": "South", "AZ": "West", "CO": "West",
"ID": "West", "MT": "West", "NV": "West", "NM": "West",
"UT": "West", "WY": "West", "AK": "West", "CA": "West",
"HI": "West", "OR": "West", "WA": "West", "PR": "Other",
"VI": "Other", "TT": "Other",
}
CARRIER_NAMES = {
"AA": "American", "AS": "Alaska", "B6": "JetBlue", "DL": "Delta",
"F9": "Frontier", "G4": "Allegiant", "HA": "Hawaiian", "NK": "Spirit",
"UA": "United", "WN": "Southwest",
}
def number(value: str | None) -> float:
try:
return float(value or 0)
except ValueError:
return 0.0
def bucket() -> dict:
return {
"flights": 0, "completed": 0, "on_time": 0, "cancelled": 0, "diverted": 0,
"arr_delay": 0.0, "dep_delay": 0.0, "taxi_out": 0.0, "taxi_in": 0.0,
"carrier_delay": 0.0, "weather_delay": 0.0, "nas_delay": 0.0,
"security_delay": 0.0, "late_aircraft_delay": 0.0,
}
def add(target: dict, row: dict) -> None:
target["flights"] += 1
cancelled = number(row.get("Cancelled")) == 1
diverted = number(row.get("Diverted")) == 1
target["cancelled"] += int(cancelled)
target["diverted"] += int(diverted)
if not cancelled and not diverted:
target["completed"] += 1
target["on_time"] += int(number(row.get("ArrDelay")) <= 15)
target["arr_delay"] += number(row.get("ArrDelayMinutes"))
target["dep_delay"] += number(row.get("DepDelayMinutes"))
target["taxi_out"] += number(row.get("TaxiOut"))
target["taxi_in"] += number(row.get("TaxiIn"))
delay_fields = {
"CarrierDelay": "carrier_delay",
"WeatherDelay": "weather_delay",
"NASDelay": "nas_delay",
"SecurityDelay": "security_delay",
"LateAircraftDelay": "late_aircraft_delay",
}
for source, destination in delay_fields.items():
target[destination] += number(row.get(source))
def summarize(raw: dict) -> dict:
flights = max(raw["flights"], 1)
completed = max(raw["completed"], 1)
delay_total = sum(raw[k] for k in (
"carrier_delay", "weather_delay", "nas_delay", "security_delay", "late_aircraft_delay"
)) or 1
return {
"flights": raw["flights"],
"onTimeRate": round(100 * raw["on_time"] / completed, 1),
"avgArrivalDelay": round(raw["arr_delay"] / completed, 1),
"avgDepartureDelay": round(raw["dep_delay"] / completed, 1),
"cancellationRate": round(100 * raw["cancelled"] / flights, 2),
"diversionRate": round(100 * raw["diverted"] / flights, 2),
"avgTaxiOut": round(raw["taxi_out"] / completed, 1),
"avgTaxiIn": round(raw["taxi_in"] / completed, 1),
"carrierDelayShare": round(100 * raw["carrier_delay"] / delay_total, 1),
"weatherDelayShare": round(100 * raw["weather_delay"] / delay_total, 1),
}
def week_label(value: str) -> str:
day = datetime.strptime(value, "%Y-%m-%d").date()
start = day.replace(day=max(1, day.day - day.weekday()))
return start.isoformat()
def download(path: Path) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
print(f"Downloading {DATA_URL}")
urllib.request.urlretrieve(DATA_URL, path)
def build(zip_path: Path, output: Path) -> dict:
totals = defaultdict(bucket)
carriers = defaultdict(lambda: defaultdict(bucket))
airports = defaultdict(lambda: defaultdict(bucket))
causes = defaultdict(lambda: defaultdict(float))
weeks = set()
regions = {"National"}
record_count = 0
with zipfile.ZipFile(zip_path) as archive:
csv_name = next(name for name in archive.namelist() if name.lower().endswith(".csv"))
with archive.open(csv_name) as raw:
rows = csv.DictReader((line.decode("utf-8-sig") for line in raw))
for row in rows:
record_count += 1
week = week_label(row["FlightDate"])
region = REGIONS.get(row.get("OriginState", ""), "Other")
carrier = row.get("Marketing_Airline_Network", "Unknown").strip()
airport = row.get("Origin", "Unknown").strip()
weeks.add(week)
regions.add(region)
for region_key in ("National", region):
key = (week, region_key)
add(totals[key], row)
add(carriers[key][carrier], row)
add(airports[key][airport], row)
causes[key]["Carrier"] += number(row.get("CarrierDelay"))
causes[key]["Weather"] += number(row.get("WeatherDelay"))
causes[key]["Air system"] += number(row.get("NASDelay"))
causes[key]["Security"] += number(row.get("SecurityDelay"))
causes[key]["Late aircraft"] += number(row.get("LateAircraftDelay"))
segments = []
for (week, region), raw in sorted(totals.items()):
top_carriers = sorted(carriers[(week, region)].items(), key=lambda x: x[1]["flights"], reverse=True)[:8]
top_airports = sorted(airports[(week, region)].items(), key=lambda x: x[1]["flights"], reverse=True)[:10]
segments.append({
"week": week,
"region": region,
"metrics": summarize(raw),
"carriers": [
{"code": code, "name": CARRIER_NAMES.get(code, code), **summarize(value)}
for code, value in top_carriers
],
"airports": [
{"code": code, **summarize(value)} for code, value in top_airports
],
"causes": [
{"name": name, "minutes": round(minutes)}
for name, minutes in sorted(causes[(week, region)].items(), key=lambda x: x[1], reverse=True)
],
})
payload = {
"title": "Flight Operations Intelligence Copilot",
"source": "U.S. Department of Transportation, Bureau of Transportation Statistics",
"sourceUrl": "https://www.transtats.bts.gov/",
"period": "July 2026",
"generated": date.today().isoformat(),
"recordCount": record_count,
"weeks": sorted(weeks),
"regions": [r for r in ("National", "Northeast", "Midwest", "South", "West", "Other") if r in regions],
"segments": segments,
}
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(json.dumps(payload, indent=2), encoding="utf-8")
output.with_suffix(".js").write_text(
"window.FLIGHT_OPS_DATA = " + json.dumps(payload, separators=(",", ":")) + ";\n",
encoding="utf-8",
)
return payload
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--zip", type=Path, default=Path("data/bts_2026_07.zip"))
parser.add_argument("--output", type=Path, default=Path("data/dashboard_data.json"))
parser.add_argument("--download", action="store_true")
args = parser.parse_args()
if args.download and not args.zip.exists():
download(args.zip)
if not args.zip.exists():
raise SystemExit("Dataset zip not found. Run with --download or provide --zip PATH.")
payload = build(args.zip, args.output)
print(f"Processed {payload['recordCount']:,} flights into {len(payload['segments'])} scorecard segments.")
if __name__ == "__main__":
main()