backtestingfx 0.3.0__cp315-cp315-win_amd64.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.
@@ -0,0 +1,3 @@
1
+ from backtestingfx._backtestingfx import Bar, Broker, Engine, Stats, SwapConfig, SwapCharge, Trade # type: ignore
2
+ from backtestingfx.backtest import Strategy, Backtest
3
+ from backtestingfx._backtestingfx import MarginConfig, OrderResult, OrderRejection, Liquidation
@@ -0,0 +1,157 @@
1
+ """Reference input preparation and one positional map for public index identity."""
2
+
3
+ from dataclasses import dataclass, field
4
+ from enum import Enum
5
+ import operator
6
+ import warnings
7
+
8
+ import numpy as np
9
+ import pandas as pd
10
+ from pandas.api.types import is_numeric_dtype
11
+
12
+
13
+ REFERENCE_OHLCV = ("Open", "High", "Low", "Close", "Volume")
14
+
15
+
16
+ class InputMode(Enum):
17
+ FX = "fx"
18
+ REFERENCE = "reference"
19
+
20
+ @classmethod
21
+ def parse(cls, value):
22
+ if not isinstance(value, str):
23
+ raise ValueError("data_mode must be 'fx' or 'reference'")
24
+ try:
25
+ return cls(value)
26
+ except ValueError as error:
27
+ raise ValueError("data_mode must be 'fx' or 'reference'") from error
28
+
29
+
30
+ def prepare_reference(data, cash):
31
+ """Apply the pinned 0.6.6 input policy through supported pandas APIs."""
32
+ data = data.copy(deep=False)
33
+ if (not isinstance(data.index, (pd.DatetimeIndex, pd.RangeIndex))
34
+ and is_numeric_dtype(data.index.dtype)
35
+ and (data.index > pd.Timestamp("1975").timestamp()).mean() > 0.8):
36
+ try:
37
+ data.index = pd.to_datetime(data.index)
38
+ except ValueError:
39
+ pass
40
+ if "Volume" not in data:
41
+ data["Volume"] = np.nan
42
+ if len(data) == 0:
43
+ raise ValueError("OHLC `data` is empty")
44
+ if len(data.columns.intersection(REFERENCE_OHLCV)) != len(REFERENCE_OHLCV):
45
+ raise ValueError("reference data must contain 'Open', 'High', 'Low', and 'Close' columns")
46
+ if data[list(REFERENCE_OHLCV[:-1])].isnull().to_numpy().any():
47
+ raise ValueError("Some OHLC values are missing (NaN)")
48
+ if np.any(data["Close"] > cash):
49
+ warnings.warn("Some prices are larger than initial cash value. Fractional asset trading is not enabled.",
50
+ UserWarning, stacklevel=3)
51
+ if not data.index.is_monotonic_increasing:
52
+ warnings.warn("Data index is not sorted in ascending order. Sorting.", UserWarning, stacklevel=3)
53
+ data = data.sort_index()
54
+ if not isinstance(data.index, pd.DatetimeIndex):
55
+ warnings.warn("Data index is not datetime. Assuming simple periods, but `pd.DateTimeIndex` is advised.",
56
+ UserWarning, stacklevel=3)
57
+ return data
58
+
59
+
60
+ def reference_columns(frame):
61
+ values = [np.require(frame[name].to_numpy(), dtype=np.float64, requirements=["C", "A"])
62
+ for name in REFERENCE_OHLCV]
63
+ return np.arange(len(frame), dtype=np.int64), values
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class ReferenceSnapshot:
68
+ frame: pd.DataFrame
69
+ _index: pd.Index = field(init=False, repr=False)
70
+
71
+ def __post_init__(self):
72
+ index = self.frame.index.copy(deep=True)
73
+ self.frame.index = index
74
+ object.__setattr__(self, "_index", index)
75
+
76
+ @property
77
+ def index(self):
78
+ return self._index
79
+
80
+ def offset(self, value):
81
+ offset = operator.index(value)
82
+ if not 0 <= offset < len(self._index):
83
+ raise IndexError("event row is outside this input snapshot")
84
+ return offset
85
+
86
+ def label(self, value):
87
+ return self._index[self.offset(value)]
88
+
89
+ def record(self, native):
90
+ return IndexedRecord(native, self)
91
+
92
+ def result(self, native):
93
+ return IndexedResult(native, self)
94
+
95
+
96
+ _TIME_FIELDS = {
97
+ "timestamp": ("timestamp", True),
98
+ "time": ("timestamp", True),
99
+ "bar": ("timestamp", False),
100
+ "entry_timestamp": ("entry_timestamp", True),
101
+ "entry_time": ("entry_timestamp", True),
102
+ "entry_bar": ("entry_timestamp", False),
103
+ "exit_timestamp": ("exit_timestamp", True),
104
+ "exit_time": ("exit_timestamp", True),
105
+ "exit_bar": ("exit_timestamp", False),
106
+ }
107
+
108
+
109
+ @dataclass(frozen=True)
110
+ class IndexedRecord:
111
+ _native: object
112
+ _snapshot: ReferenceSnapshot
113
+
114
+ def __getattr__(self, name):
115
+ mapping = _TIME_FIELDS.get(name)
116
+ if mapping is None:
117
+ return getattr(self._native, name)
118
+ source, label = mapping
119
+ value = getattr(self._native, source)
120
+ return self._snapshot.label(value) if label else self._snapshot.offset(value)
121
+
122
+
123
+ @dataclass(frozen=True)
124
+ class IndexedResult:
125
+ _native: object
126
+ _snapshot: ReferenceSnapshot
127
+
128
+ def __getattr__(self, name):
129
+ return getattr(self._native, name)
130
+
131
+ def __repr__(self):
132
+ return repr(self._native)
133
+
134
+ @property
135
+ def index(self):
136
+ return self._snapshot.index
137
+
138
+ @property
139
+ def equity(self):
140
+ return pd.Series(self._native.equity_curve[1:], index=self.index, name="Equity")
141
+
142
+ @property
143
+ def trades(self):
144
+ return [self._snapshot.record(trade) for trade in self._native.trades]
145
+
146
+ @property
147
+ def open_positions(self):
148
+ return [self._snapshot.record(position) for position in self._native.open_positions]
149
+
150
+ @property
151
+ def order_rejections(self):
152
+ return [self._snapshot.record(record) for record in self._native.order_rejections]
153
+
154
+ @property
155
+ def liquidation(self):
156
+ event = self._native.liquidation
157
+ return None if event is None else self._snapshot.record(event)
@@ -0,0 +1,43 @@
1
+ """Parse external timestamps into exact, floored UTC Unix seconds."""
2
+
3
+ from numbers import Integral, Real
4
+ import re
5
+
6
+ import numpy as np
7
+ import pandas as pd
8
+
9
+
10
+ UNITS = {"s": 1, "ms": 1000, "us": 1000000, "ns": 1000000000}
11
+
12
+
13
+ def timestamp_value(value, offset, unit):
14
+ try:
15
+ if isinstance(value, (bool, np.bool_)):
16
+ raise ValueError("boolean timestamp")
17
+ if isinstance(value, str) and re.fullmatch(r"[+-]?[0-9]+", value.strip()):
18
+ value = int(value)
19
+ if isinstance(value, (Integral, Real)):
20
+ if unit is None:
21
+ raise ValueError("numeric timestamps require timestamp_unit='s', 'ms', 'us', or 'ns'")
22
+ if isinstance(value, Integral):
23
+ seconds = int(value) // UNITS[unit]
24
+ else:
25
+ numerator, denominator = value.as_integer_ratio()
26
+ seconds = numerator // (denominator * UNITS[unit])
27
+ else:
28
+ stamp = value if isinstance(value, pd.Timestamp) else pd.Timestamp(value)
29
+ if pd.isna(stamp):
30
+ raise ValueError("missing timestamp")
31
+ # asm8 stores UTC for aware values and treats naive values as UTC.
32
+ # Integer division floors before the epoch and avoids float rounding.
33
+ raw = stamp.asm8
34
+ seconds = int(raw.view("i8")) // UNITS[np.datetime_data(raw.dtype)[0]]
35
+ if not -(2**63) <= seconds < 2**63:
36
+ raise ValueError("timestamp outside int64 Unix seconds")
37
+ return seconds
38
+ except (TypeError, ValueError, OverflowError) as error:
39
+ raise ValueError(f"bar {offset}: invalid timestamp: {error}") from error
40
+
41
+
42
+ def index_seconds(index):
43
+ return np.ascontiguousarray(index.asi8 // UNITS[getattr(index, "unit", "ns")], dtype=np.int64)