Skip to content

openavmkit.time_adjustment

Time adjustment of sale prices.

Computes a per-day multiplier that adjusts historical sale prices to the valuation date, using a rolling median of price per area unit. The multiplier is applied via sale_price_time_adj = sale_price * multiplier and used throughout downstream ratio studies, modeling, and reporting.

The built-in engine can be wholly replaced for any model group by setting data.process.time_adjustment.from_file.<model_group> in settings.json to point at a precomputed CSV — useful when a jurisdiction publishes its own time-adjustment factors. The CSV is a price index (period, index: a day, a month 2023-04, a quarter 2023-Q2 or a year per row, at any base) or a schedule as OpenAVMKit writes one; see :func:read_schedule.

A model group with too few sales of its own can use another group's time adjustment: data.process.time_adjustment.borrow.<model_group> = <other group>.

apply_time_adjustment

apply_time_adjustment(df_sales_in, settings, period='M', write=False, verbose=False)

Compute time adjustment multipliers and apply them to adjust sale prices forward in time.

Parameters:

Name Type Description Default
df_sales_in DataFrame

Input sales DataFrame.

required
settings dict

Settings dictionary containing time adjustment parameters.

required
period str

Period type to use for adjustment ("M", "Q", or "Y"). Defaults to "M".

'M'
write bool

Whether to write out the time adjustment data as a separate CSV file

False
verbose bool

If True, print verbose output during computation. Defaults to False.

False

Returns:

Type Description
DataFrame

Sales DataFrame with an added sale_price_time_adj column.

Source code in openavmkit/time_adjustment.py
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
def apply_time_adjustment(
    df_sales_in: pd.DataFrame,
    settings: dict,
    period: str = "M",
    write: bool = False,
    verbose: bool = False
) -> pd.DataFrame:
    """
    Compute time adjustment multipliers and apply them to adjust sale prices forward in time.

    Parameters
    ----------
    df_sales_in : pandas.DataFrame
        Input sales DataFrame.
    settings : dict
        Settings dictionary containing time adjustment parameters.
    period : str, optional
        Period type to use for adjustment ("M", "Q", or "Y"). Defaults to "M".
    write : bool, optional
        Whether to write out the time adjustment data as a separate CSV file
    verbose : bool, optional
        If True, print verbose output during computation. Defaults to False.

    Returns
    -------
    pandas.DataFrame
        Sales DataFrame with an added `sale_price_time_adj` column.
    """
    # Groups that borrow another group's time adjustment: worked out from that group's sales (or its file).
    borrowed = {}
    for group, source in get_time_adjustment_instructions(settings).get("borrow", {}).items():
        if not source or source == group:
            continue
        if "model_group" not in df_sales_in or not df_sales_in["model_group"].eq(source).any():
            warnings.warn(
                f"Model group {group!r} borrows the time adjustment of {source!r}, which has no sales: "
                f"{group!r} works out its own."
            )
            continue
        df_source = df_sales_in[df_sales_in["model_group"].eq(source)]
        borrowed[group] = _schedule(df_source, settings, source, period, verbose)
    return do_per_model_group(
        df_sales_in,
        settings,
        apply_time_adjustment_per_model_group,
        {"settings": settings, "period": period, "write": write, "verbose": verbose, "borrowed": borrowed},
        key="key_sale"
    )

apply_time_adjustment_per_model_group

apply_time_adjustment_per_model_group(df_sales_in, settings, model_group, period='M', write=False, verbose=False, borrowed=None)

Compute time adjustment multipliers and apply them to adjust sale prices forward in time.

Parameters:

Name Type Description Default
df_sales_in DataFrame

Input sales DataFrame.

required
settings dict

Settings dictionary containing time adjustment parameters.

required
period str

Period type to use for adjustment ("M", "Q", or "Y"). Defaults to "M".

'M'
write bool

Whether to write out the time adjustment data as a separate CSV file

False
verbose bool

If True, print verbose output during computation. Defaults to False.

False
borrowed dict

Schedules borrowed from other model groups, by the group that borrows them.

None

Returns:

Type Description
DataFrame

Sales DataFrame with an added sale_price_time_adj column.

Source code in openavmkit/time_adjustment.py
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
def apply_time_adjustment_per_model_group(
    df_sales_in: pd.DataFrame,
    settings: dict,
    model_group: str,
    period: str = "M",
    write: bool = False,
    verbose: bool = False,
    borrowed: dict | None = None,
) -> pd.DataFrame:
    """
    Compute time adjustment multipliers and apply them to adjust sale prices forward in time.

    Parameters
    ----------
    df_sales_in : pandas.DataFrame
        Input sales DataFrame.
    settings : dict
        Settings dictionary containing time adjustment parameters.
    period : str, optional
        Period type to use for adjustment ("M", "Q", or "Y"). Defaults to "M".
    write : bool, optional
        Whether to write out the time adjustment data as a separate CSV file
    verbose : bool, optional
        If True, print verbose output during computation. Defaults to False.
    borrowed : dict, optional
        Schedules borrowed from other model groups, by the group that borrows them.

    Returns
    -------
    pandas.DataFrame
        Sales DataFrame with an added `sale_price_time_adj` column.
    """
    if len(df_sales_in) == 0:
        return df_sales_in

    unit = area_unit(settings)

    df_sales = df_sales_in.copy()

    if borrowed and model_group in borrowed:
        # Another group's schedule, held flat outside its dates.
        df_time = _cover(borrowed[model_group], df_sales["sale_date"])
    elif get_time_adjustment_instructions(settings).get("from_file", {}).get(model_group) is not None:
        # The group's own file, held flat outside its dates.
        df_time = _cover(_schedule(df_sales_in, settings, model_group, period, verbose), df_sales["sale_date"])
    else:
        df_time = _schedule(df_sales_in, settings, model_group, period, verbose)

    os.makedirs(f"out/time_adjustment/{model_group}", exist_ok=True)
    df_time.to_csv(f"out/time_adjustment/{model_group}/time_adjustment_schedule.csv", index=False)

    # now we have a multiplier that we can straightforwardly multiply sales by, that will bring all sales FORWARDS in time
    # we merge the time adjustment back into the sales data
    df_time = df_time[["period","correction_factor"]].copy().rename(
        columns={"period": "sale_date"}
    )

    # ensure both dtypes are datetime:
    dtype_time = df_time["sale_date"].dtype
    dtype_sales = df_sales["sale_date"].dtype
    if dtype_time != "datetime64[ns]":
        df_time["sale_date"] = pd.to_datetime(df_time["sale_date"])
    if dtype_sales != "datetime64[ns]":
        df_sales["sale_date"] = pd.to_datetime(df_sales["sale_date"])

    # now, ensure both are converted to YYYY-MM-DD format:
    df_time["sale_date"] = df_time["sale_date"].dt.strftime("%Y-%m-%d")
    df_sales["sale_date"] = df_sales["sale_date"].dt.strftime("%Y-%m-%d")

    df_sales = pd.merge(df_sales, df_time, how="left", on="sale_date")

    # we multiply the sale price by the time adjustment
    df_sales["sale_price_time_adj"] = (
            df_sales["sale_price"] * df_sales["correction_factor"]
    )

    # When the time-adjustment schedule yielded no usable correction (e.g. insufficient
    # per-period variance for rural land sales), correction_factor is NaN and so is
    # sale_price_time_adj. Fall back to the unadjusted sale_price so downstream consumers
    # (canonical splits, spatial lag, _get_sales' positive-price filter) don't drop the row.
    n_missing = int(df_sales["sale_price_time_adj"].isna().sum())
    if n_missing > 0:
        df_sales["sale_price_time_adj"] = df_sales["sale_price_time_adj"].fillna(
            df_sales["sale_price"]
        )
        warnings.warn(
            f"Time adjustment unavailable for {n_missing:,} sales (model group "
            f"'{model_group}'); falling back to unadjusted sale_price for those rows."
        )

    # we drop the time adjustment column
    df_sales = df_sales.drop(columns=["correction_factor"])

    if f"sale_price_per_impr_{unit}" in df_sales:
        df_sales[f"sale_price_time_adj_per_impr_{unit}"] = div_df_z_safe(
            df_sales, "sale_price_time_adj", f"bldg_area_finished_{unit}"
        )
    if f"sale_price_per_land_{unit}" in df_sales:
        df_sales[f"sale_price_time_adj_per_land_{unit}"] = div_df_z_safe(
            df_sales, "sale_price_time_adj", f"land_area_{unit}"
        )

    return df_sales

calculate_time_adjustment

calculate_time_adjustment(df_sales_in, settings, period='M', verbose=False, per=None)

Calculate a time adjustment multiplier for sales data.

Processes sales data to compute a median sale price per area unit over time (at a resolution determined dynamically), interpolates missing values, and returns a DataFrame with daily time adjustment multipliers.

Parameters:

Name Type Description Default
df_sales_in DataFrame

Input sales DataFrame.

required
settings dict

Settings dictionary.

required
period str

Initial period type ("M", "Q", or "Y"). Defaults to "M".

'M'
verbose bool

If True, print progress information. Defaults to False.

False
per str

What the index is of: "impr" (price per finished area) or "land" (price per land area). None (the default) works it out from the sales (determine_value_driver).

None

Returns:

Type Description
DataFrame

DataFrame with time adjustment values per day.

Source code in openavmkit/time_adjustment.py
 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
def calculate_time_adjustment(
    df_sales_in: pd.DataFrame, settings: dict, period: str = "M", verbose: bool = False, per: str | None = None
) -> pd.DataFrame:
    """
    Calculate a time adjustment multiplier for sales data.

    Processes sales data to compute a median sale price per area unit over time (at a
    resolution determined dynamically), interpolates missing values, and returns a
    DataFrame with daily time adjustment multipliers.

    Parameters
    ----------
    df_sales_in : pandas.DataFrame
        Input sales DataFrame.
    settings : dict
        Settings dictionary.
    period : str, optional
        Initial period type ("M", "Q", or "Y"). Defaults to "M".
    verbose : bool, optional
        If True, print progress information. Defaults to False.
    per : str, optional
        What the index is of: "impr" (price per finished area) or "land" (price per land
        area). None (the default) works it out from the sales (determine_value_driver).

    Returns
    -------
    pandas.DataFrame
        DataFrame with time adjustment values per day.
    """

    unit = area_unit(settings)

    # We assume that all the sales we are presented with are valid sales, and for a single modeling group

    # We need at least 5 sales in a given time period to make a valid time adjustment
    min_sale_count = 5

    # We assume we have access to the following fields:
    essential_fields = [
        "sale_date",
        "sale_year",
        "sale_month",
        "sale_quarter",
        "sale_price",
        f"bldg_area_finished_{unit}",
        f"land_area_{unit}",
    ]
    for field in essential_fields:
        if field not in df_sales_in.columns:
            raise ValueError(f"Field '{field}' not found in the sales data.")

    df_sales = df_sales_in.copy()

    if "sale_quarter" not in df_sales.columns:
        df_sales["sale_quarter"] = (df_sales["sale_month"] - 1) // 3 + 1
        df_sales["sale_quarter"] = (
            df_sales["sale_year"].astype(str)
            + "-Q"
            + df_sales["sale_quarter"].astype(str)
        )

    df_sales[f"sale_price_per_impr_{unit}"] = div_df_z_safe(
        df_sales, "sale_price", f"bldg_area_finished_{unit}"
    )
    df_sales[f"sale_price_per_land_{unit}"] = div_df_z_safe(
        df_sales, "sale_price", f"land_area_{unit}"
    )

    # Determine whether land or improvement drives value the modeling group, unless the settings say:
    if per not in ("impr", "land"):
        per = determine_value_driver(df_sales, settings)
    sale_field = f"sale_price_per_{per}_{unit}"

    df_per_unfiltered = df_sales[df_sales[sale_field].gt(0)]
    # Exclude the wrong-side sales from the per-area median: vacant sales for an
    # impr-driven index, improved sales for a land-driven index. Without this,
    # vacant sales (land-only prices) divided by the parcel's currently-recorded
    # bldg_area pull the impr-PPSF median down by orders of magnitude.
    df_per = df_per_unfiltered
    if "vacant_sale" in df_per_unfiltered.columns and len(df_per_unfiltered) > 0:
        if per == "impr":
            df_per_filtered = df_per_unfiltered[~df_per_unfiltered["vacant_sale"].eq(True)]
        elif per == "land":
            df_per_filtered = df_per_unfiltered[df_per_unfiltered["vacant_sale"].eq(True)]
        else:
            df_per_filtered = df_per_unfiltered
        # If the V/I filter would empty the dataset, fall back to no filter rather
        # than producing a broken time-adjustment curve. This happens when a model
        # group has only one side (e.g. an apartment group with no vacant sales but
        # determine_value_driver picked "land", or vice versa).
        if len(df_per_filtered) == 0:
            warnings.warn(
                f"Time-adjustment V/I filter for per={per!r} would leave 0 sales "
                f"(of {len(df_per_unfiltered)} candidates). Falling back to the "
                "unfiltered set — the resulting index may be biased."
            )
        else:
            df_per = df_per_filtered

    # If we still have no usable sales, return a flat (no-op) multiplier schedule
    # covering the sales date range. Downstream code applies the multiplier via
    # `sale_price * value`, so value=1.0 leaves prices unchanged.
    if len(df_per) == 0:
        warnings.warn(
            "Time adjustment: no sales with a positive "
            f"{sale_field} remain. Returning a flat multiplier=1.0 schedule."
        )
        if len(df_sales) > 0 and df_sales["sale_date"].notna().any():
            start = df_sales["sale_date"].min()
            end = df_sales["sale_date"].max()
            dates = pd.date_range(start=start, end=end, freq="D")
        else:
            dates = pd.DatetimeIndex([pd.Timestamp.today().normalize()])
        return pd.DataFrame({"period": dates, "value": np.ones(len(dates))})

    # Determine the time resolution (Month, Quarter, Year) -- "M", "Q", or "Y":
    period = determine_time_resolution(df_per, sale_field, min_sale_count, period)

    if verbose:
        print(f"--> Using period: {period}")
        print(f"--> Crunching time adjustment...")
    # Derive the time adjustment:
    df_crunch = _crunch_time_adjustment(df_per, sale_field, period, min_sale_count)
    if verbose:
        print(f"--> Flattening time adjustment...")
    # Flatten out the time adjustment to daily values:
    df_time = _flatten_periods_to_days(df_per, df_crunch, period, verbose)
    print(f"--> Time adjustment calculated for {len(df_time)} days.")

    return df_time

determine_time_resolution

determine_time_resolution(df_per, sale_field, min_sale_count, period='M')

Determine the appropriate time resolution (Month, Quarter, or Year) based on sales counts.

Months, while no more than 2 months a year have fewer than min_sale_count sales; else quarters, while no more than 1 quarter a year has fewer; else years.

Parameters:

Name Type Description Default
df_per DataFrame

Sales with sale_year_month and sale_year_quarter.

required
sale_field str

The column counted.

required
min_sale_count int

The fewest sales a period should have.

required
period str

The finest to try: "M" (months), "Q" (quarters) or "Y" (years).

'M'

Returns:

Type Description
str

"M", "Q" or "Y".

Source code in openavmkit/time_adjustment.py
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
def determine_time_resolution(df_per, sale_field, min_sale_count, period: str = "M"):
    """Determine the appropriate time resolution (Month, Quarter, or Year) based on sales
    counts.

    Months, while no more than 2 months a year have fewer than ``min_sale_count`` sales; else quarters, while no
    more than 1 quarter a year has fewer; else years.

    Parameters
    ----------
    df_per : pandas.DataFrame
        Sales with ``sale_year_month`` and ``sale_year_quarter``.
    sale_field : str
        The column counted.
    min_sale_count : int
        The fewest sales a period should have.
    period : str
        The finest to try: ``"M"`` (months), ``"Q"`` (quarters) or ``"Y"`` (years).

    Returns
    -------
    str
        ``"M"``, ``"Q"`` or ``"Y"``.
    """
    months_total = 0
    months_missing = 0

    if period == "M":
        # Count how many months are below the minimum sale count
        df_counts = df_per.groupby("sale_year_month")[sale_field].agg(["count"])
        months_total = len(df_counts)
        months_above_min = len(df_counts[df_counts["count"].ge(min_sale_count)])
        months_missing = len(df_counts) - months_above_min

    # Tolerate up to 2 missing months a year
    if period != "M" or months_missing / months_total > 2 / 12:

        if period == "M":
            period = "Q"

        if period == "Q":
            # Count how many quarters are below the minimum sale count
            df_counts = df_per.groupby("sale_year_quarter")[sale_field].agg(["count"])
            quarters_total = len(df_counts)
            if quarters_total == 0:
                warnings.warn("Unable to determine time resolution due to insufficient data")
                return period
            quarters_above_min = len(df_counts[df_counts["count"].ge(min_sale_count)])
            quarters_missing = len(df_counts) - quarters_above_min

            # Tolerate up to 1 missing quarter a year
            if quarters_missing / quarters_total > 1 / 4:
                period = "Y"

    return period

determine_value_driver

determine_value_driver(df_in, settings)

Determine whether land or improvement drives the value in the modeling group.

Compares median sale prices per area unit for improved and land properties and returns "land" if the relative difference is small and a significant portion of sales are land; otherwise returns "impr".

Parameters:

Name Type Description Default
df_in DataFrame

The model group's parcels with their sales.

required
settings dict

The settings (for the area unit and which sales count).

required

Returns:

Type Description
str

"land" or "impr".

Source code in openavmkit/time_adjustment.py
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
def determine_value_driver(df_in: pd.DataFrame, settings: dict):
    """Determine whether land or improvement drives the value in the modeling group.

    Compares median sale prices per area unit for improved and land properties and returns
    "land" if the relative difference is small and a significant portion of sales are
    land; otherwise returns "impr".

    Parameters
    ----------
    df_in : pandas.DataFrame
        The model group's parcels with their sales.
    settings : dict
        The settings (for the area unit and which sales count).

    Returns
    -------
    str
        ``"land"`` or ``"impr"``.
    """
    unit = area_unit(settings)

    df = df_in.copy()

    df = _get_sales(df, settings)

    df_impr = df[df[f"bldg_area_finished_{unit}"].gt(0)]
    df_land = df[df[f"land_area_{unit}"].gt(0)]

    if len(df_land) == 0 and len(df_impr) !=0:
        return "impr"
    if len(df_impr) == 0 and len(df_land) !=0:
        return "land"
    if len(df_impr) == 0 and len(df_land) == 0:
        warnings.warn("No positive values for both land and improvement, default to improved value driver")
        return "impr"

    df_impr[f"sale_price_per_impr_{unit}"] = div_df_z_safe(
        df_impr, "sale_price", f"bldg_area_finished_{unit}"
    )
    df_land[f"sale_price_per_land_{unit}"] = div_df_z_safe(
        df_land, "sale_price", f"land_area_{unit}"
    )

    # get the median sale price per area unit for both land and improvement
    median_impr = df_impr[f"sale_price_per_impr_{unit}"].median()
    median_land = df_land[f"sale_price_per_land_{unit}"].median()

    perc_delta = abs(median_impr - median_land) / median_land

    if perc_delta < 0.15:
        # if the difference between the two values is small, we might favor land
        perc_land = len(df_land) / len(df)
        # if a significant portion of the modeling group is land, we favor land
        if perc_land >= 0.3:
            return "land"
    return "impr"

enrich_time_adjustment

enrich_time_adjustment(df_in, settings, write=False, verbose=False)

Enrich the sales data by generating time-adjusted sales if not already present.

Parameters:

Name Type Description Default
df_in DataFrame

Input sales DataFrame.

required
settings dict

Settings dictionary.

required
write bool

Whether to write out the time adjustment to a separate CSV file. Defaults to False.

False
verbose bool

If True, print verbose output. Defaults to False.

False

Returns:

Type Description
DataFrame

Enriched sales DataFrame.

Source code in openavmkit/time_adjustment.py
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
def enrich_time_adjustment(
    df_in: pd.DataFrame, settings: dict, write: bool = False, verbose: bool = False
) -> pd.DataFrame:
    """
    Enrich the sales data by generating time-adjusted sales if not already present.

    Parameters
    ----------
    df_in : pandas.DataFrame
        Input sales DataFrame.
    settings : dict
        Settings dictionary.
    write : bool
        Whether to write out the time adjustment to a separate CSV file. Defaults to False.
    verbose : bool, optional
        If True, print verbose output. Defaults to False.

    Returns
    -------
    pandas.DataFrame
        Enriched sales DataFrame.
    """
    df = df_in.copy()

    # Gather settings
    ta = get_time_adjustment_instructions(settings)

    # Apply time adjustment if necessary
    if "sale_price_time_adj" not in df:
        if verbose:
            print("Applying time adjustment...")
        period = ta.get("period", "Q")
        df = apply_time_adjustment(df.copy(), settings, period=period, write=write, verbose=verbose)

    return df

read_schedule

read_schedule(path)

Read a time adjustment file and check it.

Two kinds are accepted:

  • a price index: period (a day 2023-04-15, a month 2023-04, a quarter 2023-Q2, or a year 2023; one row each) and index (the price level then, at any base: 100, 1.0...; positive). Between periods it is interpolated day by day.
  • a schedule as OpenAVMKit writes one: period, start_indexed, end_indexed, correction_factor (start_indexed is the index).

Parameters:

Name Type Description Default
path str

The CSV file.

required

Returns:

Type Description
tuple[DataFrame | None, list[str]]

The daily schedule (period, start_indexed, end_indexed, correction_factor, prices brought to the last period), or None; and every problem found, in words.

Source code in openavmkit/time_adjustment.py
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
def read_schedule(path: str) -> tuple[pd.DataFrame | None, list[str]]:
    """Read a time adjustment file and check it.

    Two kinds are accepted:

    * a price index: ``period`` (a day ``2023-04-15``, a month ``2023-04``, a quarter
      ``2023-Q2``, or a year ``2023``; one row each) and ``index`` (the price level then, at
      any base: 100, 1.0...; positive). Between periods it is interpolated day by day.
    * a schedule as OpenAVMKit writes one: ``period``, ``start_indexed``, ``end_indexed``,
      ``correction_factor`` (``start_indexed`` is the index).

    Parameters
    ----------
    path : str
        The CSV file.

    Returns
    -------
    tuple[pd.DataFrame | None, list[str]]
        The daily schedule (``period``, ``start_indexed``, ``end_indexed``, ``correction_factor``,
        prices brought to the last period), or None; and every problem found, in words.
    """
    try:
        # As written: problems are quoted as the file has them ("n/a", not NaN).
        df = pd.read_csv(path, encoding="utf-8-sig", dtype=str, keep_default_na=False)
    except Exception as e:
        return None, [f"It couldn't be read as a CSV file: {e}"]
    df.columns = [str(c).strip().lower() for c in df.columns]
    problems: list[str] = []
    value = "index" if "index" in df.columns else "start_indexed" if "start_indexed" in df.columns else None
    if "period" not in df.columns:
        problems.append("There's no 'period' column (the date each price level is for).")
    if value is None:
        problems.append("There's no 'index' column (the price level for each period).")
    if problems:
        return None, problems
    dates = df["period"].map(_period_date)
    levels = pd.to_numeric(df[value], errors="coerce")
    bad_dates = df.loc[dates.isna(), "period"].astype(str).tolist()
    if bad_dates:
        problems.append(
            f"{len(bad_dates)} period(s) aren't a date, a month (2023-04), a quarter (2023-Q2) or a year: "
            + ", ".join(bad_dates[:5])
        )
    bad_levels = [v or "(blank)" for v in df.loc[levels.isna() | levels.le(0), value].astype(str)]
    if bad_levels:
        problems.append(f"{len(bad_levels)} {value} value(s) aren't positive numbers: " + ", ".join(bad_levels[:5]))
    repeated = dates[dates.duplicated() & dates.notna()]
    if len(repeated):
        problems.append(
            f"{len(repeated)} period(s) appear more than once: "
            + ", ".join(sorted({d.strftime("%Y-%m-%d") for d in repeated})[:5])
        )
    ok = dates.notna() & levels.notna() & levels.gt(0)
    if int(ok.sum()) < 2:
        problems.append("It needs at least 2 periods with a price level.")
    if problems:
        return None, problems
    points = pd.Series(levels[ok].values, index=pd.DatetimeIndex(dates[ok])).sort_index()
    days = pd.date_range(points.index[0], points.index[-1], freq="D")
    daily = points.reindex(points.index.union(days)).interpolate(method="time").reindex(days)
    out = pd.DataFrame({"period": days.strftime("%Y-%m-%d"), "start_indexed": daily.values / daily.iloc[0]})
    out["end_indexed"] = out["start_indexed"] / out["start_indexed"].iloc[-1]
    out["correction_factor"] = 1 / out["end_indexed"]
    return out, []

read_time_adjustment_from_file

read_time_adjustment_from_file(ta_settings, model_group)

A group's time adjustment file, as a daily schedule, or None (no file, or one that can't be used).

Source code in openavmkit/time_adjustment.py
333
334
335
336
337
338
339
340
341
def read_time_adjustment_from_file(ta_settings: dict, model_group: str) -> pd.DataFrame|None:
    """A group's time adjustment file, as a daily schedule, or None (no file, or one that can't be used)."""
    override_path = ta_settings.get("from_file",{}).get(model_group)
    if override_path is None:
        return None
    df_time, problems = read_schedule(override_path)
    if df_time is None:
        warnings.warn(f"Time adjustment file for model group {model_group} can't be used: " + " ".join(problems))
    return df_time