def latest_date_before(starting_date, upper_bound, time_step):
    """
    Looks for the latest result_date s.t

        result_date = starting_date + n * time_step     for any integer n
        result_date <= upper_bound

    :type starting_date: pd.Timestamp
    :type upper_bound: pd.Timestamp
    :type time_step: pd.Timedelta
    :return: pd.Timestamp
    """

    result = starting_date

    while result > upper_bound:
        result -= time_step

    while upper_bound - result >= time_step:
        result += time_step

    return result