retailcal 1.0.0__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.
retailcal/__init__.py ADDED
@@ -0,0 +1,188 @@
1
+ #!/usr/bin/env python3
2
+ """52/53-week retail and fiscal calendars (4-4-5, 4-5-4, 5-4-4) - any variant.
3
+
4
+ Python 3 standard library only. MIT license.
5
+
6
+ A 52/53-week fiscal year always ends on the same weekday. Two common rules:
7
+ nearest: the year ends on that weekday NEAREST a month's last day
8
+ (NRF retail calendar: Saturday nearest January 31)
9
+ last: the year ends on the LAST such weekday of the month
10
+ The 13 weeks of each quarter are split into periods by the pattern
11
+ (4-4-5, 4-5-4 or 5-4-4). In a 53-week year the extra week goes to the last
12
+ period of the year (NRF practice), unless --extra-week-period says otherwise.
13
+
14
+ Fiscal year naming: "start" = named by the calendar year in which it starts
15
+ (NRF: fiscal 2025 = Feb 2 2025 - Jan 31 2026); "end" = by the year it ends.
16
+ For a December end month both namings give the same label: the calendar year
17
+ the fiscal year ends in (it starts in the last days of the previous December).
18
+
19
+ CLI:
20
+ retailcal --preset nrf-454 --from 2000 --to 2050 > nrf.csv
21
+ retailcal --end-month 9 --weekday sat --rule last --pattern 445 \
22
+ --naming end --from 2010 --to 2040 > fy.csv
23
+ retailcal --preset nrf-454 --year-table # one row per fiscal year
24
+ """
25
+ import argparse
26
+ import csv
27
+ import sys
28
+ from datetime import date, timedelta
29
+
30
+ WEEKDAYS = {"mon": 0, "tue": 1, "wed": 2, "thu": 3, "fri": 4, "sat": 5, "sun": 6}
31
+ PATTERNS = {"445": (4, 4, 5), "454": (4, 5, 4), "544": (5, 4, 4)}
32
+ PRESETS = {
33
+ # name: (end_month, weekday, rule, pattern, naming)
34
+ "nrf-454": (1, "sat", "nearest", "454", "start"),
35
+ "445-sat-nearest-dec": (12, "sat", "nearest", "445", "end"),
36
+ "445-sat-last-sep": (9, "sat", "last", "445", "end"),
37
+ "544-sat-nearest-dec": (12, "sat", "nearest", "544", "end"),
38
+ }
39
+
40
+ COLUMNS = ["date", "fiscal_year", "fiscal_quarter", "fiscal_period", "fiscal_week",
41
+ "week_of_period", "day_of_fiscal_year", "day_of_fiscal_week",
42
+ "fiscal_year_start", "fiscal_year_end", "period_start", "period_end",
43
+ "week_start", "week_end", "weeks_in_year", "is_53_week_year"]
44
+
45
+
46
+ class Calendar:
47
+ def __init__(self, end_month, weekday, rule="nearest", pattern="454", naming="start",
48
+ extra_week_period=12):
49
+ if rule not in ("nearest", "last"):
50
+ raise ValueError("rule must be nearest or last")
51
+ if naming not in ("start", "end"):
52
+ raise ValueError("naming must be start or end")
53
+ if not (isinstance(end_month, int) and 1 <= end_month <= 12):
54
+ raise ValueError("end_month must be 1-12")
55
+ if not (isinstance(extra_week_period, int) and 1 <= extra_week_period <= 12):
56
+ raise ValueError("extra_week_period must be 1-12")
57
+ if isinstance(weekday, str) and weekday.lower() not in WEEKDAYS:
58
+ raise ValueError("weekday must be one of %s" % ", ".join(WEEKDAYS))
59
+ if isinstance(pattern, str) and pattern not in PATTERNS:
60
+ raise ValueError("pattern must be 445, 454 or 544")
61
+ self.end_month = end_month
62
+ self.weekday = WEEKDAYS[weekday.lower()] if isinstance(weekday, str) else weekday
63
+ self.rule = rule
64
+ self.pattern = PATTERNS[pattern] if isinstance(pattern, str) else tuple(pattern)
65
+ self.naming = naming
66
+ self.extra_week_period = extra_week_period
67
+
68
+ def _month_end(self, y):
69
+ m = self.end_month
70
+ return date(y + (m == 12), m % 12 + 1, 1) - timedelta(days=1)
71
+
72
+ def year_end_in(self, y):
73
+ """Fiscal year-end date anchored on the end month of calendar year y."""
74
+ me = self._month_end(y)
75
+ back = (me.weekday() - self.weekday) % 7 # days back to the last such weekday
76
+ last = me - timedelta(days=back)
77
+ if self.rule == "last" or back <= 3:
78
+ return last
79
+ return last + timedelta(days=7)
80
+
81
+ def _anchor_year(self, fy):
82
+ """Calendar year (of the end month) in which fiscal year `fy` ends."""
83
+ if self.naming == "end":
84
+ return fy
85
+ # "start" naming: fy starts in calendar year fy, ends ~12 months later.
86
+ return fy + 1 if self.end_month < 12 else fy
87
+
88
+ def bounds(self, fy):
89
+ end = self.year_end_in(self._anchor_year(fy))
90
+ prev_end = self.year_end_in(self._anchor_year(fy) - 1)
91
+ return prev_end + timedelta(days=1), end
92
+
93
+ def fiscal_year_of(self, d):
94
+ guess = d.year if self.naming == "end" else d.year - (1 if self.end_month < 12 else 0)
95
+ for fy in (guess - 1, guess, guess + 1, guess + 2):
96
+ s, e = self.bounds(fy)
97
+ if s <= d <= e:
98
+ return fy
99
+ raise AssertionError("no fiscal year found for %s" % d)
100
+
101
+ def period_lengths(self, fy):
102
+ s, e = self.bounds(fy)
103
+ weeks = ((e - s).days + 1) // 7
104
+ lens = list(self.pattern) * 4
105
+ if weeks == 53:
106
+ lens[self.extra_week_period - 1] += 1
107
+ return lens, weeks
108
+
109
+ def row(self, d):
110
+ fy = self.fiscal_year_of(d)
111
+ s, e = self.bounds(fy)
112
+ lens, weeks = self.period_lengths(fy)
113
+ doy = (d - s).days + 1
114
+ wk = (doy - 1) // 7 + 1
115
+ acc, period = 0, 0
116
+ for i, n in enumerate(lens):
117
+ if wk <= acc + n:
118
+ period = i + 1
119
+ break
120
+ acc += n
121
+ p_start = s + timedelta(weeks=acc)
122
+ p_end = p_start + timedelta(weeks=lens[period - 1]) - timedelta(days=1)
123
+ w_start = s + timedelta(weeks=wk - 1)
124
+ return {
125
+ "date": d.isoformat(), "fiscal_year": fy, "fiscal_quarter": (period - 1) // 3 + 1,
126
+ "fiscal_period": period, "fiscal_week": wk, "week_of_period": wk - acc,
127
+ "day_of_fiscal_year": doy, "day_of_fiscal_week": (doy - 1) % 7 + 1,
128
+ "fiscal_year_start": s.isoformat(), "fiscal_year_end": e.isoformat(),
129
+ "period_start": p_start.isoformat(), "period_end": p_end.isoformat(),
130
+ "week_start": w_start.isoformat(), "week_end": (w_start + timedelta(days=6)).isoformat(),
131
+ "weeks_in_year": weeks, "is_53_week_year": int(weeks == 53),
132
+ }
133
+
134
+ def rows(self, fy_from, fy_to):
135
+ for fy in range(fy_from, fy_to + 1):
136
+ s, e = self.bounds(fy)
137
+ d = s
138
+ while d <= e:
139
+ yield self.row(d)
140
+ d += timedelta(days=1)
141
+
142
+ def year_rows(self, fy_from, fy_to):
143
+ for fy in range(fy_from, fy_to + 1):
144
+ s, e = self.bounds(fy)
145
+ lens, weeks = self.period_lengths(fy)
146
+ yield {"fiscal_year": fy, "fiscal_year_start": s.isoformat(), "fiscal_year_end": e.isoformat(),
147
+ "weeks": weeks, "period_weeks": "-".join(map(str, lens))}
148
+
149
+
150
+ def from_args(a):
151
+ if a.preset:
152
+ m, wd, rule, pat, naming = PRESETS[a.preset]
153
+ else:
154
+ m, wd, rule, pat, naming = a.end_month, a.weekday, a.rule, a.pattern, a.naming
155
+ return Calendar(m, wd, rule, pat, naming, a.extra_week_period)
156
+
157
+
158
+ def main(argv=None):
159
+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
160
+ ap.add_argument("--preset", choices=sorted(PRESETS))
161
+ ap.add_argument("--end-month", type=int, default=1)
162
+ ap.add_argument("--weekday", choices=sorted(WEEKDAYS), default="sat")
163
+ ap.add_argument("--rule", choices=["nearest", "last"], default="nearest")
164
+ ap.add_argument("--pattern", choices=sorted(PATTERNS), default="454")
165
+ ap.add_argument("--naming", choices=["start", "end"], default="start")
166
+ ap.add_argument("--extra-week-period", type=int, default=12)
167
+ ap.add_argument("--from", dest="fy_from", type=int, default=2000)
168
+ ap.add_argument("--to", dest="fy_to", type=int, default=2050)
169
+ ap.add_argument("--year-table", action="store_true")
170
+ a = ap.parse_args(argv)
171
+ try:
172
+ cal = from_args(a)
173
+ except ValueError as e:
174
+ ap.error(str(e))
175
+ w = csv.writer(sys.stdout, lineterminator="\n")
176
+ if a.year_table:
177
+ cols = ["fiscal_year", "fiscal_year_start", "fiscal_year_end", "weeks", "period_weeks"]
178
+ w.writerow(cols)
179
+ for r in cal.year_rows(a.fy_from, a.fy_to):
180
+ w.writerow([r[c] for c in cols])
181
+ else:
182
+ w.writerow(COLUMNS)
183
+ for r in cal.rows(a.fy_from, a.fy_to):
184
+ w.writerow([r[c] for c in COLUMNS])
185
+
186
+
187
+ if __name__ == "__main__":
188
+ main()
retailcal/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from . import main
2
+
3
+ main()
@@ -0,0 +1,83 @@
1
+ Metadata-Version: 2.4
2
+ Name: retailcal
3
+ Version: 1.0.0
4
+ Summary: 52/53-week retail and fiscal calendars (4-4-5, 4-5-4, 5-4-4, NRF-style) as CSV. Standard library only.
5
+ Author-email: Plainfold <plainfoldhq@proton.me>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/plainfoldhq/date-dimension
8
+ Keywords: fiscal calendar,retail calendar,4-4-5,4-5-4,5-4-4,52-53 week,NRF,date dimension,data warehouse
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Topic :: Office/Business :: Financial :: Accounting
13
+ Classifier: Topic :: Database
14
+ Requires-Python: >=3.8
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Dynamic: license-file
18
+
19
+ # Date dimension and 4-4-5 / 4-5-4 retail calendar generator
20
+
21
+ [![tests](https://github.com/plainfoldhq/date-dimension/actions/workflows/tests.yml/badge.svg)](https://github.com/plainfoldhq/date-dimension/actions/workflows/tests.yml)
22
+
23
+ `retailcal` builds any 52/53-week fiscal or retail calendar (4-4-5, 4-5-4, 5-4-4) as CSV: fiscal year, quarter, period, week, week of period, day of fiscal year, and period/week start and end dates. It needs Python 3 and nothing else (standard library only).
24
+
25
+ Install with `pip install retailcal` (once published) or run from a clone with `PYTHONPATH=src python3 -m retailcal ...`.
26
+
27
+ ```
28
+ # NRF-style 4-5-4 retail calendar (year ends Saturday nearest January 31)
29
+ retailcal --preset nrf-454 --from 2020 --to 2030 > nrf_454.csv
30
+
31
+ # One row per fiscal year: start, end, 52 or 53 weeks, weeks per period
32
+ retailcal --preset nrf-454 --year-table --from 2020 --to 2030
33
+
34
+ # Your own: 4-4-5, year ends on the last Sunday of June, named by end year
35
+ retailcal --end-month 6 --weekday sun --rule last --pattern 445 \
36
+ --naming end --from 2015 --to 2035 > my_calendar.csv
37
+ ```
38
+
39
+ From Python:
40
+
41
+ ```python
42
+ from datetime import date
43
+ import retailcal
44
+ cal = retailcal.Calendar(*retailcal.PRESETS["nrf-454"])
45
+ cal.bounds(2025) # (date(2025, 2, 2), date(2026, 1, 31))
46
+ cal.row(date(2025, 11, 28)) # fiscal year, quarter, period, week, ...
47
+ ```
48
+
49
+ Presets: `nrf-454`, `445-sat-nearest-dec`, `544-sat-nearest-dec`, `445-sat-last-sep`. Rules: `nearest` = the year ends on the chosen weekday nearest the last day of the end month; `last` = the last such weekday of the month. A 53rd week goes to period 12 unless `--extra-week-period` says otherwise.
50
+
51
+ ## Guides
52
+ - [4-4-5, 4-5-4 and 5-4-4 retail calendars explained (52/53-week years)](docs/retail-445-454-544-calendar-explained.md)
53
+ - [Build and load a date dimension table (dim_date) with SQL](docs/date-dimension-table-sql.md)
54
+
55
+ ## Free sample data
56
+
57
+ | File | Contents |
58
+ |---|---|
59
+ | `sample/dim_date_2026.csv` | Every day of 2026 with 45 date-dimension columns: date key, ISO and US week numbers, month/quarter boundaries, US federal holidays, US business day, NYSE trading day, US federal fiscal year, NRF fiscal year/period/week |
60
+ | `sample/nrf_454_fiscal_years_2020_2030.csv` | NRF-style fiscal years 2020-2030 with 53-week years marked |
61
+
62
+ ## Full pack ($19, one-time)
63
+
64
+ [Buy the full pack on Polar](https://buy.polar.sh/polar_cl_dQIvyRLcbGYoTfZgVmsIENITeo4Zu2zok8JI94KfqWn) (Polar is the merchant of record and handles sales tax). It contains:
65
+
66
+ - `dim_date` for 2000-2050 (18,628 rows, 45 columns) as CSV and SQLite
67
+ - Four precomputed fiscal calendars 2000-2050 (NRF 4-5-4; 4-4-5 and 5-4-4 ending Saturday nearest December 31; 4-4-5 ending last Saturday of September) and a fiscal-year summary table
68
+ - PostgreSQL tables + load script (tested) and a dbt seed config with column types and tests
69
+ - The build script and tests
70
+
71
+ Also sold as part of the [calendar data bundle](https://buy.polar.sh/polar_cl_HiUeTqJE1gUqHdb3OlOWb6Jml7pdq8E71O2pA4Y9iQ3): this pack plus the other two Plainfold calendar data packs (business days, date dimension, time zone transitions) for $35 instead of $49.
72
+
73
+ ## Checks and limits
74
+
75
+ Tests confirm known NRF fiscal years (for example, fiscal 2024 = February 4 2024 to February 1 2025; 53-week years 2000, 2006, 2012, 2017, 2023, 2028) and last-Saturday-of-September fiscal years. "NRF-style" means the rule commonly published by the National Retail Federation; this project is not affiliated with or endorsed by the NRF. Companies use their own variants, so check yours. Not accounting or tax advice.
76
+
77
+ ## Related
78
+ - [plainfoldhq/us-federal-calendar](https://github.com/plainfoldhq/us-federal-calendar): US federal holidays, NYSE trading days and Federal Reserve holidays as CSV/ICS (Python package `usbizdays`); [full set on Polar](https://buy.polar.sh/polar_cl_oW9ytw22HhxLxOnke3W8ibcgTXepc2hYuAEyl1gTqqB).
79
+ - [plainfoldhq/tz-transitions](https://github.com/plainfoldhq/tz-transitions): IANA time zone transitions 1970-2050 and DST test vectors.
80
+
81
+ ## License
82
+
83
+ Code: MIT. Sample data: CC0 1.0. Made by Plainfold, with AI assistance. Questions: plainfoldhq@proton.me.
@@ -0,0 +1,8 @@
1
+ retailcal/__init__.py,sha256=nKLsDE_4_MmRlN2VnHYDQdZMbB8clsdGmm_wRL5n8m0,8227
2
+ retailcal/__main__.py,sha256=ubt6XyZvcHwdjCQ90B_U4MeP-3YJduz5GWUC9yOgkrg,27
3
+ retailcal-1.0.0.dist-info/licenses/LICENSE,sha256=qQo1pmJrRzy2ygx4c8YfZvBHUYnUbsMIb8l4sJQICow,1241
4
+ retailcal-1.0.0.dist-info/METADATA,sha256=-vcCiFezoawDfRGGXf684FJr8f_OhBe6U0K1XjQt_LI,4904
5
+ retailcal-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ retailcal-1.0.0.dist-info/entry_points.txt,sha256=7B_kMSNzByfY1Pa8B5SG_KVX-VtsZiIL13ipyjgx_Is,45
7
+ retailcal-1.0.0.dist-info/top_level.txt,sha256=-UnOgsd5qtVPhppUTQ2mTexe0gFuvrlqNLGQv_AX6hE,10
8
+ retailcal-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ retailcal = retailcal:main
@@ -0,0 +1,24 @@
1
+ MIT License (scripts/) and CC0 1.0 (sample/)
2
+
3
+ Copyright (c) 2026 Plainfold
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ The files in sample/ are dedicated to the public domain under CC0 1.0
24
+ Universal: https://creativecommons.org/publicdomain/zero/1.0/legalcode
@@ -0,0 +1 @@
1
+ retailcal