跳轉到

策略參數

參數的 schema(名稱、範圍、預設值),以及各 K 棒 interval 使用的預設組合。

cjtrade.pkgs.strategy.parameters.schema

cjtrade.pkgs.strategy.parameters.schema ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Parameter schema: definition, type, range, constraints.

Enables: - Parameter validation - Grid search / optimization (know the search space) - Documentation of what params are available

validate_param(key, value)

Check if param value is valid according to schema.

Parameters:

Name Type Description Default
key str

Parameter name

required
value Any

Parameter value

required

Returns:

Type Description
(is_valid, error_message)

Tuple of (bool, str). If valid, error_message is empty.

Source code in src/cjtrade/pkgs/strategy/parameters/schema.py
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
def validate_param(key: str, value: Any) -> Tuple[bool, str]:
    """Check if param value is valid according to schema.

    Parameters
    ----------
    key : str
        Parameter name
    value : Any
        Parameter value

    Returns
    -------
    (is_valid, error_message)
        Tuple of (bool, str). If valid, error_message is empty.
    """
    if key not in PARAM_SCHEMA:
        return False, f"Unknown param: {key}"

    schema = PARAM_SCHEMA[key]
    param_type = schema["type"]

    # Type check
    type_map = {"int": int, "float": float, "str": str, "bool": bool}
    expected_type = type_map[param_type]

    if not isinstance(value, expected_type):
        return False, f"{key} must be {param_type}, got {type(value).__name__}"

    # Range check for numeric types
    if param_type in ("int", "float"):
        if "min" in schema and value < schema["min"]:
            return False, f"{key}={value} < min {schema['min']}"
        if "max" in schema and value > schema["max"]:
            return False, f"{key}={value} > max {schema['max']}"

    # Enum check
    if "enum" in schema and value not in schema["enum"]:
        return False, f"{key}={value} not in {schema['enum']}"

    return True, ""

can_optimize(key)

Check if param can be optimized (not fixed).

Parameters:

Name Type Description Default
key str

Parameter name

required

Returns:

Type Description
bool

True if parameter can be optimized

Source code in src/cjtrade/pkgs/strategy/parameters/schema.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
def can_optimize(key: str) -> bool:
    """Check if param can be optimized (not fixed).

    Parameters
    ----------
    key : str
        Parameter name

    Returns
    -------
    bool
        True if parameter can be optimized
    """
    if key not in PARAM_SCHEMA:
        return False
    return not PARAM_SCHEMA[key].get("fixed", False)

get_param_range(key)

Get optimization range for a parameter.

Parameters:

Name Type Description Default
key str

Parameter name

required

Returns:

Type Description
dict

Dict with 'min', 'max', 'step', 'type' and 'default'; empty if the key is unknown or fixed.

Source code in src/cjtrade/pkgs/strategy/parameters/schema.py
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
def get_param_range(key: str) -> Dict[str, Any]:
    """Get optimization range for a parameter.

    Parameters
    ----------
    key : str
        Parameter name

    Returns
    -------
    dict
        Dict with 'min', 'max', 'step', 'type' and 'default'; empty if the
        key is unknown or fixed.
    """
    if key not in PARAM_SCHEMA or not can_optimize(key):
        return {}

    schema = PARAM_SCHEMA[key]
    return {
        "type": schema["type"],
        "min": schema.get("min"),
        "max": schema.get("max"),
        "step": schema.get("step"),
        "default": schema.get("default"),
    }

cjtrade.pkgs.strategy.parameters.presets

cjtrade.pkgs.strategy.parameters.presets ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Interval-based parameter presets.

Different intervals (1m, 5m, 1h, 1d) require different parameter values for the same strategy to work effectively.

This module centralizes all preset values per interval.

get_interval_presets(interval)

Get base presets for given interval.

Parameters:

Name Type Description Default
interval str

'1m', '5m', '1h', '1d'

required

Returns:

Type Description
dict

Preset parameters for this interval (deep copy to avoid mutations)

Raises:

Type Description
ValueError

If interval is not supported

Warnings

Window parameters are in bars, so each interval has its own values; do not reuse one interval's preset on another.

Source code in src/cjtrade/pkgs/strategy/parameters/presets.py
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
def get_interval_presets(interval: str) -> dict:
    """Get base presets for given interval.

    Parameters
    ----------
    interval : str
        '1m', '5m', '1h', '1d'

    Returns
    -------
    dict
        Preset parameters for this interval (deep copy to avoid mutations)

    Raises
    ------
    ValueError
        If interval is not supported

    Warnings
    --------
    Window parameters are in bars, so each interval has its own values; do not
    reuse one interval's preset on another.
    """
    if interval not in INTERVAL_PRESETS:
        raise ValueError(
            f"Unknown interval: {interval}. "
            f"Supported: {list(INTERVAL_PRESETS.keys())}"
        )

    import copy

    return copy.deepcopy(INTERVAL_PRESETS[interval])

get_supported_intervals()

Get list of supported intervals.

Returns:

Type Description
list[str]

List of supported interval strings

Source code in src/cjtrade/pkgs/strategy/parameters/presets.py
170
171
172
173
174
175
176
177
178
def get_supported_intervals() -> list:
    """Get list of supported intervals.

    Returns
    -------
    list[str]
        List of supported interval strings
    """
    return list(INTERVAL_PRESETS.keys())

cjtrade.pkgs.strategy.parameters.config

cjtrade.pkgs.strategy.parameters.config ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ParameterConfig: encapsulates all parameters + metadata for one run.

Tracks: - Final parameter values - Which preset was used as base - What user overrides were applied - Hash for experiment reproducibility

ParameterConfig(interval, strategy_name, params, base_preset=dict(), user_overrides=dict(), created_at=(lambda: datetime.now().isoformat())()) dataclass

Holds all parameters for a strategy run.

Attributes:

Name Type Description
interval str

KBar interval ('1m', '5m', '1h', '1d')

strategy_name str

Strategy name ('BollingerStrategy', 'SupportResistanceStrategy', etc.)

params dict

Final resolved parameters (preset + overrides)

base_preset dict

The interval preset we started with

user_overrides dict

User-specified overrides (what params they changed)

created_at str

ISO timestamp of when this config was created

Warnings

created_at defaults to the wall-clock time (datetime.now()); it is not part of params_hash.

params_hash property

Hash of params for reproducibility and experiment tracking.

Returns:

Type Description
str

8-char SHA256 hash of params

to_dict()

Serialize to dict for logging/saving.

Returns:

Type Description
dict

Dictionary representation suitable for JSON serialization

Source code in src/cjtrade/pkgs/strategy/parameters/config.py
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def to_dict(self) -> dict:
    """Serialize to dict for logging/saving.

    Returns
    -------
    dict
        Dictionary representation suitable for JSON serialization
    """
    return {
        "interval": self.interval,
        "strategy_name": self.strategy_name,
        "params": self.params,
        "params_hash": self.params_hash,
        "base_preset": self.base_preset,
        "user_overrides": self.user_overrides,
        "created_at": self.created_at,
    }

to_json()

Serialize to JSON string.

Returns:

Type Description
str

JSON representation

Source code in src/cjtrade/pkgs/strategy/parameters/config.py
88
89
90
91
92
93
94
95
96
def to_json(self) -> str:
    """Serialize to JSON string.

    Returns
    -------
    str
        JSON representation
    """
    return json.dumps(self.to_dict(), indent=2)