File size: 4,619 Bytes
6a35a44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
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
from __future__ import annotations

from dataclasses import dataclass

import numpy as np
import pandas as pd

from smc_framework.time._utils import get_datetime_utc


@dataclass(frozen=True)
class HTFResampleParams:
    """
    Causal HTF resampling v0.1.

    Exemple avec timeframe="1h":

        LTF bars:
            10:00
            10:15
            10:30
            10:45

        HTF candle:
            open  = 10:00
            close = fin de 10:45 candle

        Elle devient disponible à:
            11:00

    La colonne `htf_available_time` représente donc
    la première date à laquelle le contenu HTF est causalement connu.
    """

    timeframe: str = "1h"

    volume_column: str = "volume"


def resample_htf_ohlcv(
    df: pd.DataFrame,
    params: HTFResampleParams = HTFResampleParams(),
) -> pd.DataFrame:

    required = {
        "open",
        "high",
        "low",
        "close",
    }

    missing = required.difference(
        df.columns
    )

    if missing:
        raise ValueError(
            "resample_htf_ohlcv(): "
            f"colonnes manquantes: {sorted(missing)}"
        )

    dt = get_datetime_utc(
        df
    )

    work = df.copy()

    work["_mtf_datetime"] = dt

    work = work.set_index(
        "_mtf_datetime",
        drop=True,
    )

    aggregation = {
        "open":
            "first",

        "high":
            "max",

        "low":
            "min",

        "close":
            "last",
    }

    if (
        params.volume_column
        in work.columns
    ):

        aggregation[
            params.volume_column
        ] = "sum"

    # -------------------------------------------------------------------------
    # closed="left", label="right"
    #
    # [10:00, 11:00) is labelled 11:00.
    #
    # Therefore the HTF candle appears exactly when it is complete.
    # -------------------------------------------------------------------------

    htf = (
        work
        .resample(
            params.timeframe,
            closed="left",
            label="right",
            origin="epoch",
        )
        .agg(
            aggregation
        )
    )

    htf = htf.dropna(
        subset=[
            "open",
            "high",
            "low",
            "close",
        ]
    )

    htf = htf.reset_index()

    htf = htf.rename(
        columns={
            "_mtf_datetime":
                "datetime",
        }
    )

    htf[
        "htf_available_time"
    ] = htf[
        "datetime"
    ]

    htf[
        "htf_bar_idx"
    ] = np.arange(
        len(htf),
        dtype=np.int64,
    )

    return htf


def align_completed_htf_to_ltf(
    ltf: pd.DataFrame,
    htf: pd.DataFrame,
    prefix: str = "htf_",
) -> pd.DataFrame:
    """
    Forward-align completed HTF data onto LTF.

    Uses merge_asof(backward):

        LTF 10:45
            cannot see HTF candle available at 11:00.

        LTF 11:00
            can see it.

    This is the core causal MTF invariant.
    """

    if "htf_available_time" not in htf.columns:

        raise ValueError(
            "align_completed_htf_to_ltf(): "
            "htf_available_time absent"
        )

    ltf_out = ltf.copy()

    ltf_time = get_datetime_utc(
        ltf_out
    )

    ltf_out[
        "_mtf_datetime"
    ] = ltf_time

    htf_work = htf.copy()

    htf_work[
        "_mtf_available"
    ] = pd.to_datetime(
        htf_work[
            "htf_available_time"
        ],
        utc=True,
    )

    protected = {
        "datetime",
        "htf_available_time",
        "_mtf_available",
    }

    rename = {}

    for column in htf_work.columns:

        if column in protected:
            continue

        if column.startswith(
            prefix
        ):
            continue

        rename[column] = (
            f"{prefix}{column}"
        )

    htf_work = htf_work.rename(
        columns=rename
    )

    ltf_out = ltf_out.sort_values(
        "_mtf_datetime"
    )

    htf_work = htf_work.sort_values(
        "_mtf_available"
    )

    merged = pd.merge_asof(
        ltf_out,
        htf_work.drop(
            columns=[
                "datetime",
                "htf_available_time",
            ],
            errors="ignore",
        ),
        left_on="_mtf_datetime",
        right_on="_mtf_available",
        direction="backward",
        allow_exact_matches=True,
    )

    merged = merged.drop(
        columns=[
            "_mtf_datetime",
            "_mtf_available",
        ],
        errors="ignore",
    )

    merged.index = ltf_out.index

    return merged.sort_index()