#345 by GitHub stars

edtechre/pybroker

Algorithmic Trading in Python with Machine Learning

History

Review weekly changes to SKILL.md before updating. Dates mark the weeks in which we observed each version; checks apply to the recorded commits.

View weekly changes

skills/pybroker-indicator-creator/SKILL.md

Week of Nov 2, 2026 · +0 / −0 lines

Before Network or broad shell → After Network or broad shell

01f11fdd42b7 → 01f11fdd42b7

Diff text is unavailable under the recorded licenses. Line counts and the GitHub link remain available.

Compare on GitHub

Week of Oct 26, 2026 · Line counts unavailable

Before Not checked yet → After Network or broad shell

First observation → 01f11fdd42b7

No earlier version was observed for comparison.

Compare on GitHub

skills/pybroker-model-trainer/SKILL.md

Week of Nov 2, 2026 · +0 / −0 lines

Before Network or broad shell → After Network or broad shell

01f11fdd42b7 → 01f11fdd42b7

Diff text is unavailable under the recorded licenses. Line counts and the GitHub link remain available.

Compare on GitHub

Week of Oct 26, 2026 · Line counts unavailable

Before Not checked yet → After Network or broad shell

First observation → 01f11fdd42b7

No earlier version was observed for comparison.

Compare on GitHub

skills/pybroker-multi-interval/SKILL.md

Week of Nov 2, 2026 · +0 / −0 lines

Before Network or broad shell → After Network or broad shell

01f11fdd42b7 → 01f11fdd42b7

Diff text is unavailable under the recorded licenses. Line counts and the GitHub link remain available.

Compare on GitHub

Week of Oct 26, 2026 · Line counts unavailable

Before Not checked yet → After Network or broad shell

First observation → 01f11fdd42b7

No earlier version was observed for comparison.

Compare on GitHub

skills/pybroker-optimize/SKILL.md

Week of Nov 2, 2026 · +0 / −0 lines

Before Network or broad shell → After Network or broad shell

01f11fdd42b7 → 01f11fdd42b7

Diff text is unavailable under the recorded licenses. Line counts and the GitHub link remain available.

Compare on GitHub

Week of Oct 26, 2026 · Line counts unavailable

Before Not checked yet → After Network or broad shell

First observation → 01f11fdd42b7

No earlier version was observed for comparison.

Compare on GitHub

skills/pybroker-rotational-trading/SKILL.md

Week of Nov 2, 2026 · +0 / −0 lines

Before Network or broad shell → After Network or broad shell

01f11fdd42b7 → 01f11fdd42b7

Diff text is unavailable under the recorded licenses. Line counts and the GitHub link remain available.

Compare on GitHub

Week of Oct 26, 2026 · Line counts unavailable

Before Not checked yet → After Network or broad shell

First observation → 01f11fdd42b7

No earlier version was observed for comparison.

Compare on GitHub

skills/pybroker-strategy-creator/SKILL.md

Week of Nov 2, 2026 · +0 / −0 lines

Before Network or broad shell → After Network or broad shell

01f11fdd42b7 → 01f11fdd42b7

Diff text is unavailable under the recorded licenses. Line counts and the GitHub link remain available.

Compare on GitHub

Week of Oct 26, 2026 · Line counts unavailable

Before Not checked yet → After Network or broad shell

First observation → 01f11fdd42b7

No earlier version was observed for comparison.

Compare on GitHub

View on GitHubAdd to my skills

Verified commit 01f11fdd42b76ef564a7f550c247a3dfce81330e

git clone --filter=blob:none --no-checkout https://github.com/edtechre/pybroker.git .hotskills/edtechre-pybroker && git -C .hotskills/edtechre-pybroker checkout --detach 01f11fdd42b76ef564a7f550c247a3dfce81330e # Copy each selected skill directory from .hotskills/edtechre-pybroker into .claude/skills/<skill-name>/
3.7kGitHub stars
7stars in 7 days
6skills in this repository
5commits in 30 days

Heat

3.5
  • Star growth, last 7 daysAhead of 51% of tracked repositories
  • Star growth, last 24 hoursAhead of 5% of tracked repositories
  • Rank movement, last 7 daysAhead of 30% of tracked repositories
  • Commits, last 30 daysAhead of 70% of tracked repositories
  • Accounts asking about it through MCP, last 7 daysNot available
  • Hot votes this weekAhead of 0% of tracked repositories

Heat never changes the order by stars, and sponsorship never touches it. How heat works

Stars over time

Aug 1, 2026Nov 6, 20263,673

Individual skills in this repository

How it works

pybroker-indicator-creator

When your agent uses it

Write, register, and debug PyBroker indicators using the bundled PyBroker wiki references generated from the local docs. Use when an agent needs to write custom indicator functions with pybroker.indicator, vectorize indicator logic with NumPy and Numba @njit kernels, wrap third-party technical analysis libraries such as TA-Lib, pandas-ta, ta, tulipy, or finta, use the built-in indicator factories and vector helpers, compute indicators standalone with IndicatorSet, parameterize indicators with hyperparams for optimization, compute indicators on multiple time intervals, feed custom data columns into indicators, cache indicator computations, or debug Numba compilation errors and parallel indicator failures.

What it loads into context

Frontmatter

143 tokens

Always available to the agent

SKILL.md

3,029 tokens

When the skill is activated

Reference documents

35,437 tokens

Loaded on request

Token counts are estimates. Scripts run separately; they are not counted as reference context.

The playbook

  1. Overview
  2. Workflow
  3. Implementation Rules
  4. Common Deliverables
  5. Resources

Scripts executed separately

  • assets/indicator_template.py

Files

  • SKILL.mdcore13,490 bytes
  • SKILL.mdcore13,490 bytes
  • SKILL.mdcore13,490 bytes
  • agents/openai.yamlasset248 bytes
  • assets/indicator_template.pyruns3,429 bytes
  • references/api-public-surface.mddoc87,110 bytes
  • references/indicator-patterns.mddoc21,312 bytes
  • references/pybroker_context.pyiasset12,325 bytes
  • references/pybroker_model.pyiasset12,873 bytes
  • references/pybroker_strategy.pyiasset9,216 bytes
  • references/pybroker_types.pyiasset14,697 bytes
  • references/wiki-05-writing-indicators.mddoc9,336 bytes
  • references/wiki-11-configuring-parallelization.mddoc6,350 bytes
  • references/wiki-15-multiple-time-intervals.mddoc10,606 bytes
  • references/wiki-index.mddoc2,575 bytes

No excerpt is shown for this license. Read the source on GitHub.

View the complete source on GitHub

Skills included

  • pybroker-indicator-creator
  • pybroker-model-trainer
  • pybroker-multi-interval
  • pybroker-optimize
  • pybroker-rotational-trading
  • pybroker-strategy-creator

Repository facts

License
No license detected
Created
Jan 16, 2023
Last pushed
Nov 2, 2026
Forks
460
Open issues
0
Project activity
Active

Rank over the last 12 weeks

Now #345 · best #248 · down 50 in 30 days

  1. #336 on Oct 31
  2. #337 on Nov 1
  3. #338 on Nov 2
  4. #342 from Nov 3 to Nov 4
  5. #343 on Nov 5
  6. #345 since Nov 6
55 earlier periods
  1. #244 on Aug 1
  2. #243 on Aug 7
  3. #246 on Aug 8
  4. #241 on Aug 9
  5. #250 on Aug 10
  6. #245 on Aug 11
  7. #243 on Aug 12
  8. #249 on Aug 13
  9. #251 on Aug 14
  10. #248 on Aug 15
  11. #251 from Aug 16 to Aug 17
  12. #253 on Aug 20
  13. #260 on Aug 23
  14. #261 on Aug 24
  15. #264 on Aug 25
  16. #263 from Aug 26 to Aug 28
  17. #264 on Aug 29
  18. #270 on Sep 3
  19. #262 on Sep 4
  20. #265 on Sep 5
  21. #263 on Sep 6
  22. #270 from Sep 7 to Sep 8
  23. #272 on Sep 9
  24. #270 on Sep 11
  25. #274 on Sep 12
  26. #278 on Sep 14
  27. #279 from Sep 15 to Sep 16
  28. #280 on Sep 18
  29. #281 on Sep 21
  30. #284 on Sep 22
  31. #285 on Sep 23
  32. #292 from Sep 28 to Sep 29
  33. #290 on Sep 30
  34. #288 on Oct 1
  35. #287 on Oct 3
  36. #285 on Oct 4
  37. #293 on Oct 6
  38. #295 from Oct 7 to Oct 8
  39. #299 on Oct 9
  40. #295 from Oct 10 to Oct 11
  41. #303 on Oct 12
  42. #301 on Oct 13
  43. #305 on Oct 14
  44. #306 on Oct 16
  45. #307 on Oct 17
  46. #311 on Oct 18
  47. #312 on Oct 19
  48. #315 on Oct 20
  49. #317 on Oct 21
  50. #318 on Oct 22
  51. #316 from Oct 23 to Oct 24
  52. #323 on Oct 25
  53. #325 on Oct 28
  54. #331 on Oct 29
  55. #334 on Oct 30

Before you install

Network or broad shell

Automated signals, not a guarantee

Checked Nov 2, 2026

Not fully analyzed: some files were too long, unreadable or missing. This never lowers the level.

Show 14 notes
  • skills/pybroker-indicator-creator/SKILL.md:1 Analysis incomplete: Referenced executable target unavailable; not analyzed
  • skills/pybroker-indicator-creator/SKILL.md:1 Analysis incomplete: Referenced executable target unavailable; not analyzed
  • skills/pybroker-model-trainer/SKILL.md:1 Analysis incomplete: Referenced executable target unavailable; not analyzed
  • skills/pybroker-model-trainer/SKILL.md:1 Analysis incomplete: Referenced executable target unavailable; not analyzed
  • skills/pybroker-model-trainer/SKILL.md:1 Analysis incomplete: Referenced executable target unavailable; not analyzed
  • skills/pybroker-model-trainer/SKILL.md:1 Analysis incomplete: Referenced executable target unavailable; not analyzed
  • skills/pybroker-multi-interval/SKILL.md:1 Analysis incomplete: Referenced executable target unavailable; not analyzed
  • skills/pybroker-optimize/SKILL.md:1 Analysis incomplete: Referenced executable target unavailable; not analyzed
  • skills/pybroker-rotational-trading/SKILL.md:1 Analysis incomplete: Referenced executable target unavailable; not analyzed
  • skills/pybroker-rotational-trading/SKILL.md:1 Analysis incomplete: Referenced executable target unavailable; not analyzed
  • skills/pybroker-strategy-creator/SKILL.md:1 Analysis incomplete: Referenced executable target unavailable; not analyzed
  • skills/pybroker-strategy-creator/SKILL.md:1 Analysis incomplete: Referenced executable target unavailable; not analyzed
  • skills/pybroker-strategy-creator/SKILL.md:1 Analysis incomplete: Referenced executable target unavailable; not analyzed
  • skills/pybroker-strategy-creator/SKILL.md:1 Analysis incomplete: Referenced executable target unavailable; not analyzed
Show all 675 signals by file

skills/pybroker-indicator-creator/assets/indicator_template.py

  • Executable scriptline 1
    Executable file

skills/pybroker-indicator-creator/references/api-public-surface.md

  • Access to secretsline 367
    [Credential-related source omitted]
  • Network accessline 369
    Retrieves stock data from `Alpaca <https://alpaca.markets/>`_.
  • Access to secretsline 373
    [Credential-related source omitted]
  • Network accessline 375
    Retrieves crypto data from `Alpaca <https://alpaca.markets/>`_.
  • Network accessline 381
    Retrieves data from `Yahoo Finance <https://finance.yahoo.com/>`_\ .
  • Network accessline 383
    - `auto_adjust: bool` - `query(symbols: Union[str, Iterable[str]], start_date: Union[str, datetime], end_date: Union[str, datetime], _timeframe: Optional[str]='', _adjust: Optional[Any]=None) -> pd.DataFrame`: Queries data from `Yahoo Finan
  • Network accessline 384
    - `query(symbols: Union[str, Iterable[str]], start_date: Union[str, datetime], end_date: Union[str, datetime], _timeframe: Optional[str]='', _adjust: Optional[Any]=None) -> pd.DataFrame`: Queries data from `Yahoo Finance <https://finance.ya
  • Network accessline 402
    - `profit_factor(changes: NDArray[np.float64], use_log: bool=False) -> float`: Computes the profit factor, which is the ratio of gross profit to gross loss. - `log_profit_factor(changes: NDArray[np.float64]) -> float`: Computes the log tran
  • Network accessline 403
    - `log_profit_factor(changes: NDArray[np.float64]) -> float`: Computes the log transformed profit factor, which is the ratio of gross profit to gross loss. - `sharpe_ratio(returns: NDArray[np.float64], obs: Optional[int]=None) -> float`: Co
  • Network accessline 404
    - `sharpe_ratio(returns: NDArray[np.float64], obs: Optional[int]=None) -> float`: Computes the `Sharpe Ratio <https://en.wikipedia.org/wiki/Sharpe_ratio>`_, using the population standard deviation of ``returns``.
  • Network accessline 405
    - `downside_deviation(returns: NDArray[np.float64]) -> float`: Computes downside deviation, the denominator of the `Sortino Ratio <https://en.wikipedia.org/wiki/Sortino_ratio>`_.
  • Network accessline 406
    - `sortino_ratio(returns: NDArray[np.float64], obs: Optional[int]=None) -> float`: Computes the `Sortino Ratio <https://en.wikipedia.org/wiki/Sortino_ratio>`_.
  • Network accessline 429
    - `drawdown_conf(changes: NDArray[np.float64], returns: NDArray[np.float64], n_boot: int) -> DrawdownMetrics`: Computes upper bounds of confidence intervals for maximum drawdown using the bootstrap method. - `bootstrap_eval_all(changes: NDA
  • Network accessline 430
    - `bootstrap_eval_all(changes: NDArray[np.float64], returns: NDArray[np.float64], n_boot: int, bars_per_year: int) -> tuple[BootConfIntervals, BootConfIntervals, DrawdownMetrics]`: Computes all bootstrap metrics in one shared resampling pas
  • Network accessline 431
    - `relative_entropy(values: NDArray[np.float64]) -> float`: Computes the relative `entropy <https://en.wikipedia.org/wiki/Entropy_(information_theory)>`_.
  • Network accessline 432
    - `iqr(values: NDArray[np.float64]) -> float`: Computes the `interquartile range (IQR) <https://en.wikipedia.org/wiki/Interquartile_range>`_ of ``values``.
  • Network accessline 433
    - `ulcer_index(values: NDArray[np.float64], period: Optional[int]=None) -> float`: Computes the `Ulcer Index <https://en.wikipedia.org/wiki/Ulcer_index>`_ of ``values``: the root mean square of percentage drawdowns from the running peak.
  • Network accessline 434
    - `upi(values: NDArray[np.float64], period: Optional[int]=None, ui: Optional[float]=None, bars_per_year: Optional[int]=None) -> float`: Computes the `Ulcer Performance Index <https://en.wikipedia.org/wiki/Ulcer_index>`_ of ``values``: retur
  • Network accessline 566
    - `name: str` - `hyperparam_names() -> frozenset[str]` - `relative_entropy(data: Union[BarData, pd.DataFrame]) -> float`: Generates indicator data with ``data`` and computes its relative `entropy <https://en.wikipedia.org/wiki/Entropy_(info
  • Network accessline 567
    - `hyperparam_names() -> frozenset[str]` - `relative_entropy(data: Union[BarData, pd.DataFrame]) -> float`: Generates indicator data with ``data`` and computes its relative `entropy <https://en.wikipedia.org/wiki/Entropy_(information_theory
  • Network accessline 568
    - `relative_entropy(data: Union[BarData, pd.DataFrame]) -> float`: Generates indicator data with ``data`` and computes its relative `entropy <https://en.wikipedia.org/wiki/Entropy_(information_theory)>`_.
  • Network accessline 569
    - `iqr(data: Union[BarData, pd.DataFrame]) -> float`: Generates indicator data with ``data`` and computes its `interquartile range (IQR) <https://en.wikipedia.org/wiki/Interquartile_range>`_.
  • Network accessline 1119
    - `unique_dates() -> NDArray[np.datetime64]`: Returns sorted unique dates across every symbol in the store. - `fetch_dict(symbol: str, names: Iterable[str], end_index: Optional[int]=None) -> dict[str, Optional[NDArray]]`: Fetches a ``dict``
  • Network accessline 1120
    - `fetch_dict(symbol: str, names: Iterable[str], end_index: Optional[int]=None) -> dict[str, Optional[NDArray]]`: Fetches a ``dict`` of column data for ``symbol``. - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> Optional[
  • Network accessline 1121
    - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> Optional[NDArray]`: Fetches a :class:`numpy.ndarray` of column data for ``symbol``.
  • Network accessline 1129
    - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> NDArray[np.float64]`: Fetches :class:`pybroker.indicator.Indicator` data.
  • Network accessline 1151
    - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> pd.DataFrame`: Fetches model input data.
  • Network accessline 1158
    - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> NDArray`: Fetches model predictions.
  • Network accessline 1167
    - `fetch_float(symbol: str, price: Union[int, float, np.floating, Decimal, PriceType, Callable[[str, BarData], Union[int, float, Decimal]]]) -> float`: Returns a bar price as ``float`` using the per-bar cache when possible. - `fetch_bar_ohl
  • Network accessline 1169
    - `fetch(symbol: str, price: Union[int, float, np.floating, Decimal, PriceType, Callable[[str, BarData], Union[int, float, Decimal]]]) -> Decimal`
  • Network accessline 1298
    Mixin implementing logic for `Walkforward Analysis <https://www.pybroker.com/en/latest/notebooks/6.%20Training%20a%20Model.html#Walkforward-Analysis>`_.
  • Network accessline 1300
    - `walkforward_split(df: pd.DataFrame, windows: int, lookahead: int, train_size: float=0.9, shuffle: bool=False) -> Iterator[WalkforwardWindow]`: Splits a :class:`pandas.DataFrame` containing data for multiple ticker symbols into an :class:
  • Network accessline 1332
    - `clear_executions()`: Clears executions that were added with :meth:`.add_execution`. - `backtest(start_date: Optional[Union[str, datetime]]=None, end_date: Optional[Union[str, datetime]]=None, timeframe: str='', between_time: Optional[tup
  • Network accessline 1334
    - `walkforward(windows: int, lookahead: int=1, start_date: Optional[Union[str, datetime]]=None, end_date: Optional[Union[str, datetime]]=None, timeframe: str='', between_time: Optional[tuple[str, str]]=None, days: Optional[Union[str, Day, I
  • Network accessline 1383
    Retrieves data from `AKShare <https://akshare.akfamily.xyz/>`_.
  • Network accessline 1388
    Retrieves data from Yahoo Finance using `Yahooquery <https://github.com/dpguthrie/yahooquery>`_\ .

skills/pybroker-indicator-creator/references/pybroker_model.pyi

  • Network accessline 240
    class Alpaca(DataSource):     """Retrieves stock data from `Alpaca <https://alpaca.markets/>`_."""
  • Network accessline 241
    """Retrieves stock data from `Alpaca <https://alpaca.markets/>`_."""
  • Access to secretsline 242
    [Credential-related source omitted]
  • Network accessline 252
    class AlpacaCrypto(DataSource):     """Retrieves crypto data from `Alpaca <https://alpaca.markets/>`_."""
  • Network accessline 253
    """Retrieves crypto data from `Alpaca <https://alpaca.markets/>`_."""
  • Access to secretsline 267
    [Credential-related source omitted]
  • Network accessline 277
    class YFinance(DataSource):     """Retrieves data from `Yahoo Finance <https://finance.yahoo.com/>`_."""
  • Network accessline 278
    """Retrieves data from `Yahoo Finance <https://finance.yahoo.com/>`_."""
  • Network accessline 293
    # --- src/pybroker/ext/data.py --- class AKShare(DataSource):     """Retrieves data from `AKShare <https://akshare.akfamily.xyz/>`_."""
  • Network accessline 295
    """Retrieves data from `AKShare <https://akshare.akfamily.xyz/>`_."""
  • Network accessline 297
    class YQuery(DataSource):     """Retrieves data from Yahoo Finance using `Yahooquery <https://github.com/dpguthrie/yahooquery>`_."""
  • Network accessline 298
    """Retrieves data from Yahoo Finance using `Yahooquery <https://github.com/dpguthrie/yahooquery>`_."""

skills/pybroker-indicator-creator/references/pybroker_types.pyi

  • Network accessline 427
    end_index: Optional[int] = None,     ) -> dict[str, Optional[NDArray]]: ...     def fetch(
  • Network accessline 428
    ) -> dict[str, Optional[NDArray]]: ...     def fetch(         self, symbol: str, name: str, end_index: Optional[int] = None
  • Network accessline 429
    def fetch(
  • Network accessline 440
    """Caches and retrieves :class:`pybroker.indicator.Indicator` data."""     # Constructed by the framework; not user-instantiable.     def fetch(
  • Network accessline 441
    # Constructed by the framework; not user-instantiable.     def fetch(         self, symbol: str, name: str, end_index: Optional[int] = None
  • Network accessline 442
    def fetch(

skills/pybroker-indicator-creator/references/wiki-05-writing-indicators.md

  • Network accessline 9
    This notebook explains how to create and integrate custom stock indicators in **PyBroker**.  Indicators in **PyBroker** are written using [NumPy](https://numpy.org/), a powerful library for numerical computing. To optimize performance, we'l
  • Network accessline 16
    The following code shows an indicator function that calculates close prices minus a moving average (CMMA), which can be used for a [mean reversion](https://en.wikipedia.org/wiki/Mean_reversion_(finance)) strategy:
  • Network accessline 42
    The ```cmma``` function takes two arguments: ```bar_data```, which is an instance of the [BarData](https://www.pybroker.com/en/latest/reference/pybroker.common.html#pybroker.common.BarData) class that holds OHLCV data and custom fields, and
  • Network accessline 44
    The ```vec_cmma``` function is JIT-compiled by Numba and nested inside ```cmma```. This is necessary since a Numba compiled function supports a NumPy array as an argument but not an instance of a Python class like ```BarData```. Note the co
  • Network accessline 54
    Here, we are giving the name ```cmma_20``` to the indicator function and specifying the ```lookback``` parameter as ```20``` bars. Any arguments in the indicator function that come after ```bar_data``` will be passed as user-defined argumen
  • Network accessline 56
    The following is an example of how to use the registered ```Indicator``` in **PyBroker** with some data downloaded from [Yahoo Finance](https://finance.yahoo.com):
  • Network accessline 71
    As you can see, the ```Indicator``` instance is a ```Callable```. Once called, the resulting computed indicator values are returned as a [Pandas Series](https://pandas.pydata.org/docs/reference/api/pandas.Series.html).
  • Network accessline 73
    The ```Indicator``` class also provides functions for measuring its information content. For example, you can compute the [interquartile range (IQR)](https://en.wikipedia.org/wiki/Interquartile_range):
  • Network accessline 79
    Or compute the relative [entropy](https://en.wikipedia.org/wiki/Entropy_(information_theory)):
  • Network accessline 99
    The indicator values are retrieved by calling [ctx.indicator](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.indicator) on the [ExecContext](https://www.pybroker.com/en/latest/reference/pybro
  • Network accessline 108
    Here, the ```buy_cmma_cross``` function is added to the [Strategy](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy) along with the ```cmma_20``` indicator. We can enable caching of the computed
  • Network accessline 121
    **PyBroker** computes indicator values before the backtest runs. By default, these calculations occur serially. See [Configuring Parallelization](https://www.pybroker.com/en/latest/notebooks/11.%20Configuring%20Parallelization.html) for det
  • Network accessline 125
    **PyBroker** provides vectorized helper functions to make the process of computing indicators easier. One of these helper functions is [highv](https://www.pybroker.com/en/latest/reference/pybroker.vect.html#pybroker.vect.highv), which calcu
  • Network accessline 141
    The [pybroker.vect](https://www.pybroker.com/en/latest/reference/pybroker.vect.html) module also includes other vectorized helpers such as [lowv](https://www.pybroker.com/en/latest/reference/pybroker.vect.html#pybroker.vect.lowv), [sumv](ht
  • Network accessline 143
    Additionally, **PyBroker** includes convenient wrappers for [highest](https://www.pybroker.com/en/latest/reference/pybroker.indicator.html#pybroker.indicator.highest) and [lowest](https://www.pybroker.com/en/latest/reference/pybroker.indica
  • Network accessline 154
    Use an [IndicatorSet](https://www.pybroker.com/en/latest/reference/pybroker.indicator.html#pybroker.indicator.IndicatorSet) to calculate multiple indicators. Add the `cmma_20` and `hhv_5` indicators to the `IndicatorSet` to compute them tog
  • Network accessline 166
    [TA-Lib](https://github.com/TA-Lib/ta-lib-python) is a widely used technical analysis library that implements many financial indicators. You can install it with `pip install ta-lib`.
  • Network accessline 181
    **PyBroker** also includes built-in indicators that are available in the [indicator module](https://www.pybroker.com/en/latest/reference/pybroker.indicator.html). **PyBroker** reimplements these standard indicators with volatility normaliza
  • Network accessline 183
    [In the next tutorial, you will learn how to train a model using custom indicators in PyBroker](https://www.pybroker.com/en/latest/notebooks/6.%20Training%20a%20Model.html).

skills/pybroker-indicator-creator/references/wiki-11-configuring-parallelization.md

  • Network accessline 9
    **PyBroker** uses [Joblib](https://joblib.readthedocs.io/) to compute indicators, train models, and optimize parameters in parallel.
  • Network accessline 13
    [set_parallel](https://www.pybroker.com/en/latest/reference/pybroker.parallel.html#pybroker.parallel.set_parallel) updates the global Joblib configuration. The [n_jobs](https://www.pybroker.com/en/latest/reference/pybroker.parallel.html#pyb
  • Network accessline 29
    Indicators are computed **per symbol**: all indicators for a given symbol are grouped into a single task, and one task is dispatched per symbol. Passing `parallel_indicators=True` to [backtest](https://www.pybroker.com/en/latest/reference/p
  • Network accessline 68
    Standalone indicator computation with an [IndicatorSet](https://www.pybroker.com/en/latest/reference/pybroker.indicator.html#pybroker.indicator.IndicatorSet) accepts the same `parallel_indicators` flag:
  • Network accessline 83
    Model training runs serially by default. Passing `parallel_models=True` to [backtest](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.backtest) or [walkforward](https://www.pybroker.com/en/late
  • Network accessline 85
    This example adapts the linear regression model from [Training a Model](https://www.pybroker.com/en/latest/notebooks/6.%20Training%20a%20Model.html):
  • Network accessline 132
    [Ray](https://www.ray.io/) can distribute the same work across many cores or an entire cluster. Install it with `pip install ray` and then register it with Joblib via [register_ray](https://docs.ray.io/en/latest/ray-more-libs/joblib.html) (
  • Network accessline 142
    After registering Ray, pass `backend="ray"` to [set_parallel](https://www.pybroker.com/en/latest/reference/pybroker.parallel.html#pybroker.parallel.set_parallel) to make it available as a backend:
  • Network accessline 149
    **PyBroker** will now use the Ray backend for all parallel tasks. For example, calling [backtest](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.backtest) with `parallel_indicators=True`:
  • Network accessline 158
    We will explore [parameter optimization](https://www.pybroker.com/en/latest/notebooks/12.%20Parameter%20Optimization.html) in the next notebook, which can also be parallelized in certain scenarios.

skills/pybroker-indicator-creator/references/wiki-15-multiple-time-intervals.md

  • Network accessline 27
    Your chosen interval must always be longer than the bars being compressed. For example, if you fetch daily bars from [YFinance](https://www.pybroker.com/en/latest/reference/pybroker.data.html#pybroker.data.YFinance), then `"weekly"` and `"m
  • Network accessline 46
    The [compress_bars](https://www.pybroker.com/en/latest/reference/pybroker.interval.html#pybroker.interval.compress_bars) function converts OHLCV data (either a [Pandas DataFrame](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame
  • Network accessline 52
    *   **Volume:** The sum of the volumes. *   **VWAP:** The volume-weighted average. *   **Custom columns:** The last value in the period (e.g., [YFinance](https://www.pybroker.com/en/latest/reference/pybroker.data.html#pybroker.data.YFinance
  • Network accessline 54
    *   **Custom columns:** The last value in the period (e.g., [YFinance](https://www.pybroker.com/en/latest/reference/pybroker.data.html#pybroker.data.YFinance)'s `adj_close`).
  • Network accessline 58
    Let's compress AMD into calendar weeks and view the result as a [Pandas DataFrame](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html) with [bars_to_df](https://www.pybroker.com/en/latest/reference/pybroker.common.html#pybro
  • Network accessline 77
    To use higher timeframes in your backtest, pass the `intervals` parameter to [add_execution](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.add_execution). Your execution function can then acc
  • Network accessline 81
    To prevent look-ahead bias, [ctx.interval](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.interval) only ever exposes *completed* bars. For example, the week or month that is currently formin
  • Network accessline 117
    To compute an indicator on compressed bars, bind it to one or more intervals with [Indicator.intervals(...)](https://www.pybroker.com/en/latest/reference/pybroker.indicator.html#pybroker.indicator.Indicator.intervals).
  • Network accessline 152
    **PyBroker** automatically combines bound intervals with those in the execution's `intervals` parameter. Here, the `"weekly"` interval is made accessible via [ctx.interval("weekly")](https://www.pybroker.com/en/latest/reference/pybroker.con
  • Network accessline 154
    Note that the binding will override also computing the indicator on the base timeframe of the data source. To also compute the indicator on the base timeframe of the data source, pass `"base"` to [Indicator.intervals()](https://www.pybroker
  • Network accessline 163
    You can bind models in the same way with [ModelSource.intervals(...)](https://www.pybroker.com/en/latest/reference/pybroker.model.html#pybroker.model.ModelSource.intervals). **PyBroker** will then train models for each interval using the in
  • Network accessline 165
    This example trains a [LinearRegression](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html) model to predict the next weekly return from the weekly close:
  • Network accessline 202
    During [Walkforward Analysis](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.walkforward), the `lookahead` between an interval model's train and test data is enforced using the compressed bar 

skills/pybroker-model-trainer/assets/model_training_template.py

  • Executable scriptline 1
    Executable file

skills/pybroker-model-trainer/references/api-public-surface.md

  • Access to secretsline 367
    [Credential-related source omitted]
  • Network accessline 369
    Retrieves stock data from `Alpaca <https://alpaca.markets/>`_.
  • Access to secretsline 373
    [Credential-related source omitted]
  • Network accessline 375
    Retrieves crypto data from `Alpaca <https://alpaca.markets/>`_.
  • Network accessline 381
    Retrieves data from `Yahoo Finance <https://finance.yahoo.com/>`_\ .
  • Network accessline 383
    - `auto_adjust: bool` - `query(symbols: Union[str, Iterable[str]], start_date: Union[str, datetime], end_date: Union[str, datetime], _timeframe: Optional[str]='', _adjust: Optional[Any]=None) -> pd.DataFrame`: Queries data from `Yahoo Finan
  • Network accessline 384
    - `query(symbols: Union[str, Iterable[str]], start_date: Union[str, datetime], end_date: Union[str, datetime], _timeframe: Optional[str]='', _adjust: Optional[Any]=None) -> pd.DataFrame`: Queries data from `Yahoo Finance <https://finance.ya
  • Network accessline 402
    - `profit_factor(changes: NDArray[np.float64], use_log: bool=False) -> float`: Computes the profit factor, which is the ratio of gross profit to gross loss. - `log_profit_factor(changes: NDArray[np.float64]) -> float`: Computes the log tran
  • Network accessline 403
    - `log_profit_factor(changes: NDArray[np.float64]) -> float`: Computes the log transformed profit factor, which is the ratio of gross profit to gross loss. - `sharpe_ratio(returns: NDArray[np.float64], obs: Optional[int]=None) -> float`: Co
  • Network accessline 404
    - `sharpe_ratio(returns: NDArray[np.float64], obs: Optional[int]=None) -> float`: Computes the `Sharpe Ratio <https://en.wikipedia.org/wiki/Sharpe_ratio>`_, using the population standard deviation of ``returns``.
  • Network accessline 405
    - `downside_deviation(returns: NDArray[np.float64]) -> float`: Computes downside deviation, the denominator of the `Sortino Ratio <https://en.wikipedia.org/wiki/Sortino_ratio>`_.
  • Network accessline 406
    - `sortino_ratio(returns: NDArray[np.float64], obs: Optional[int]=None) -> float`: Computes the `Sortino Ratio <https://en.wikipedia.org/wiki/Sortino_ratio>`_.
  • Network accessline 429
    - `drawdown_conf(changes: NDArray[np.float64], returns: NDArray[np.float64], n_boot: int) -> DrawdownMetrics`: Computes upper bounds of confidence intervals for maximum drawdown using the bootstrap method. - `bootstrap_eval_all(changes: NDA
  • Network accessline 430
    - `bootstrap_eval_all(changes: NDArray[np.float64], returns: NDArray[np.float64], n_boot: int, bars_per_year: int) -> tuple[BootConfIntervals, BootConfIntervals, DrawdownMetrics]`: Computes all bootstrap metrics in one shared resampling pas
  • Network accessline 431
    - `relative_entropy(values: NDArray[np.float64]) -> float`: Computes the relative `entropy <https://en.wikipedia.org/wiki/Entropy_(information_theory)>`_.
  • Network accessline 432
    - `iqr(values: NDArray[np.float64]) -> float`: Computes the `interquartile range (IQR) <https://en.wikipedia.org/wiki/Interquartile_range>`_ of ``values``.
  • Network accessline 433
    - `ulcer_index(values: NDArray[np.float64], period: Optional[int]=None) -> float`: Computes the `Ulcer Index <https://en.wikipedia.org/wiki/Ulcer_index>`_ of ``values``: the root mean square of percentage drawdowns from the running peak.
  • Network accessline 434
    - `upi(values: NDArray[np.float64], period: Optional[int]=None, ui: Optional[float]=None, bars_per_year: Optional[int]=None) -> float`: Computes the `Ulcer Performance Index <https://en.wikipedia.org/wiki/Ulcer_index>`_ of ``values``: retur
  • Network accessline 566
    - `name: str` - `hyperparam_names() -> frozenset[str]` - `relative_entropy(data: Union[BarData, pd.DataFrame]) -> float`: Generates indicator data with ``data`` and computes its relative `entropy <https://en.wikipedia.org/wiki/Entropy_(info
  • Network accessline 567
    - `hyperparam_names() -> frozenset[str]` - `relative_entropy(data: Union[BarData, pd.DataFrame]) -> float`: Generates indicator data with ``data`` and computes its relative `entropy <https://en.wikipedia.org/wiki/Entropy_(information_theory
  • Network accessline 568
    - `relative_entropy(data: Union[BarData, pd.DataFrame]) -> float`: Generates indicator data with ``data`` and computes its relative `entropy <https://en.wikipedia.org/wiki/Entropy_(information_theory)>`_.
  • Network accessline 569
    - `iqr(data: Union[BarData, pd.DataFrame]) -> float`: Generates indicator data with ``data`` and computes its `interquartile range (IQR) <https://en.wikipedia.org/wiki/Interquartile_range>`_.
  • Network accessline 1119
    - `unique_dates() -> NDArray[np.datetime64]`: Returns sorted unique dates across every symbol in the store. - `fetch_dict(symbol: str, names: Iterable[str], end_index: Optional[int]=None) -> dict[str, Optional[NDArray]]`: Fetches a ``dict``
  • Network accessline 1120
    - `fetch_dict(symbol: str, names: Iterable[str], end_index: Optional[int]=None) -> dict[str, Optional[NDArray]]`: Fetches a ``dict`` of column data for ``symbol``. - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> Optional[
  • Network accessline 1121
    - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> Optional[NDArray]`: Fetches a :class:`numpy.ndarray` of column data for ``symbol``.
  • Network accessline 1129
    - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> NDArray[np.float64]`: Fetches :class:`pybroker.indicator.Indicator` data.
  • Network accessline 1151
    - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> pd.DataFrame`: Fetches model input data.
  • Network accessline 1158
    - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> NDArray`: Fetches model predictions.
  • Network accessline 1167
    - `fetch_float(symbol: str, price: Union[int, float, np.floating, Decimal, PriceType, Callable[[str, BarData], Union[int, float, Decimal]]]) -> float`: Returns a bar price as ``float`` using the per-bar cache when possible. - `fetch_bar_ohl
  • Network accessline 1169
    - `fetch(symbol: str, price: Union[int, float, np.floating, Decimal, PriceType, Callable[[str, BarData], Union[int, float, Decimal]]]) -> Decimal`
  • Network accessline 1298
    Mixin implementing logic for `Walkforward Analysis <https://www.pybroker.com/en/latest/notebooks/6.%20Training%20a%20Model.html#Walkforward-Analysis>`_.
  • Network accessline 1300
    - `walkforward_split(df: pd.DataFrame, windows: int, lookahead: int, train_size: float=0.9, shuffle: bool=False) -> Iterator[WalkforwardWindow]`: Splits a :class:`pandas.DataFrame` containing data for multiple ticker symbols into an :class:
  • Network accessline 1332
    - `clear_executions()`: Clears executions that were added with :meth:`.add_execution`. - `backtest(start_date: Optional[Union[str, datetime]]=None, end_date: Optional[Union[str, datetime]]=None, timeframe: str='', between_time: Optional[tup
  • Network accessline 1334
    - `walkforward(windows: int, lookahead: int=1, start_date: Optional[Union[str, datetime]]=None, end_date: Optional[Union[str, datetime]]=None, timeframe: str='', between_time: Optional[tuple[str, str]]=None, days: Optional[Union[str, Day, I
  • Network accessline 1383
    Retrieves data from `AKShare <https://akshare.akfamily.xyz/>`_.
  • Network accessline 1388
    Retrieves data from Yahoo Finance using `Yahooquery <https://github.com/dpguthrie/yahooquery>`_\ .

skills/pybroker-model-trainer/references/pybroker_model.pyi

  • Network accessline 240
    class Alpaca(DataSource):     """Retrieves stock data from `Alpaca <https://alpaca.markets/>`_."""
  • Network accessline 241
    """Retrieves stock data from `Alpaca <https://alpaca.markets/>`_."""
  • Access to secretsline 242
    [Credential-related source omitted]
  • Network accessline 252
    class AlpacaCrypto(DataSource):     """Retrieves crypto data from `Alpaca <https://alpaca.markets/>`_."""
  • Network accessline 253
    """Retrieves crypto data from `Alpaca <https://alpaca.markets/>`_."""
  • Access to secretsline 267
    [Credential-related source omitted]
  • Network accessline 277
    class YFinance(DataSource):     """Retrieves data from `Yahoo Finance <https://finance.yahoo.com/>`_."""
  • Network accessline 278
    """Retrieves data from `Yahoo Finance <https://finance.yahoo.com/>`_."""
  • Network accessline 293
    # --- src/pybroker/ext/data.py --- class AKShare(DataSource):     """Retrieves data from `AKShare <https://akshare.akfamily.xyz/>`_."""
  • Network accessline 295
    """Retrieves data from `AKShare <https://akshare.akfamily.xyz/>`_."""
  • Network accessline 297
    class YQuery(DataSource):     """Retrieves data from Yahoo Finance using `Yahooquery <https://github.com/dpguthrie/yahooquery>`_."""
  • Network accessline 298
    """Retrieves data from Yahoo Finance using `Yahooquery <https://github.com/dpguthrie/yahooquery>`_."""

skills/pybroker-model-trainer/references/pybroker_types.pyi

  • Network accessline 427
    end_index: Optional[int] = None,     ) -> dict[str, Optional[NDArray]]: ...     def fetch(
  • Network accessline 428
    ) -> dict[str, Optional[NDArray]]: ...     def fetch(         self, symbol: str, name: str, end_index: Optional[int] = None
  • Network accessline 429
    def fetch(
  • Network accessline 440
    """Caches and retrieves :class:`pybroker.indicator.Indicator` data."""     # Constructed by the framework; not user-instantiable.     def fetch(
  • Network accessline 441
    # Constructed by the framework; not user-instantiable.     def fetch(         self, symbol: str, name: str, end_index: Optional[int] = None
  • Network accessline 442
    def fetch(

skills/pybroker-model-trainer/references/wiki-06-training-a-model.md

  • Network accessline 9
    In the [last notebook](https://www.pybroker.com/en/latest/notebooks/5.%20Writing%20Indicators.html), we learned how to write stock indicators in **PyBroker**. Indicators are a good starting point for developing a trading strategy. But to cr
  • Network accessline 11
    One of the main features of **PyBroker** is the ability to train and backtest machine learning models. These models can utilize indicators as features to make more accurate predictions about market movements. Once trained, these models can 
  • Network accessline 22
    As with [DataSource](https://www.pybroker.com/en/latest/reference/pybroker.data.html#pybroker.data.DataSource) and [Indicator](https://www.pybroker.com/en/latest/reference/pybroker.indicator.html#pybroker.indicator.Indicator) data, **PyBrok
  • Network accessline 28
    In [the last notebook](https://www.pybroker.com/en/latest/notebooks/5.%20Writing%20Indicators.html), we implemented an indicator that calculates the close-minus-moving-average (CMMA) using [NumPy](https://www.numpy.org) and [Numba](https://
  • Network accessline 59
    Next, we want to build a model that predicts the next day's return using the 20-day CMMA. Using [simple linear regression](https://en.wikipedia.org/wiki/Simple_linear_regression) is a good approach to begin experimenting with as a baseline 
  • Network accessline 61
    Below we import a [LinearRegression](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html) model from [scikit-learn](https://scikit-learn.org/stable/):
  • Network accessline 110
    After fitting the model, the function uses the testing data to evaluate the model's accuracy, specifically by computing the [R-squared](https://en.wikipedia.org/wiki/Coefficient_of_determination) score. The R-squared score provides a measur
  • Network accessline 114
    Once the function to train the model has been defined, it needs to be registered with **PyBroker**. This is done by creating a new [ModelSource](https://www.pybroker.com/en/latest/reference/pybroker.model.html#pybroker.model.ModelSource)  i
  • Network accessline 120
    To create a trading strategy that uses the trained model, create a new [Strategy](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy) object using the [YFinance](https://www.pybroker.com/en/latest
  • Network accessline 128
    The [add_execution](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.add_execution) method is then called on the [Strategy](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#py
  • Network accessline 130
    The last step is to run the backtest by calling the [backtest](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.backtest) method on the `Strategy` object. Set the `train_size` to `0.5` to specif
  • Network accessline 139
    **PyBroker** employs a powerful algorithm known as [Walkforward Analysis](https://www.youtube.com/watch?v=WBZ_Vv-iMv4) to perform backtesting. The algorithm partitions the backtest data into a fixed number of time windows, each containing a
  • Network accessline 145
    ![Walkforward Diagram](https://github.com/edtechre/pybroker/blob/master/docs/_static/walkforward.gif?raw=true)
  • Network accessline 149
    Let's consider a trading strategy that generates buy and sell signals from the [LinearRegression](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html) model that we trained earlier. The strategy is i
  • Network accessline 169
    The [ctx.preds('slr')](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.preds) method is used to access the predictions made by the ```'slr'``` model for the current stock symbol being executed
  • Network accessline 173
    Run the backtest by calling the [walkforward](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.walkforward) method on the `Strategy` object, passing the desired number of time windows and the tr
  • Network accessline 203
    Beyond linear regression, **PyBroker** can train other model types such as gradient boosted machines, neural networks, or any other architecture that we choose. To help support these models, **PyBroker** offers extensive customization optio
  • Network accessline 205
    Additionally, **PyBroker v2** now supports training [time series models](https://www.pybroker.com/en/latest/notebooks/16.%20Time%20Series%20Models.html) and [multi-symbol models](https://www.pybroker.com/en/latest/notebooks/17.%20Multi-Symb

skills/pybroker-model-trainer/references/wiki-16-time-series-models.md

  • Network accessline 11
    To show how this works, we will backtest two different strategies. The first relies on a volatility forecast from a [GARCH(1,1)](https://en.wikipedia.org/wiki/Autoregressive_conditional_heteroskedasticity) model built with the [arch](https:
  • Network accessline 25
    GARCH will model the volatility of a return series, so we start by defining an [indicator](https://www.pybroker.com/en/latest/reference/pybroker.indicator.html#pybroker.indicator.indicator) for log returns:
  • Network accessline 72
    By default, **PyBroker** passes all test window data to the model in a single call to make a make a prediction. While this vectorized approach is efficient, it fails for autoregressive models since they rely on the previous step's output to
  • Network accessline 84
    The strategy then uses the volatility forecast from [ctx.preds](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.preds) as a regime filter. It enters a long position when forecast volatility is
  • Network accessline 109
    The second strategy trains a [RandomForestRegressor](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html) to predict the next bar's return from lagged returns:
  • Network accessline 123
    The training function receives `lag_train` and `lag_test` parameters built from configuring the model with the desired number of [lags](https://www.pybroker.com/en/latest/reference/pybroker.model.html#pybroker.model.model). Each parameter i
  • Network accessline 132
    Registering the model with [lags](https://www.pybroker.com/en/latest/reference/pybroker.model.html#pybroker.model.model) set to `3` will include the past three lagged values for each column declared in [lag_cols](https://www.pybroker.com/en
  • Network accessline 144
    The strategy buys when [ctx.preds](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.preds) for the next-bar return is positive and exits when it is negative. We then run a [walkforward](https:/

skills/pybroker-model-trainer/references/wiki-17-multi-symbol-models.md

  • Network accessline 11
    **PyBroker v2** supports training one model across all symbols passed to [Strategy.add_execution](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.add_execution), as shown in this notebook.
  • Network accessline 23
    This notebook repurposes the linear regression example from [Training a Model](https://www.pybroker.com/en/latest/notebooks/6.%20Training%20a%20Model.html). Below, one shared [LinearRegression](https://scikit-learn.org/stable/modules/genera

skills/pybroker-multi-interval/assets/multi_interval_template.py

  • Executable scriptline 1
    Executable file

skills/pybroker-multi-interval/references/api-public-surface.md

  • Access to secretsline 367
    [Credential-related source omitted]
  • Network accessline 369
    Retrieves stock data from `Alpaca <https://alpaca.markets/>`_.
  • Access to secretsline 373
    [Credential-related source omitted]
  • Network accessline 375
    Retrieves crypto data from `Alpaca <https://alpaca.markets/>`_.
  • Network accessline 381
    Retrieves data from `Yahoo Finance <https://finance.yahoo.com/>`_\ .
  • Network accessline 383
    - `auto_adjust: bool` - `query(symbols: Union[str, Iterable[str]], start_date: Union[str, datetime], end_date: Union[str, datetime], _timeframe: Optional[str]='', _adjust: Optional[Any]=None) -> pd.DataFrame`: Queries data from `Yahoo Finan
  • Network accessline 384
    - `query(symbols: Union[str, Iterable[str]], start_date: Union[str, datetime], end_date: Union[str, datetime], _timeframe: Optional[str]='', _adjust: Optional[Any]=None) -> pd.DataFrame`: Queries data from `Yahoo Finance <https://finance.ya
  • Network accessline 402
    - `profit_factor(changes: NDArray[np.float64], use_log: bool=False) -> float`: Computes the profit factor, which is the ratio of gross profit to gross loss. - `log_profit_factor(changes: NDArray[np.float64]) -> float`: Computes the log tran
  • Network accessline 403
    - `log_profit_factor(changes: NDArray[np.float64]) -> float`: Computes the log transformed profit factor, which is the ratio of gross profit to gross loss. - `sharpe_ratio(returns: NDArray[np.float64], obs: Optional[int]=None) -> float`: Co
  • Network accessline 404
    - `sharpe_ratio(returns: NDArray[np.float64], obs: Optional[int]=None) -> float`: Computes the `Sharpe Ratio <https://en.wikipedia.org/wiki/Sharpe_ratio>`_, using the population standard deviation of ``returns``.
  • Network accessline 405
    - `downside_deviation(returns: NDArray[np.float64]) -> float`: Computes downside deviation, the denominator of the `Sortino Ratio <https://en.wikipedia.org/wiki/Sortino_ratio>`_.
  • Network accessline 406
    - `sortino_ratio(returns: NDArray[np.float64], obs: Optional[int]=None) -> float`: Computes the `Sortino Ratio <https://en.wikipedia.org/wiki/Sortino_ratio>`_.
  • Network accessline 429
    - `drawdown_conf(changes: NDArray[np.float64], returns: NDArray[np.float64], n_boot: int) -> DrawdownMetrics`: Computes upper bounds of confidence intervals for maximum drawdown using the bootstrap method. - `bootstrap_eval_all(changes: NDA
  • Network accessline 430
    - `bootstrap_eval_all(changes: NDArray[np.float64], returns: NDArray[np.float64], n_boot: int, bars_per_year: int) -> tuple[BootConfIntervals, BootConfIntervals, DrawdownMetrics]`: Computes all bootstrap metrics in one shared resampling pas
  • Network accessline 431
    - `relative_entropy(values: NDArray[np.float64]) -> float`: Computes the relative `entropy <https://en.wikipedia.org/wiki/Entropy_(information_theory)>`_.
  • Network accessline 432
    - `iqr(values: NDArray[np.float64]) -> float`: Computes the `interquartile range (IQR) <https://en.wikipedia.org/wiki/Interquartile_range>`_ of ``values``.
  • Network accessline 433
    - `ulcer_index(values: NDArray[np.float64], period: Optional[int]=None) -> float`: Computes the `Ulcer Index <https://en.wikipedia.org/wiki/Ulcer_index>`_ of ``values``: the root mean square of percentage drawdowns from the running peak.
  • Network accessline 434
    - `upi(values: NDArray[np.float64], period: Optional[int]=None, ui: Optional[float]=None, bars_per_year: Optional[int]=None) -> float`: Computes the `Ulcer Performance Index <https://en.wikipedia.org/wiki/Ulcer_index>`_ of ``values``: retur
  • Network accessline 566
    - `name: str` - `hyperparam_names() -> frozenset[str]` - `relative_entropy(data: Union[BarData, pd.DataFrame]) -> float`: Generates indicator data with ``data`` and computes its relative `entropy <https://en.wikipedia.org/wiki/Entropy_(info
  • Network accessline 567
    - `hyperparam_names() -> frozenset[str]` - `relative_entropy(data: Union[BarData, pd.DataFrame]) -> float`: Generates indicator data with ``data`` and computes its relative `entropy <https://en.wikipedia.org/wiki/Entropy_(information_theory
  • Network accessline 568
    - `relative_entropy(data: Union[BarData, pd.DataFrame]) -> float`: Generates indicator data with ``data`` and computes its relative `entropy <https://en.wikipedia.org/wiki/Entropy_(information_theory)>`_.
  • Network accessline 569
    - `iqr(data: Union[BarData, pd.DataFrame]) -> float`: Generates indicator data with ``data`` and computes its `interquartile range (IQR) <https://en.wikipedia.org/wiki/Interquartile_range>`_.
  • Network accessline 1119
    - `unique_dates() -> NDArray[np.datetime64]`: Returns sorted unique dates across every symbol in the store. - `fetch_dict(symbol: str, names: Iterable[str], end_index: Optional[int]=None) -> dict[str, Optional[NDArray]]`: Fetches a ``dict``
  • Network accessline 1120
    - `fetch_dict(symbol: str, names: Iterable[str], end_index: Optional[int]=None) -> dict[str, Optional[NDArray]]`: Fetches a ``dict`` of column data for ``symbol``. - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> Optional[
  • Network accessline 1121
    - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> Optional[NDArray]`: Fetches a :class:`numpy.ndarray` of column data for ``symbol``.
  • Network accessline 1129
    - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> NDArray[np.float64]`: Fetches :class:`pybroker.indicator.Indicator` data.
  • Network accessline 1151
    - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> pd.DataFrame`: Fetches model input data.
  • Network accessline 1158
    - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> NDArray`: Fetches model predictions.
  • Network accessline 1167
    - `fetch_float(symbol: str, price: Union[int, float, np.floating, Decimal, PriceType, Callable[[str, BarData], Union[int, float, Decimal]]]) -> float`: Returns a bar price as ``float`` using the per-bar cache when possible. - `fetch_bar_ohl
  • Network accessline 1169
    - `fetch(symbol: str, price: Union[int, float, np.floating, Decimal, PriceType, Callable[[str, BarData], Union[int, float, Decimal]]]) -> Decimal`
  • Network accessline 1298
    Mixin implementing logic for `Walkforward Analysis <https://www.pybroker.com/en/latest/notebooks/6.%20Training%20a%20Model.html#Walkforward-Analysis>`_.
  • Network accessline 1300
    - `walkforward_split(df: pd.DataFrame, windows: int, lookahead: int, train_size: float=0.9, shuffle: bool=False) -> Iterator[WalkforwardWindow]`: Splits a :class:`pandas.DataFrame` containing data for multiple ticker symbols into an :class:
  • Network accessline 1332
    - `clear_executions()`: Clears executions that were added with :meth:`.add_execution`. - `backtest(start_date: Optional[Union[str, datetime]]=None, end_date: Optional[Union[str, datetime]]=None, timeframe: str='', between_time: Optional[tup
  • Network accessline 1334
    - `walkforward(windows: int, lookahead: int=1, start_date: Optional[Union[str, datetime]]=None, end_date: Optional[Union[str, datetime]]=None, timeframe: str='', between_time: Optional[tuple[str, str]]=None, days: Optional[Union[str, Day, I
  • Network accessline 1383
    Retrieves data from `AKShare <https://akshare.akfamily.xyz/>`_.
  • Network accessline 1388
    Retrieves data from Yahoo Finance using `Yahooquery <https://github.com/dpguthrie/yahooquery>`_\ .

skills/pybroker-multi-interval/references/pybroker_model.pyi

  • Network accessline 240
    class Alpaca(DataSource):     """Retrieves stock data from `Alpaca <https://alpaca.markets/>`_."""
  • Network accessline 241
    """Retrieves stock data from `Alpaca <https://alpaca.markets/>`_."""
  • Access to secretsline 242
    [Credential-related source omitted]
  • Network accessline 252
    class AlpacaCrypto(DataSource):     """Retrieves crypto data from `Alpaca <https://alpaca.markets/>`_."""
  • Network accessline 253
    """Retrieves crypto data from `Alpaca <https://alpaca.markets/>`_."""
  • Access to secretsline 267
    [Credential-related source omitted]
  • Network accessline 277
    class YFinance(DataSource):     """Retrieves data from `Yahoo Finance <https://finance.yahoo.com/>`_."""
  • Network accessline 278
    """Retrieves data from `Yahoo Finance <https://finance.yahoo.com/>`_."""
  • Network accessline 293
    # --- src/pybroker/ext/data.py --- class AKShare(DataSource):     """Retrieves data from `AKShare <https://akshare.akfamily.xyz/>`_."""
  • Network accessline 295
    """Retrieves data from `AKShare <https://akshare.akfamily.xyz/>`_."""
  • Network accessline 297
    class YQuery(DataSource):     """Retrieves data from Yahoo Finance using `Yahooquery <https://github.com/dpguthrie/yahooquery>`_."""
  • Network accessline 298
    """Retrieves data from Yahoo Finance using `Yahooquery <https://github.com/dpguthrie/yahooquery>`_."""

skills/pybroker-multi-interval/references/pybroker_types.pyi

  • Network accessline 427
    end_index: Optional[int] = None,     ) -> dict[str, Optional[NDArray]]: ...     def fetch(
  • Network accessline 428
    ) -> dict[str, Optional[NDArray]]: ...     def fetch(         self, symbol: str, name: str, end_index: Optional[int] = None
  • Network accessline 429
    def fetch(
  • Network accessline 440
    """Caches and retrieves :class:`pybroker.indicator.Indicator` data."""     # Constructed by the framework; not user-instantiable.     def fetch(
  • Network accessline 441
    # Constructed by the framework; not user-instantiable.     def fetch(         self, symbol: str, name: str, end_index: Optional[int] = None
  • Network accessline 442
    def fetch(

skills/pybroker-multi-interval/references/wiki-05-writing-indicators.md

  • Network accessline 9
    This notebook explains how to create and integrate custom stock indicators in **PyBroker**.  Indicators in **PyBroker** are written using [NumPy](https://numpy.org/), a powerful library for numerical computing. To optimize performance, we'l
  • Network accessline 16
    The following code shows an indicator function that calculates close prices minus a moving average (CMMA), which can be used for a [mean reversion](https://en.wikipedia.org/wiki/Mean_reversion_(finance)) strategy:
  • Network accessline 42
    The ```cmma``` function takes two arguments: ```bar_data```, which is an instance of the [BarData](https://www.pybroker.com/en/latest/reference/pybroker.common.html#pybroker.common.BarData) class that holds OHLCV data and custom fields, and
  • Network accessline 44
    The ```vec_cmma``` function is JIT-compiled by Numba and nested inside ```cmma```. This is necessary since a Numba compiled function supports a NumPy array as an argument but not an instance of a Python class like ```BarData```. Note the co
  • Network accessline 54
    Here, we are giving the name ```cmma_20``` to the indicator function and specifying the ```lookback``` parameter as ```20``` bars. Any arguments in the indicator function that come after ```bar_data``` will be passed as user-defined argumen
  • Network accessline 56
    The following is an example of how to use the registered ```Indicator``` in **PyBroker** with some data downloaded from [Yahoo Finance](https://finance.yahoo.com):
  • Network accessline 71
    As you can see, the ```Indicator``` instance is a ```Callable```. Once called, the resulting computed indicator values are returned as a [Pandas Series](https://pandas.pydata.org/docs/reference/api/pandas.Series.html).
  • Network accessline 73
    The ```Indicator``` class also provides functions for measuring its information content. For example, you can compute the [interquartile range (IQR)](https://en.wikipedia.org/wiki/Interquartile_range):
  • Network accessline 79
    Or compute the relative [entropy](https://en.wikipedia.org/wiki/Entropy_(information_theory)):
  • Network accessline 99
    The indicator values are retrieved by calling [ctx.indicator](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.indicator) on the [ExecContext](https://www.pybroker.com/en/latest/reference/pybro
  • Network accessline 108
    Here, the ```buy_cmma_cross``` function is added to the [Strategy](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy) along with the ```cmma_20``` indicator. We can enable caching of the computed
  • Network accessline 121
    **PyBroker** computes indicator values before the backtest runs. By default, these calculations occur serially. See [Configuring Parallelization](https://www.pybroker.com/en/latest/notebooks/11.%20Configuring%20Parallelization.html) for det
  • Network accessline 125
    **PyBroker** provides vectorized helper functions to make the process of computing indicators easier. One of these helper functions is [highv](https://www.pybroker.com/en/latest/reference/pybroker.vect.html#pybroker.vect.highv), which calcu
  • Network accessline 141
    The [pybroker.vect](https://www.pybroker.com/en/latest/reference/pybroker.vect.html) module also includes other vectorized helpers such as [lowv](https://www.pybroker.com/en/latest/reference/pybroker.vect.html#pybroker.vect.lowv), [sumv](ht
  • Network accessline 143
    Additionally, **PyBroker** includes convenient wrappers for [highest](https://www.pybroker.com/en/latest/reference/pybroker.indicator.html#pybroker.indicator.highest) and [lowest](https://www.pybroker.com/en/latest/reference/pybroker.indica
  • Network accessline 154
    Use an [IndicatorSet](https://www.pybroker.com/en/latest/reference/pybroker.indicator.html#pybroker.indicator.IndicatorSet) to calculate multiple indicators. Add the `cmma_20` and `hhv_5` indicators to the `IndicatorSet` to compute them tog
  • Network accessline 166
    [TA-Lib](https://github.com/TA-Lib/ta-lib-python) is a widely used technical analysis library that implements many financial indicators. You can install it with `pip install ta-lib`.
  • Network accessline 181
    **PyBroker** also includes built-in indicators that are available in the [indicator module](https://www.pybroker.com/en/latest/reference/pybroker.indicator.html). **PyBroker** reimplements these standard indicators with volatility normaliza
  • Network accessline 183
    [In the next tutorial, you will learn how to train a model using custom indicators in PyBroker](https://www.pybroker.com/en/latest/notebooks/6.%20Training%20a%20Model.html).

skills/pybroker-multi-interval/references/wiki-06-training-a-model.md

  • Network accessline 9
    In the [last notebook](https://www.pybroker.com/en/latest/notebooks/5.%20Writing%20Indicators.html), we learned how to write stock indicators in **PyBroker**. Indicators are a good starting point for developing a trading strategy. But to cr
  • Network accessline 11
    One of the main features of **PyBroker** is the ability to train and backtest machine learning models. These models can utilize indicators as features to make more accurate predictions about market movements. Once trained, these models can 
  • Network accessline 22
    As with [DataSource](https://www.pybroker.com/en/latest/reference/pybroker.data.html#pybroker.data.DataSource) and [Indicator](https://www.pybroker.com/en/latest/reference/pybroker.indicator.html#pybroker.indicator.Indicator) data, **PyBrok
  • Network accessline 28
    In [the last notebook](https://www.pybroker.com/en/latest/notebooks/5.%20Writing%20Indicators.html), we implemented an indicator that calculates the close-minus-moving-average (CMMA) using [NumPy](https://www.numpy.org) and [Numba](https://
  • Network accessline 59
    Next, we want to build a model that predicts the next day's return using the 20-day CMMA. Using [simple linear regression](https://en.wikipedia.org/wiki/Simple_linear_regression) is a good approach to begin experimenting with as a baseline 
  • Network accessline 61
    Below we import a [LinearRegression](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html) model from [scikit-learn](https://scikit-learn.org/stable/):
  • Network accessline 110
    After fitting the model, the function uses the testing data to evaluate the model's accuracy, specifically by computing the [R-squared](https://en.wikipedia.org/wiki/Coefficient_of_determination) score. The R-squared score provides a measur
  • Network accessline 114
    Once the function to train the model has been defined, it needs to be registered with **PyBroker**. This is done by creating a new [ModelSource](https://www.pybroker.com/en/latest/reference/pybroker.model.html#pybroker.model.ModelSource)  i
  • Network accessline 120
    To create a trading strategy that uses the trained model, create a new [Strategy](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy) object using the [YFinance](https://www.pybroker.com/en/latest
  • Network accessline 128
    The [add_execution](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.add_execution) method is then called on the [Strategy](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#py
  • Network accessline 130
    The last step is to run the backtest by calling the [backtest](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.backtest) method on the `Strategy` object. Set the `train_size` to `0.5` to specif
  • Network accessline 139
    **PyBroker** employs a powerful algorithm known as [Walkforward Analysis](https://www.youtube.com/watch?v=WBZ_Vv-iMv4) to perform backtesting. The algorithm partitions the backtest data into a fixed number of time windows, each containing a
  • Network accessline 145
    ![Walkforward Diagram](https://github.com/edtechre/pybroker/blob/master/docs/_static/walkforward.gif?raw=true)
  • Network accessline 149
    Let's consider a trading strategy that generates buy and sell signals from the [LinearRegression](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html) model that we trained earlier. The strategy is i
  • Network accessline 169
    The [ctx.preds('slr')](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.preds) method is used to access the predictions made by the ```'slr'``` model for the current stock symbol being executed
  • Network accessline 173
    Run the backtest by calling the [walkforward](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.walkforward) method on the `Strategy` object, passing the desired number of time windows and the tr
  • Network accessline 203
    Beyond linear regression, **PyBroker** can train other model types such as gradient boosted machines, neural networks, or any other architecture that we choose. To help support these models, **PyBroker** offers extensive customization optio
  • Network accessline 205
    Additionally, **PyBroker v2** now supports training [time series models](https://www.pybroker.com/en/latest/notebooks/16.%20Time%20Series%20Models.html) and [multi-symbol models](https://www.pybroker.com/en/latest/notebooks/17.%20Multi-Symb

skills/pybroker-multi-interval/references/wiki-15-multiple-time-intervals.md

  • Network accessline 27
    Your chosen interval must always be longer than the bars being compressed. For example, if you fetch daily bars from [YFinance](https://www.pybroker.com/en/latest/reference/pybroker.data.html#pybroker.data.YFinance), then `"weekly"` and `"m
  • Network accessline 46
    The [compress_bars](https://www.pybroker.com/en/latest/reference/pybroker.interval.html#pybroker.interval.compress_bars) function converts OHLCV data (either a [Pandas DataFrame](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame
  • Network accessline 52
    *   **Volume:** The sum of the volumes. *   **VWAP:** The volume-weighted average. *   **Custom columns:** The last value in the period (e.g., [YFinance](https://www.pybroker.com/en/latest/reference/pybroker.data.html#pybroker.data.YFinance
  • Network accessline 54
    *   **Custom columns:** The last value in the period (e.g., [YFinance](https://www.pybroker.com/en/latest/reference/pybroker.data.html#pybroker.data.YFinance)'s `adj_close`).
  • Network accessline 58
    Let's compress AMD into calendar weeks and view the result as a [Pandas DataFrame](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html) with [bars_to_df](https://www.pybroker.com/en/latest/reference/pybroker.common.html#pybro
  • Network accessline 77
    To use higher timeframes in your backtest, pass the `intervals` parameter to [add_execution](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.add_execution). Your execution function can then acc
  • Network accessline 81
    To prevent look-ahead bias, [ctx.interval](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.interval) only ever exposes *completed* bars. For example, the week or month that is currently formin
  • Network accessline 117
    To compute an indicator on compressed bars, bind it to one or more intervals with [Indicator.intervals(...)](https://www.pybroker.com/en/latest/reference/pybroker.indicator.html#pybroker.indicator.Indicator.intervals).
  • Network accessline 152
    **PyBroker** automatically combines bound intervals with those in the execution's `intervals` parameter. Here, the `"weekly"` interval is made accessible via [ctx.interval("weekly")](https://www.pybroker.com/en/latest/reference/pybroker.con
  • Network accessline 154
    Note that the binding will override also computing the indicator on the base timeframe of the data source. To also compute the indicator on the base timeframe of the data source, pass `"base"` to [Indicator.intervals()](https://www.pybroker
  • Network accessline 163
    You can bind models in the same way with [ModelSource.intervals(...)](https://www.pybroker.com/en/latest/reference/pybroker.model.html#pybroker.model.ModelSource.intervals). **PyBroker** will then train models for each interval using the in
  • Network accessline 165
    This example trains a [LinearRegression](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html) model to predict the next weekly return from the weekly close:
  • Network accessline 202
    During [Walkforward Analysis](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.walkforward), the `lookahead` between an interval model's train and test data is enforced using the compressed bar 

skills/pybroker-optimize/assets/optimize_template.py

  • Executable scriptline 1
    Executable file

skills/pybroker-optimize/references/api-public-surface.md

  • Access to secretsline 367
    [Credential-related source omitted]
  • Network accessline 369
    Retrieves stock data from `Alpaca <https://alpaca.markets/>`_.
  • Access to secretsline 373
    [Credential-related source omitted]
  • Network accessline 375
    Retrieves crypto data from `Alpaca <https://alpaca.markets/>`_.
  • Network accessline 381
    Retrieves data from `Yahoo Finance <https://finance.yahoo.com/>`_\ .
  • Network accessline 383
    - `auto_adjust: bool` - `query(symbols: Union[str, Iterable[str]], start_date: Union[str, datetime], end_date: Union[str, datetime], _timeframe: Optional[str]='', _adjust: Optional[Any]=None) -> pd.DataFrame`: Queries data from `Yahoo Finan
  • Network accessline 384
    - `query(symbols: Union[str, Iterable[str]], start_date: Union[str, datetime], end_date: Union[str, datetime], _timeframe: Optional[str]='', _adjust: Optional[Any]=None) -> pd.DataFrame`: Queries data from `Yahoo Finance <https://finance.ya
  • Network accessline 402
    - `profit_factor(changes: NDArray[np.float64], use_log: bool=False) -> float`: Computes the profit factor, which is the ratio of gross profit to gross loss. - `log_profit_factor(changes: NDArray[np.float64]) -> float`: Computes the log tran
  • Network accessline 403
    - `log_profit_factor(changes: NDArray[np.float64]) -> float`: Computes the log transformed profit factor, which is the ratio of gross profit to gross loss. - `sharpe_ratio(returns: NDArray[np.float64], obs: Optional[int]=None) -> float`: Co
  • Network accessline 404
    - `sharpe_ratio(returns: NDArray[np.float64], obs: Optional[int]=None) -> float`: Computes the `Sharpe Ratio <https://en.wikipedia.org/wiki/Sharpe_ratio>`_, using the population standard deviation of ``returns``.
  • Network accessline 405
    - `downside_deviation(returns: NDArray[np.float64]) -> float`: Computes downside deviation, the denominator of the `Sortino Ratio <https://en.wikipedia.org/wiki/Sortino_ratio>`_.
  • Network accessline 406
    - `sortino_ratio(returns: NDArray[np.float64], obs: Optional[int]=None) -> float`: Computes the `Sortino Ratio <https://en.wikipedia.org/wiki/Sortino_ratio>`_.
  • Network accessline 429
    - `drawdown_conf(changes: NDArray[np.float64], returns: NDArray[np.float64], n_boot: int) -> DrawdownMetrics`: Computes upper bounds of confidence intervals for maximum drawdown using the bootstrap method. - `bootstrap_eval_all(changes: NDA
  • Network accessline 430
    - `bootstrap_eval_all(changes: NDArray[np.float64], returns: NDArray[np.float64], n_boot: int, bars_per_year: int) -> tuple[BootConfIntervals, BootConfIntervals, DrawdownMetrics]`: Computes all bootstrap metrics in one shared resampling pas
  • Network accessline 431
    - `relative_entropy(values: NDArray[np.float64]) -> float`: Computes the relative `entropy <https://en.wikipedia.org/wiki/Entropy_(information_theory)>`_.
  • Network accessline 432
    - `iqr(values: NDArray[np.float64]) -> float`: Computes the `interquartile range (IQR) <https://en.wikipedia.org/wiki/Interquartile_range>`_ of ``values``.
  • Network accessline 433
    - `ulcer_index(values: NDArray[np.float64], period: Optional[int]=None) -> float`: Computes the `Ulcer Index <https://en.wikipedia.org/wiki/Ulcer_index>`_ of ``values``: the root mean square of percentage drawdowns from the running peak.
  • Network accessline 434
    - `upi(values: NDArray[np.float64], period: Optional[int]=None, ui: Optional[float]=None, bars_per_year: Optional[int]=None) -> float`: Computes the `Ulcer Performance Index <https://en.wikipedia.org/wiki/Ulcer_index>`_ of ``values``: retur
  • Network accessline 566
    - `name: str` - `hyperparam_names() -> frozenset[str]` - `relative_entropy(data: Union[BarData, pd.DataFrame]) -> float`: Generates indicator data with ``data`` and computes its relative `entropy <https://en.wikipedia.org/wiki/Entropy_(info
  • Network accessline 567
    - `hyperparam_names() -> frozenset[str]` - `relative_entropy(data: Union[BarData, pd.DataFrame]) -> float`: Generates indicator data with ``data`` and computes its relative `entropy <https://en.wikipedia.org/wiki/Entropy_(information_theory
  • Network accessline 568
    - `relative_entropy(data: Union[BarData, pd.DataFrame]) -> float`: Generates indicator data with ``data`` and computes its relative `entropy <https://en.wikipedia.org/wiki/Entropy_(information_theory)>`_.
  • Network accessline 569
    - `iqr(data: Union[BarData, pd.DataFrame]) -> float`: Generates indicator data with ``data`` and computes its `interquartile range (IQR) <https://en.wikipedia.org/wiki/Interquartile_range>`_.
  • Network accessline 1119
    - `unique_dates() -> NDArray[np.datetime64]`: Returns sorted unique dates across every symbol in the store. - `fetch_dict(symbol: str, names: Iterable[str], end_index: Optional[int]=None) -> dict[str, Optional[NDArray]]`: Fetches a ``dict``
  • Network accessline 1120
    - `fetch_dict(symbol: str, names: Iterable[str], end_index: Optional[int]=None) -> dict[str, Optional[NDArray]]`: Fetches a ``dict`` of column data for ``symbol``. - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> Optional[
  • Network accessline 1121
    - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> Optional[NDArray]`: Fetches a :class:`numpy.ndarray` of column data for ``symbol``.
  • Network accessline 1129
    - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> NDArray[np.float64]`: Fetches :class:`pybroker.indicator.Indicator` data.
  • Network accessline 1151
    - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> pd.DataFrame`: Fetches model input data.
  • Network accessline 1158
    - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> NDArray`: Fetches model predictions.
  • Network accessline 1167
    - `fetch_float(symbol: str, price: Union[int, float, np.floating, Decimal, PriceType, Callable[[str, BarData], Union[int, float, Decimal]]]) -> float`: Returns a bar price as ``float`` using the per-bar cache when possible. - `fetch_bar_ohl
  • Network accessline 1169
    - `fetch(symbol: str, price: Union[int, float, np.floating, Decimal, PriceType, Callable[[str, BarData], Union[int, float, Decimal]]]) -> Decimal`
  • Network accessline 1298
    Mixin implementing logic for `Walkforward Analysis <https://www.pybroker.com/en/latest/notebooks/6.%20Training%20a%20Model.html#Walkforward-Analysis>`_.
  • Network accessline 1300
    - `walkforward_split(df: pd.DataFrame, windows: int, lookahead: int, train_size: float=0.9, shuffle: bool=False) -> Iterator[WalkforwardWindow]`: Splits a :class:`pandas.DataFrame` containing data for multiple ticker symbols into an :class:
  • Network accessline 1332
    - `clear_executions()`: Clears executions that were added with :meth:`.add_execution`. - `backtest(start_date: Optional[Union[str, datetime]]=None, end_date: Optional[Union[str, datetime]]=None, timeframe: str='', between_time: Optional[tup
  • Network accessline 1334
    - `walkforward(windows: int, lookahead: int=1, start_date: Optional[Union[str, datetime]]=None, end_date: Optional[Union[str, datetime]]=None, timeframe: str='', between_time: Optional[tuple[str, str]]=None, days: Optional[Union[str, Day, I
  • Network accessline 1383
    Retrieves data from `AKShare <https://akshare.akfamily.xyz/>`_.
  • Network accessline 1388
    Retrieves data from Yahoo Finance using `Yahooquery <https://github.com/dpguthrie/yahooquery>`_\ .

skills/pybroker-optimize/references/pybroker_model.pyi

  • Network accessline 240
    class Alpaca(DataSource):     """Retrieves stock data from `Alpaca <https://alpaca.markets/>`_."""
  • Network accessline 241
    """Retrieves stock data from `Alpaca <https://alpaca.markets/>`_."""
  • Access to secretsline 242
    [Credential-related source omitted]
  • Network accessline 252
    class AlpacaCrypto(DataSource):     """Retrieves crypto data from `Alpaca <https://alpaca.markets/>`_."""
  • Network accessline 253
    """Retrieves crypto data from `Alpaca <https://alpaca.markets/>`_."""
  • Access to secretsline 267
    [Credential-related source omitted]
  • Network accessline 277
    class YFinance(DataSource):     """Retrieves data from `Yahoo Finance <https://finance.yahoo.com/>`_."""
  • Network accessline 278
    """Retrieves data from `Yahoo Finance <https://finance.yahoo.com/>`_."""
  • Network accessline 293
    # --- src/pybroker/ext/data.py --- class AKShare(DataSource):     """Retrieves data from `AKShare <https://akshare.akfamily.xyz/>`_."""
  • Network accessline 295
    """Retrieves data from `AKShare <https://akshare.akfamily.xyz/>`_."""
  • Network accessline 297
    class YQuery(DataSource):     """Retrieves data from Yahoo Finance using `Yahooquery <https://github.com/dpguthrie/yahooquery>`_."""
  • Network accessline 298
    """Retrieves data from Yahoo Finance using `Yahooquery <https://github.com/dpguthrie/yahooquery>`_."""

skills/pybroker-optimize/references/pybroker_types.pyi

  • Network accessline 427
    end_index: Optional[int] = None,     ) -> dict[str, Optional[NDArray]]: ...     def fetch(
  • Network accessline 428
    ) -> dict[str, Optional[NDArray]]: ...     def fetch(         self, symbol: str, name: str, end_index: Optional[int] = None
  • Network accessline 429
    def fetch(
  • Network accessline 440
    """Caches and retrieves :class:`pybroker.indicator.Indicator` data."""     # Constructed by the framework; not user-instantiable.     def fetch(
  • Network accessline 441
    # Constructed by the framework; not user-instantiable.     def fetch(         self, symbol: str, name: str, end_index: Optional[int] = None
  • Network accessline 442
    def fetch(

skills/pybroker-optimize/references/wiki-03-evaluating-with-bootstrap-metrics.md

  • Network accessline 11
    [In the previous notebook](https://www.pybroker.com/en/latest/notebooks/2.%20Backtesting%20a%20Strategy.html), we implemented and backtested a trading strategy. Here is that implementation again:
  • Network accessline 37
    As before, we create a new [Strategy](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy) instance with the given configurations:
  • Network accessline 53
    While the `total_pnl` metric above suggests a profitable strategy, these results could just be due to chance. To increase confidence in our evaluation, we can use the [bootstrap method](https://en.wikipedia.org/wiki/Bootstrapping_(statistic
  • Network accessline 59
    **PyBroker** applies the bootstrap method to calculate [confidence intervals](https://en.wikipedia.org/wiki/Confidence_interval) for two performance metrics: the [Profit Factor](https://www.pybroker.com/en/latest/reference/pybroker.eval.htm
  • Network accessline 65
    **PyBroker** uses the [bias-corrected and accelerated (BCa) bootstrap method](https://en.wikipedia.org/wiki/Bootstrapping_(statistics)#Bias-corrected_and_accelerated_(BCa)_bootstrap) to calculate confidence intervals for these metrics. Retu
  • Network accessline 83
    [In the next notebook, we will discuss how to incorporate ranking long and short signals in your trading strategies](https://www.pybroker.com/en/latest/notebooks/4.%20Ranking%20Long%20and%20Short%20Signals.html).

skills/pybroker-optimize/references/wiki-11-configuring-parallelization.md

  • Network accessline 9
    **PyBroker** uses [Joblib](https://joblib.readthedocs.io/) to compute indicators, train models, and optimize parameters in parallel.
  • Network accessline 13
    [set_parallel](https://www.pybroker.com/en/latest/reference/pybroker.parallel.html#pybroker.parallel.set_parallel) updates the global Joblib configuration. The [n_jobs](https://www.pybroker.com/en/latest/reference/pybroker.parallel.html#pyb
  • Network accessline 29
    Indicators are computed **per symbol**: all indicators for a given symbol are grouped into a single task, and one task is dispatched per symbol. Passing `parallel_indicators=True` to [backtest](https://www.pybroker.com/en/latest/reference/p
  • Network accessline 68
    Standalone indicator computation with an [IndicatorSet](https://www.pybroker.com/en/latest/reference/pybroker.indicator.html#pybroker.indicator.IndicatorSet) accepts the same `parallel_indicators` flag:
  • Network accessline 83
    Model training runs serially by default. Passing `parallel_models=True` to [backtest](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.backtest) or [walkforward](https://www.pybroker.com/en/late
  • Network accessline 85
    This example adapts the linear regression model from [Training a Model](https://www.pybroker.com/en/latest/notebooks/6.%20Training%20a%20Model.html):
  • Network accessline 132
    [Ray](https://www.ray.io/) can distribute the same work across many cores or an entire cluster. Install it with `pip install ray` and then register it with Joblib via [register_ray](https://docs.ray.io/en/latest/ray-more-libs/joblib.html) (
  • Network accessline 142
    After registering Ray, pass `backend="ray"` to [set_parallel](https://www.pybroker.com/en/latest/reference/pybroker.parallel.html#pybroker.parallel.set_parallel) to make it available as a backend:
  • Network accessline 149
    **PyBroker** will now use the Ray backend for all parallel tasks. For example, calling [backtest](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.backtest) with `parallel_indicators=True`:
  • Network accessline 158
    We will explore [parameter optimization](https://www.pybroker.com/en/latest/notebooks/12.%20Parameter%20Optimization.html) in the next notebook, which can also be parallelized in certain scenarios.

skills/pybroker-optimize/references/wiki-12-parameter-optimization.md

  • Network accessline 9
    **PyBroker v2** supports parameterized strategies. This allows you to backtest strategies using different combinations of parameters and automatically select the best performers. This process is known as **parameter optimization** and is ha
  • Network accessline 15
    A hyperparameter is a named, tunable value created with [hyperparam](https://www.pybroker.com/en/latest/reference/pybroker.optimize.html#pybroker.optimize.hyperparam). Each one has a [default](https://www.pybroker.com/en/latest/reference/py
  • Network accessline 19
    - **Indicators**: pass it as a keyword argument to [indicator](https://www.pybroker.com/en/latest/reference/pybroker.indicator.html#pybroker.indicator.indicator).
  • Network accessline 20
    - **Executions**: attach it with `hyperparams=` on [add_execution](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.add_execution) and read it with [ctx.hyperparam](https://www.pybroker.com/en/l
  • Network accessline 71
    The [optimize](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.optimize) method splits the data into train and test windows as specified by `train_size` (`0.5` for 50/50 by default). As Optuna 
  • Network accessline 86
    [best_params](https://www.pybroker.com/en/latest/reference/pybroker.optimize.html#pybroker.optimize.OptimizeResult.best_params) holds the best in-sample values, and [best_score](https://www.pybroker.com/en/latest/reference/pybroker.optimize
  • Network accessline 88
    Using the optimized parameters, we're able to see an improvment to the total return from before. The [result](https://www.pybroker.com/en/latest/reference/pybroker.optimize.html#pybroker.optimize.OptimizeResult.result) attribute contains th
  • Network accessline 96
    Grid search grows multiplicatively with each added hyperparameter. An alternative approach is using `sampler="tpe"`. Optuna's [TPESampler](https://optuna.readthedocs.io/en/stable/reference/samplers/generated/optuna.samplers.TPESampler.html)
  • Network accessline 111
    `sampler="random"` chooses combinations uniformly at random with Optuna's [RandomSampler](https://optuna.readthedocs.io/en/stable/reference/samplers/generated/optuna.samplers.RandomSampler.html). Like grid, random trials can be evaluated in
  • Network accessline 118
    Any [optuna.samplers.BaseSampler](https://optuna.readthedocs.io/en/stable/reference/samplers/index.html) instance can also be passed directly to [optimize](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strateg
  • Network accessline 131
    Every optimization also returns the underlying [optuna.Study](https://optuna.readthedocs.io/en/stable/reference/generated/optuna.study.Study.html) for inspecting the trials:
  • Network accessline 139
    Finally, [optimize](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.optimize) supports walkforward optimization. If you pass `> 1` to the `windows` parameter, PyBroker will independently tune t
  • Network accessline 154
    Each window is tuned separately, so the best parameters can differ between windows. The combined result contains the [best_params](https://www.pybroker.com/en/latest/reference/pybroker.optimize.html#pybroker.optimize.OptimizeResult.best_par

skills/pybroker-rotational-trading/assets/rotation_template.py

  • Executable scriptline 1
    Executable file

skills/pybroker-rotational-trading/references/api-public-surface.md

  • Access to secretsline 367
    [Credential-related source omitted]
  • Network accessline 369
    Retrieves stock data from `Alpaca <https://alpaca.markets/>`_.
  • Access to secretsline 373
    [Credential-related source omitted]
  • Network accessline 375
    Retrieves crypto data from `Alpaca <https://alpaca.markets/>`_.
  • Network accessline 381
    Retrieves data from `Yahoo Finance <https://finance.yahoo.com/>`_\ .
  • Network accessline 383
    - `auto_adjust: bool` - `query(symbols: Union[str, Iterable[str]], start_date: Union[str, datetime], end_date: Union[str, datetime], _timeframe: Optional[str]='', _adjust: Optional[Any]=None) -> pd.DataFrame`: Queries data from `Yahoo Finan
  • Network accessline 384
    - `query(symbols: Union[str, Iterable[str]], start_date: Union[str, datetime], end_date: Union[str, datetime], _timeframe: Optional[str]='', _adjust: Optional[Any]=None) -> pd.DataFrame`: Queries data from `Yahoo Finance <https://finance.ya
  • Network accessline 402
    - `profit_factor(changes: NDArray[np.float64], use_log: bool=False) -> float`: Computes the profit factor, which is the ratio of gross profit to gross loss. - `log_profit_factor(changes: NDArray[np.float64]) -> float`: Computes the log tran
  • Network accessline 403
    - `log_profit_factor(changes: NDArray[np.float64]) -> float`: Computes the log transformed profit factor, which is the ratio of gross profit to gross loss. - `sharpe_ratio(returns: NDArray[np.float64], obs: Optional[int]=None) -> float`: Co
  • Network accessline 404
    - `sharpe_ratio(returns: NDArray[np.float64], obs: Optional[int]=None) -> float`: Computes the `Sharpe Ratio <https://en.wikipedia.org/wiki/Sharpe_ratio>`_, using the population standard deviation of ``returns``.
  • Network accessline 405
    - `downside_deviation(returns: NDArray[np.float64]) -> float`: Computes downside deviation, the denominator of the `Sortino Ratio <https://en.wikipedia.org/wiki/Sortino_ratio>`_.
  • Network accessline 406
    - `sortino_ratio(returns: NDArray[np.float64], obs: Optional[int]=None) -> float`: Computes the `Sortino Ratio <https://en.wikipedia.org/wiki/Sortino_ratio>`_.
  • Network accessline 429
    - `drawdown_conf(changes: NDArray[np.float64], returns: NDArray[np.float64], n_boot: int) -> DrawdownMetrics`: Computes upper bounds of confidence intervals for maximum drawdown using the bootstrap method. - `bootstrap_eval_all(changes: NDA
  • Network accessline 430
    - `bootstrap_eval_all(changes: NDArray[np.float64], returns: NDArray[np.float64], n_boot: int, bars_per_year: int) -> tuple[BootConfIntervals, BootConfIntervals, DrawdownMetrics]`: Computes all bootstrap metrics in one shared resampling pas
  • Network accessline 431
    - `relative_entropy(values: NDArray[np.float64]) -> float`: Computes the relative `entropy <https://en.wikipedia.org/wiki/Entropy_(information_theory)>`_.
  • Network accessline 432
    - `iqr(values: NDArray[np.float64]) -> float`: Computes the `interquartile range (IQR) <https://en.wikipedia.org/wiki/Interquartile_range>`_ of ``values``.
  • Network accessline 433
    - `ulcer_index(values: NDArray[np.float64], period: Optional[int]=None) -> float`: Computes the `Ulcer Index <https://en.wikipedia.org/wiki/Ulcer_index>`_ of ``values``: the root mean square of percentage drawdowns from the running peak.
  • Network accessline 434
    - `upi(values: NDArray[np.float64], period: Optional[int]=None, ui: Optional[float]=None, bars_per_year: Optional[int]=None) -> float`: Computes the `Ulcer Performance Index <https://en.wikipedia.org/wiki/Ulcer_index>`_ of ``values``: retur
  • Network accessline 566
    - `name: str` - `hyperparam_names() -> frozenset[str]` - `relative_entropy(data: Union[BarData, pd.DataFrame]) -> float`: Generates indicator data with ``data`` and computes its relative `entropy <https://en.wikipedia.org/wiki/Entropy_(info
  • Network accessline 567
    - `hyperparam_names() -> frozenset[str]` - `relative_entropy(data: Union[BarData, pd.DataFrame]) -> float`: Generates indicator data with ``data`` and computes its relative `entropy <https://en.wikipedia.org/wiki/Entropy_(information_theory
  • Network accessline 568
    - `relative_entropy(data: Union[BarData, pd.DataFrame]) -> float`: Generates indicator data with ``data`` and computes its relative `entropy <https://en.wikipedia.org/wiki/Entropy_(information_theory)>`_.
  • Network accessline 569
    - `iqr(data: Union[BarData, pd.DataFrame]) -> float`: Generates indicator data with ``data`` and computes its `interquartile range (IQR) <https://en.wikipedia.org/wiki/Interquartile_range>`_.
  • Network accessline 1119
    - `unique_dates() -> NDArray[np.datetime64]`: Returns sorted unique dates across every symbol in the store. - `fetch_dict(symbol: str, names: Iterable[str], end_index: Optional[int]=None) -> dict[str, Optional[NDArray]]`: Fetches a ``dict``
  • Network accessline 1120
    - `fetch_dict(symbol: str, names: Iterable[str], end_index: Optional[int]=None) -> dict[str, Optional[NDArray]]`: Fetches a ``dict`` of column data for ``symbol``. - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> Optional[
  • Network accessline 1121
    - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> Optional[NDArray]`: Fetches a :class:`numpy.ndarray` of column data for ``symbol``.
  • Network accessline 1129
    - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> NDArray[np.float64]`: Fetches :class:`pybroker.indicator.Indicator` data.
  • Network accessline 1151
    - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> pd.DataFrame`: Fetches model input data.
  • Network accessline 1158
    - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> NDArray`: Fetches model predictions.
  • Network accessline 1167
    - `fetch_float(symbol: str, price: Union[int, float, np.floating, Decimal, PriceType, Callable[[str, BarData], Union[int, float, Decimal]]]) -> float`: Returns a bar price as ``float`` using the per-bar cache when possible. - `fetch_bar_ohl
  • Network accessline 1169
    - `fetch(symbol: str, price: Union[int, float, np.floating, Decimal, PriceType, Callable[[str, BarData], Union[int, float, Decimal]]]) -> Decimal`
  • Network accessline 1298
    Mixin implementing logic for `Walkforward Analysis <https://www.pybroker.com/en/latest/notebooks/6.%20Training%20a%20Model.html#Walkforward-Analysis>`_.
  • Network accessline 1300
    - `walkforward_split(df: pd.DataFrame, windows: int, lookahead: int, train_size: float=0.9, shuffle: bool=False) -> Iterator[WalkforwardWindow]`: Splits a :class:`pandas.DataFrame` containing data for multiple ticker symbols into an :class:
  • Network accessline 1332
    - `clear_executions()`: Clears executions that were added with :meth:`.add_execution`. - `backtest(start_date: Optional[Union[str, datetime]]=None, end_date: Optional[Union[str, datetime]]=None, timeframe: str='', between_time: Optional[tup
  • Network accessline 1334
    - `walkforward(windows: int, lookahead: int=1, start_date: Optional[Union[str, datetime]]=None, end_date: Optional[Union[str, datetime]]=None, timeframe: str='', between_time: Optional[tuple[str, str]]=None, days: Optional[Union[str, Day, I
  • Network accessline 1383
    Retrieves data from `AKShare <https://akshare.akfamily.xyz/>`_.
  • Network accessline 1388
    Retrieves data from Yahoo Finance using `Yahooquery <https://github.com/dpguthrie/yahooquery>`_\ .

skills/pybroker-rotational-trading/references/pybroker_model.pyi

  • Network accessline 240
    class Alpaca(DataSource):     """Retrieves stock data from `Alpaca <https://alpaca.markets/>`_."""
  • Network accessline 241
    """Retrieves stock data from `Alpaca <https://alpaca.markets/>`_."""
  • Access to secretsline 242
    [Credential-related source omitted]
  • Network accessline 252
    class AlpacaCrypto(DataSource):     """Retrieves crypto data from `Alpaca <https://alpaca.markets/>`_."""
  • Network accessline 253
    """Retrieves crypto data from `Alpaca <https://alpaca.markets/>`_."""
  • Access to secretsline 267
    [Credential-related source omitted]
  • Network accessline 277
    class YFinance(DataSource):     """Retrieves data from `Yahoo Finance <https://finance.yahoo.com/>`_."""
  • Network accessline 278
    """Retrieves data from `Yahoo Finance <https://finance.yahoo.com/>`_."""
  • Network accessline 293
    # --- src/pybroker/ext/data.py --- class AKShare(DataSource):     """Retrieves data from `AKShare <https://akshare.akfamily.xyz/>`_."""
  • Network accessline 295
    """Retrieves data from `AKShare <https://akshare.akfamily.xyz/>`_."""
  • Network accessline 297
    class YQuery(DataSource):     """Retrieves data from Yahoo Finance using `Yahooquery <https://github.com/dpguthrie/yahooquery>`_."""
  • Network accessline 298
    """Retrieves data from Yahoo Finance using `Yahooquery <https://github.com/dpguthrie/yahooquery>`_."""

skills/pybroker-rotational-trading/references/pybroker_types.pyi

  • Network accessline 427
    end_index: Optional[int] = None,     ) -> dict[str, Optional[NDArray]]: ...     def fetch(
  • Network accessline 428
    ) -> dict[str, Optional[NDArray]]: ...     def fetch(         self, symbol: str, name: str, end_index: Optional[int] = None
  • Network accessline 429
    def fetch(
  • Network accessline 440
    """Caches and retrieves :class:`pybroker.indicator.Indicator` data."""     # Constructed by the framework; not user-instantiable.     def fetch(
  • Network accessline 441
    # Constructed by the framework; not user-instantiable.     def fetch(         self, symbol: str, name: str, end_index: Optional[int] = None
  • Network accessline 442
    def fetch(

skills/pybroker-rotational-trading/references/wiki-04-ranking-long-and-short-signals.md

  • Network accessline 39
    To limit the number of long positions that can be held at any time to ```1```, we call [set_max_long_positions](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.set_max_long_positions). This eff
  • Network accessline 48
    **PyBroker** can also rank short signals using [short_score](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.short_score), where short orders are placed for the ticker symbols with the highest
  • Network accessline 77
    [In the next notebook, we will discuss how to implement custom indicators in PyBroker](https://www.pybroker.com/en/latest/notebooks/5.%20Writing%20Indicators.html).

skills/pybroker-rotational-trading/references/wiki-10-rotational-trading.md

  • Network accessline 16
    Our strategy will involve ranking and buying stocks with the highest [price rate-of-change (ROC)](https://www.investopedia.com/terms/p/pricerateofchange.asp). To start, we'll define a 20-day ROC indicator using [TA-Lib](https://github.com/T
  • Network accessline 33
    To implement the strategy, we write a `rotate` function that sets each stock's [long_score](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.long_score) to its 20-day ROC. **PyBroker** then ran
  • Network accessline 40
    Now that we have a method for scoring stocks by their ROC, we can use the [enable_rotation](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.enable_rotation) method to turn on rotational trading
  • Network accessline 42
    We cap long positions at `2` with [set_max_long_positions](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.set_max_long_positions). Setting `worst_rank_held` to `5` liquidates any currently hel
  • Network accessline 73
    **PyBroker** will allocate our capital equally between positions by default. To customize this, we can pass a ``sizer`` function to [enable_rotation](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Stra

skills/pybroker-rotational-trading/references/wiki-18-dynamic-symbol-selection.md

  • Network accessline 11
    **PyBroker v2** now enables dynamic symbol selection with [SymbolSelector](https://www.pybroker.com/en/latest/reference/pybroker.common.html#pybroker.common.SymbolSelector).
  • Network accessline 15
    Below, data is downloaded for twenty liquid large-caps from [YFinance](https://www.pybroker.com/en/latest/reference/pybroker.data.html#pybroker.data.YFinance):
  • Network accessline 56
    Dynamic symbol selection is handled using a [SymbolSelector](https://www.pybroker.com/en/latest/reference/pybroker.common.html#pybroker.common.SymbolSelector), which can be any callable that takes a [Pandas DataFrame](https://pandas.pydata.
  • Network accessline 102
    For each [walkforward](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.walkforward) window, the `top_dollar_volume` selector runs on the train split and selects the top three stocks to trade du

skills/pybroker-strategy-creator/assets/strategy_template.py

  • Executable scriptline 1
    Executable file

skills/pybroker-strategy-creator/references/api-public-surface.md

  • Access to secretsline 367
    [Credential-related source omitted]
  • Network accessline 369
    Retrieves stock data from `Alpaca <https://alpaca.markets/>`_.
  • Access to secretsline 373
    [Credential-related source omitted]
  • Network accessline 375
    Retrieves crypto data from `Alpaca <https://alpaca.markets/>`_.
  • Network accessline 381
    Retrieves data from `Yahoo Finance <https://finance.yahoo.com/>`_\ .
  • Network accessline 383
    - `auto_adjust: bool` - `query(symbols: Union[str, Iterable[str]], start_date: Union[str, datetime], end_date: Union[str, datetime], _timeframe: Optional[str]='', _adjust: Optional[Any]=None) -> pd.DataFrame`: Queries data from `Yahoo Finan
  • Network accessline 384
    - `query(symbols: Union[str, Iterable[str]], start_date: Union[str, datetime], end_date: Union[str, datetime], _timeframe: Optional[str]='', _adjust: Optional[Any]=None) -> pd.DataFrame`: Queries data from `Yahoo Finance <https://finance.ya
  • Network accessline 402
    - `profit_factor(changes: NDArray[np.float64], use_log: bool=False) -> float`: Computes the profit factor, which is the ratio of gross profit to gross loss. - `log_profit_factor(changes: NDArray[np.float64]) -> float`: Computes the log tran
  • Network accessline 403
    - `log_profit_factor(changes: NDArray[np.float64]) -> float`: Computes the log transformed profit factor, which is the ratio of gross profit to gross loss. - `sharpe_ratio(returns: NDArray[np.float64], obs: Optional[int]=None) -> float`: Co
  • Network accessline 404
    - `sharpe_ratio(returns: NDArray[np.float64], obs: Optional[int]=None) -> float`: Computes the `Sharpe Ratio <https://en.wikipedia.org/wiki/Sharpe_ratio>`_, using the population standard deviation of ``returns``.
  • Network accessline 405
    - `downside_deviation(returns: NDArray[np.float64]) -> float`: Computes downside deviation, the denominator of the `Sortino Ratio <https://en.wikipedia.org/wiki/Sortino_ratio>`_.
  • Network accessline 406
    - `sortino_ratio(returns: NDArray[np.float64], obs: Optional[int]=None) -> float`: Computes the `Sortino Ratio <https://en.wikipedia.org/wiki/Sortino_ratio>`_.
  • Network accessline 429
    - `drawdown_conf(changes: NDArray[np.float64], returns: NDArray[np.float64], n_boot: int) -> DrawdownMetrics`: Computes upper bounds of confidence intervals for maximum drawdown using the bootstrap method. - `bootstrap_eval_all(changes: NDA
  • Network accessline 430
    - `bootstrap_eval_all(changes: NDArray[np.float64], returns: NDArray[np.float64], n_boot: int, bars_per_year: int) -> tuple[BootConfIntervals, BootConfIntervals, DrawdownMetrics]`: Computes all bootstrap metrics in one shared resampling pas
  • Network accessline 431
    - `relative_entropy(values: NDArray[np.float64]) -> float`: Computes the relative `entropy <https://en.wikipedia.org/wiki/Entropy_(information_theory)>`_.
  • Network accessline 432
    - `iqr(values: NDArray[np.float64]) -> float`: Computes the `interquartile range (IQR) <https://en.wikipedia.org/wiki/Interquartile_range>`_ of ``values``.
  • Network accessline 433
    - `ulcer_index(values: NDArray[np.float64], period: Optional[int]=None) -> float`: Computes the `Ulcer Index <https://en.wikipedia.org/wiki/Ulcer_index>`_ of ``values``: the root mean square of percentage drawdowns from the running peak.
  • Network accessline 434
    - `upi(values: NDArray[np.float64], period: Optional[int]=None, ui: Optional[float]=None, bars_per_year: Optional[int]=None) -> float`: Computes the `Ulcer Performance Index <https://en.wikipedia.org/wiki/Ulcer_index>`_ of ``values``: retur
  • Network accessline 566
    - `name: str` - `hyperparam_names() -> frozenset[str]` - `relative_entropy(data: Union[BarData, pd.DataFrame]) -> float`: Generates indicator data with ``data`` and computes its relative `entropy <https://en.wikipedia.org/wiki/Entropy_(info
  • Network accessline 567
    - `hyperparam_names() -> frozenset[str]` - `relative_entropy(data: Union[BarData, pd.DataFrame]) -> float`: Generates indicator data with ``data`` and computes its relative `entropy <https://en.wikipedia.org/wiki/Entropy_(information_theory
  • Network accessline 568
    - `relative_entropy(data: Union[BarData, pd.DataFrame]) -> float`: Generates indicator data with ``data`` and computes its relative `entropy <https://en.wikipedia.org/wiki/Entropy_(information_theory)>`_.
  • Network accessline 569
    - `iqr(data: Union[BarData, pd.DataFrame]) -> float`: Generates indicator data with ``data`` and computes its `interquartile range (IQR) <https://en.wikipedia.org/wiki/Interquartile_range>`_.
  • Network accessline 1119
    - `unique_dates() -> NDArray[np.datetime64]`: Returns sorted unique dates across every symbol in the store. - `fetch_dict(symbol: str, names: Iterable[str], end_index: Optional[int]=None) -> dict[str, Optional[NDArray]]`: Fetches a ``dict``
  • Network accessline 1120
    - `fetch_dict(symbol: str, names: Iterable[str], end_index: Optional[int]=None) -> dict[str, Optional[NDArray]]`: Fetches a ``dict`` of column data for ``symbol``. - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> Optional[
  • Network accessline 1121
    - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> Optional[NDArray]`: Fetches a :class:`numpy.ndarray` of column data for ``symbol``.
  • Network accessline 1129
    - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> NDArray[np.float64]`: Fetches :class:`pybroker.indicator.Indicator` data.
  • Network accessline 1151
    - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> pd.DataFrame`: Fetches model input data.
  • Network accessline 1158
    - `fetch(symbol: str, name: str, end_index: Optional[int]=None) -> NDArray`: Fetches model predictions.
  • Network accessline 1167
    - `fetch_float(symbol: str, price: Union[int, float, np.floating, Decimal, PriceType, Callable[[str, BarData], Union[int, float, Decimal]]]) -> float`: Returns a bar price as ``float`` using the per-bar cache when possible. - `fetch_bar_ohl
  • Network accessline 1169
    - `fetch(symbol: str, price: Union[int, float, np.floating, Decimal, PriceType, Callable[[str, BarData], Union[int, float, Decimal]]]) -> Decimal`
  • Network accessline 1298
    Mixin implementing logic for `Walkforward Analysis <https://www.pybroker.com/en/latest/notebooks/6.%20Training%20a%20Model.html#Walkforward-Analysis>`_.
  • Network accessline 1300
    - `walkforward_split(df: pd.DataFrame, windows: int, lookahead: int, train_size: float=0.9, shuffle: bool=False) -> Iterator[WalkforwardWindow]`: Splits a :class:`pandas.DataFrame` containing data for multiple ticker symbols into an :class:
  • Network accessline 1332
    - `clear_executions()`: Clears executions that were added with :meth:`.add_execution`. - `backtest(start_date: Optional[Union[str, datetime]]=None, end_date: Optional[Union[str, datetime]]=None, timeframe: str='', between_time: Optional[tup
  • Network accessline 1334
    - `walkforward(windows: int, lookahead: int=1, start_date: Optional[Union[str, datetime]]=None, end_date: Optional[Union[str, datetime]]=None, timeframe: str='', between_time: Optional[tuple[str, str]]=None, days: Optional[Union[str, Day, I
  • Network accessline 1383
    Retrieves data from `AKShare <https://akshare.akfamily.xyz/>`_.
  • Network accessline 1388
    Retrieves data from Yahoo Finance using `Yahooquery <https://github.com/dpguthrie/yahooquery>`_\ .

skills/pybroker-strategy-creator/references/pybroker_model.pyi

  • Network accessline 240
    class Alpaca(DataSource):     """Retrieves stock data from `Alpaca <https://alpaca.markets/>`_."""
  • Network accessline 241
    """Retrieves stock data from `Alpaca <https://alpaca.markets/>`_."""
  • Access to secretsline 242
    [Credential-related source omitted]
  • Network accessline 252
    class AlpacaCrypto(DataSource):     """Retrieves crypto data from `Alpaca <https://alpaca.markets/>`_."""
  • Network accessline 253
    """Retrieves crypto data from `Alpaca <https://alpaca.markets/>`_."""
  • Access to secretsline 267
    [Credential-related source omitted]
  • Network accessline 277
    class YFinance(DataSource):     """Retrieves data from `Yahoo Finance <https://finance.yahoo.com/>`_."""
  • Network accessline 278
    """Retrieves data from `Yahoo Finance <https://finance.yahoo.com/>`_."""
  • Network accessline 293
    # --- src/pybroker/ext/data.py --- class AKShare(DataSource):     """Retrieves data from `AKShare <https://akshare.akfamily.xyz/>`_."""
  • Network accessline 295
    """Retrieves data from `AKShare <https://akshare.akfamily.xyz/>`_."""
  • Network accessline 297
    class YQuery(DataSource):     """Retrieves data from Yahoo Finance using `Yahooquery <https://github.com/dpguthrie/yahooquery>`_."""
  • Network accessline 298
    """Retrieves data from Yahoo Finance using `Yahooquery <https://github.com/dpguthrie/yahooquery>`_."""

skills/pybroker-strategy-creator/references/pybroker_types.pyi

  • Network accessline 427
    end_index: Optional[int] = None,     ) -> dict[str, Optional[NDArray]]: ...     def fetch(
  • Network accessline 428
    ) -> dict[str, Optional[NDArray]]: ...     def fetch(         self, symbol: str, name: str, end_index: Optional[int] = None
  • Network accessline 429
    def fetch(
  • Network accessline 440
    """Caches and retrieves :class:`pybroker.indicator.Indicator` data."""     # Constructed by the framework; not user-instantiable.     def fetch(
  • Network accessline 441
    # Constructed by the framework; not user-instantiable.     def fetch(         self, symbol: str, name: str, end_index: Optional[int] = None
  • Network accessline 442
    def fetch(

skills/pybroker-strategy-creator/references/wiki-01-getting-started-with-data-sources.md

  • Network accessline 9
    Welcome to **PyBroker**! The best place to start is by learning about the [DataSource](https://www.pybroker.com/en/latest/reference/pybroker.data.html#pybroker.data.DataSource) class. A `DataSource` fetches data from external providers, all
  • Network accessline 13
    One of the built-in data sources in **PyBroker** is [Yahoo Finance](https://finance.yahoo.com). To use it, import [YFinance](https://www.pybroker.com/en/latest/reference/pybroker.data.html#pybroker.data.YFinance):
  • Network accessline 25
    The code above queries data for AAPL and MSFT, returning the results in a [Pandas DataFrame](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html).
  • Network accessline 29
    To speed up data retrieval, you can cache your queries using **PyBroker**'s caching system. Enable caching by calling [pybroker.enable_data_source_cache('name')](https://www.pybroker.com/en/latest/reference/pybroker.cache.html#pybroker.cach
  • Network accessline 37
    The next call to [query](https://www.pybroker.com/en/latest/reference/pybroker.data.html#pybroker.data.DataSource.query) caches the returned data to disk. Each unique combination of ticker symbol and date range is cached separately:
  • Network accessline 50
    You can clear the cache using [pybroker.clear_data_source_cache](https://www.pybroker.com/en/latest/reference/pybroker.cache.html#pybroker.cache.clear_data_source_cache):
  • Network accessline 56
    Or disable caching altogether using [pybroker.disable_data_source_cache](https://www.pybroker.com/en/latest/reference/pybroker.cache.html#pybroker.cache.disable_data_source_cache):
  • Network accessline 62
    Note that these calls should be made after first calling [pybroker.enable_data_source_cache](https://www.pybroker.com/en/latest/reference/pybroker.cache.html#pybroker.cache.enable_data_source_cache).
  • Network accessline 66
    [Credential-related source omitted]
  • Access to secretsline 72
    [Credential-related source omitted]
  • Network accessline 89
    If you are interested in fetching cryptocurrency data, you can use [AlpacaCrypto](https://www.pybroker.com/en/latest/reference/pybroker.data.html#pybroker.data.AlpacaCrypto). Here's an example of how to query hourly data for BTC/USD:
  • Access to secretsline 95
    [Credential-related source omitted]
  • Network accessline 105
    **PyBroker** also supports an [AKShare](https://github.com/akfamily/akshare) ```DataSource``` for fetching **Chinese** stock data. AKShare, a widely-used open-source package, is tailored for obtaining financial data, with a focus on the Chi
  • Network accessline 107
    To use it, run `pip install akshare` and import the [AKShare](https://www.pybroker.com/en/latest/reference/pybroker.ext.data.html#pybroker.ext.data.AKShare) data source included in PyBroker:
  • Network accessline 127
    **NOTE**: If the above causes a  ``Native library not available`` error and you still want to use AKShare, then [see this issue for details on how to resolve it](https://github.com/edtechre/pybroker/issues/36#issuecomment-1605910339).
  • Network accessline 131
    If the built-in data sources do not cover your needs, **PyBroker** lets you implement your own [DataSource](https://www.pybroker.com/en/latest/reference/pybroker.data.html#pybroker.data.DataSource). Examples include CSV files or external AP
  • Network accessline 133
    [In the next notebook, we'll take a look at how to use DataSources to backtest a simple trading strategy](https://www.pybroker.com/en/latest/notebooks/2.%20Backtesting%20a%20Strategy.html).

skills/pybroker-strategy-creator/references/wiki-02-backtesting-a-strategy.md

  • Network accessline 18
    For the backtest, we will use [Yahoo Finance](https://finance.yahoo.com) as our [DataSource](https://www.pybroker.com/en/latest/reference/pybroker.data.html#pybroker.data.DataSource). We will also enable data caching to ensure we only downl
  • Network accessline 20
    First, create a [StrategyConfig](https://www.pybroker.com/en/latest/reference/pybroker.config.html#pybroker.config.StrategyConfig) object to configure the `Strategy`. In this example, we set the initial cash to `500,000`:
  • Network accessline 37
    The `Strategy` instance is now ready to download data from Yahoo Finance for the period between March 1, 2017, and March 1, 2022. To modify other settings, refer to the [StrategyConfig reference documentation](https://www.pybroker.com/en/la
  • Network accessline 66
    The `buy_low` function receives an [ExecContext](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext) (`ctx`) containing historical data for the current ticker (AAPL or MSFT). You can access the m
  • Network accessline 68
    To place an order, calculate the 25% portfolio allocation using [ctx.calc_target_shares](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.calc_target_shares) and assign it to [ctx.buy_shares](h
  • Network accessline 70
    By default, buy orders fill on the following bar (`buy_delay=1`) at the [bar's midpoint price](https://www.pybroker.com/en/latest/reference/pybroker.common.html#pybroker.common.PriceType.MIDDLE). You can customize this behavior using [Strat
  • Network accessline 72
    Next, use [ctx.hold_bars](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.hold_bars) to specify the holding period. Upon liquidation, shares are sold at the [ExecContext.sell_fill_price](https
  • Network accessline 74
    To apply these `buy_low` rules to AAPL and MSFT, use the [add_execution](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.add_execution) method:
  • Network accessline 104
    (Note, you can also retrieve bar data for another symbol by calling [ExecContext#foreign](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.foreign))
  • Network accessline 108
    To run a backtest, call the [backtest](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.backtest) method on the ```Strategy``` instance. Here is an example:
  • Network accessline 114
    The `backtest` method returns a [TestResult](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.TestResult) object containing detailed metrics from your backtest. For instance, you can use [Matplotlib](htt
  • Network accessline 133
    Additionally, `result.metrics_df` provides a DataFrame of metrics calculated from the backtest returns. You can find detailed explanations of these metrics in the [reference documentation](https://www.pybroker.com/en/latest/reference/pybrok
  • Network accessline 150
    You can also filter data by specific time ranges (such as 9:30 to 10:30 AM) using the [between_time](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.backtest) argument.
  • Network accessline 152
    Although the metrics earlier indicate that we have a profitable strategy, we may have been misled by randomness. [In the next notebook, we'll discuss how to use bootstrapping to further evaluate our trading strategies](https://www.pybroker.

skills/pybroker-strategy-creator/references/wiki-03-evaluating-with-bootstrap-metrics.md

  • Network accessline 11
    [In the previous notebook](https://www.pybroker.com/en/latest/notebooks/2.%20Backtesting%20a%20Strategy.html), we implemented and backtested a trading strategy. Here is that implementation again:
  • Network accessline 37
    As before, we create a new [Strategy](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy) instance with the given configurations:
  • Network accessline 53
    While the `total_pnl` metric above suggests a profitable strategy, these results could just be due to chance. To increase confidence in our evaluation, we can use the [bootstrap method](https://en.wikipedia.org/wiki/Bootstrapping_(statistic
  • Network accessline 59
    **PyBroker** applies the bootstrap method to calculate [confidence intervals](https://en.wikipedia.org/wiki/Confidence_interval) for two performance metrics: the [Profit Factor](https://www.pybroker.com/en/latest/reference/pybroker.eval.htm
  • Network accessline 65
    **PyBroker** uses the [bias-corrected and accelerated (BCa) bootstrap method](https://en.wikipedia.org/wiki/Bootstrapping_(statistics)#Bias-corrected_and_accelerated_(BCa)_bootstrap) to calculate confidence intervals for these metrics. Retu
  • Network accessline 83
    [In the next notebook, we will discuss how to incorporate ranking long and short signals in your trading strategies](https://www.pybroker.com/en/latest/notebooks/4.%20Ranking%20Long%20and%20Short%20Signals.html).

skills/pybroker-strategy-creator/references/wiki-04-ranking-long-and-short-signals.md

  • Network accessline 39
    To limit the number of long positions that can be held at any time to ```1```, we call [set_max_long_positions](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.set_max_long_positions). This eff
  • Network accessline 48
    **PyBroker** can also rank short signals using [short_score](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.short_score), where short orders are placed for the ticker symbols with the highest
  • Network accessline 77
    [In the next notebook, we will discuss how to implement custom indicators in PyBroker](https://www.pybroker.com/en/latest/notebooks/5.%20Writing%20Indicators.html).

skills/pybroker-strategy-creator/references/wiki-05-writing-indicators.md

  • Network accessline 9
    This notebook explains how to create and integrate custom stock indicators in **PyBroker**.  Indicators in **PyBroker** are written using [NumPy](https://numpy.org/), a powerful library for numerical computing. To optimize performance, we'l
  • Network accessline 16
    The following code shows an indicator function that calculates close prices minus a moving average (CMMA), which can be used for a [mean reversion](https://en.wikipedia.org/wiki/Mean_reversion_(finance)) strategy:
  • Network accessline 42
    The ```cmma``` function takes two arguments: ```bar_data```, which is an instance of the [BarData](https://www.pybroker.com/en/latest/reference/pybroker.common.html#pybroker.common.BarData) class that holds OHLCV data and custom fields, and
  • Network accessline 44
    The ```vec_cmma``` function is JIT-compiled by Numba and nested inside ```cmma```. This is necessary since a Numba compiled function supports a NumPy array as an argument but not an instance of a Python class like ```BarData```. Note the co
  • Network accessline 54
    Here, we are giving the name ```cmma_20``` to the indicator function and specifying the ```lookback``` parameter as ```20``` bars. Any arguments in the indicator function that come after ```bar_data``` will be passed as user-defined argumen
  • Network accessline 56
    The following is an example of how to use the registered ```Indicator``` in **PyBroker** with some data downloaded from [Yahoo Finance](https://finance.yahoo.com):
  • Network accessline 71
    As you can see, the ```Indicator``` instance is a ```Callable```. Once called, the resulting computed indicator values are returned as a [Pandas Series](https://pandas.pydata.org/docs/reference/api/pandas.Series.html).
  • Network accessline 73
    The ```Indicator``` class also provides functions for measuring its information content. For example, you can compute the [interquartile range (IQR)](https://en.wikipedia.org/wiki/Interquartile_range):
  • Network accessline 79
    Or compute the relative [entropy](https://en.wikipedia.org/wiki/Entropy_(information_theory)):
  • Network accessline 99
    The indicator values are retrieved by calling [ctx.indicator](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.indicator) on the [ExecContext](https://www.pybroker.com/en/latest/reference/pybro
  • Network accessline 108
    Here, the ```buy_cmma_cross``` function is added to the [Strategy](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy) along with the ```cmma_20``` indicator. We can enable caching of the computed
  • Network accessline 121
    **PyBroker** computes indicator values before the backtest runs. By default, these calculations occur serially. See [Configuring Parallelization](https://www.pybroker.com/en/latest/notebooks/11.%20Configuring%20Parallelization.html) for det
  • Network accessline 125
    **PyBroker** provides vectorized helper functions to make the process of computing indicators easier. One of these helper functions is [highv](https://www.pybroker.com/en/latest/reference/pybroker.vect.html#pybroker.vect.highv), which calcu
  • Network accessline 141
    The [pybroker.vect](https://www.pybroker.com/en/latest/reference/pybroker.vect.html) module also includes other vectorized helpers such as [lowv](https://www.pybroker.com/en/latest/reference/pybroker.vect.html#pybroker.vect.lowv), [sumv](ht
  • Network accessline 143
    Additionally, **PyBroker** includes convenient wrappers for [highest](https://www.pybroker.com/en/latest/reference/pybroker.indicator.html#pybroker.indicator.highest) and [lowest](https://www.pybroker.com/en/latest/reference/pybroker.indica
  • Network accessline 154
    Use an [IndicatorSet](https://www.pybroker.com/en/latest/reference/pybroker.indicator.html#pybroker.indicator.IndicatorSet) to calculate multiple indicators. Add the `cmma_20` and `hhv_5` indicators to the `IndicatorSet` to compute them tog
  • Network accessline 166
    [TA-Lib](https://github.com/TA-Lib/ta-lib-python) is a widely used technical analysis library that implements many financial indicators. You can install it with `pip install ta-lib`.
  • Network accessline 181
    **PyBroker** also includes built-in indicators that are available in the [indicator module](https://www.pybroker.com/en/latest/reference/pybroker.indicator.html). **PyBroker** reimplements these standard indicators with volatility normaliza
  • Network accessline 183
    [In the next tutorial, you will learn how to train a model using custom indicators in PyBroker](https://www.pybroker.com/en/latest/notebooks/6.%20Training%20a%20Model.html).

skills/pybroker-strategy-creator/references/wiki-06-training-a-model.md

  • Network accessline 9
    In the [last notebook](https://www.pybroker.com/en/latest/notebooks/5.%20Writing%20Indicators.html), we learned how to write stock indicators in **PyBroker**. Indicators are a good starting point for developing a trading strategy. But to cr
  • Network accessline 11
    One of the main features of **PyBroker** is the ability to train and backtest machine learning models. These models can utilize indicators as features to make more accurate predictions about market movements. Once trained, these models can 
  • Network accessline 22
    As with [DataSource](https://www.pybroker.com/en/latest/reference/pybroker.data.html#pybroker.data.DataSource) and [Indicator](https://www.pybroker.com/en/latest/reference/pybroker.indicator.html#pybroker.indicator.Indicator) data, **PyBrok
  • Network accessline 28
    In [the last notebook](https://www.pybroker.com/en/latest/notebooks/5.%20Writing%20Indicators.html), we implemented an indicator that calculates the close-minus-moving-average (CMMA) using [NumPy](https://www.numpy.org) and [Numba](https://
  • Network accessline 59
    Next, we want to build a model that predicts the next day's return using the 20-day CMMA. Using [simple linear regression](https://en.wikipedia.org/wiki/Simple_linear_regression) is a good approach to begin experimenting with as a baseline 
  • Network accessline 61
    Below we import a [LinearRegression](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html) model from [scikit-learn](https://scikit-learn.org/stable/):
  • Network accessline 110
    After fitting the model, the function uses the testing data to evaluate the model's accuracy, specifically by computing the [R-squared](https://en.wikipedia.org/wiki/Coefficient_of_determination) score. The R-squared score provides a measur
  • Network accessline 114
    Once the function to train the model has been defined, it needs to be registered with **PyBroker**. This is done by creating a new [ModelSource](https://www.pybroker.com/en/latest/reference/pybroker.model.html#pybroker.model.ModelSource)  i
  • Network accessline 120
    To create a trading strategy that uses the trained model, create a new [Strategy](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy) object using the [YFinance](https://www.pybroker.com/en/latest
  • Network accessline 128
    The [add_execution](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.add_execution) method is then called on the [Strategy](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#py
  • Network accessline 130
    The last step is to run the backtest by calling the [backtest](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.backtest) method on the `Strategy` object. Set the `train_size` to `0.5` to specif
  • Network accessline 139
    **PyBroker** employs a powerful algorithm known as [Walkforward Analysis](https://www.youtube.com/watch?v=WBZ_Vv-iMv4) to perform backtesting. The algorithm partitions the backtest data into a fixed number of time windows, each containing a
  • Network accessline 145
    ![Walkforward Diagram](https://github.com/edtechre/pybroker/blob/master/docs/_static/walkforward.gif?raw=true)
  • Network accessline 149
    Let's consider a trading strategy that generates buy and sell signals from the [LinearRegression](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html) model that we trained earlier. The strategy is i
  • Network accessline 169
    The [ctx.preds('slr')](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.preds) method is used to access the predictions made by the ```'slr'``` model for the current stock symbol being executed
  • Network accessline 173
    Run the backtest by calling the [walkforward](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.walkforward) method on the `Strategy` object, passing the desired number of time windows and the tr
  • Network accessline 203
    Beyond linear regression, **PyBroker** can train other model types such as gradient boosted machines, neural networks, or any other architecture that we choose. To help support these models, **PyBroker** offers extensive customization optio
  • Network accessline 205
    Additionally, **PyBroker v2** now supports training [time series models](https://www.pybroker.com/en/latest/notebooks/16.%20Time%20Series%20Models.html) and [multi-symbol models](https://www.pybroker.com/en/latest/notebooks/17.%20Multi-Symb

skills/pybroker-strategy-creator/references/wiki-07-creating-a-custom-data-source.md

  • Network accessline 9
    **PyBroker** comes with pre-built [DataSources](https://www.pybroker.com/en/latest/reference/pybroker.data.html#pybroker.data.DataSource) for [Yahoo Finance](https://www.pybroker.com/en/latest/reference/pybroker.data.html#pybroker.data.YFin
  • Network accessline 13
    The following example implements a custom `CSVDataSource` to load data from a CSV file. It reads a file named `prices.csv` into a [Pandas DataFrame](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html):
  • Network accessline 34
    To make the custom `'rsi'` column from the CSV file available to **PyBroker**, register it using [pybroker.register_columns](https://www.pybroker.com/en/latest/reference/pybroker.scope.html#pybroker.scope.register_columns). This allows **Py
  • Network accessline 46
    To use ```CSVDataSource``` in a backtest, we create a new [Strategy](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy) object and pass it the custom ```DataSource```:
  • Network accessline 66
    Because we registered the custom `rsi` column with **PyBroker**, it can be accessed in the [ExecContext](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext) using `ctx.rsi`.
  • Network accessline 70
    If you do not need the flexibility of implementing your own [DataSource](https://www.pybroker.com/en/latest/reference/pybroker.data.html#pybroker.data.DataSource), you can pass a [Pandas DataFrame](https://pandas.pydata.org/docs/reference/a

skills/pybroker-strategy-creator/references/wiki-08-applying-stops.md

  • Network accessline 118
    To set a custom exit price, you can use the `exit_price` fields available for each stop type. When configured, **PyBroker** checks the stop against the `exit_price` and uses that price for the exit when triggered. The following code sets [s
  • Network accessline 137
    For more details on the attributes available for configuring stops, see the [ExecContext reference documentation](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext).

skills/pybroker-strategy-creator/references/wiki-09-rebalancing-positions.md

  • Network accessline 9
    **PyBroker** allows you to simulate portfolio rebalancing by adjusting your asset allocation to match a desired target. This notebook also demonstrates how to rebalance using [portfolio optimization](https://en.wikipedia.org/wiki/Portfolio_
  • Network accessline 43
    With the `rebalance` function complete, we can backtest our strategy using a portfolio of five stocks. To process all stocks simultaneously on each bar of data, we use the [Strategy.set_after_exec](https://www.pybroker.com/en/latest/referen
  • Network accessline 60
    [Portfolio optimization](https://en.wikipedia.org/wiki/Portfolio_optimization) guides rebalancing to meet specific objectives, such as allocating stocks to minimize risk.
  • Network accessline 62
    [Riskfolio-Lib](https://riskfolio-lib.readthedocs.io/) is a popular Python library for portfolio optimization. You can install it using `pip install riskfolio-lib`.
  • Network accessline 64
    The following example demonstrates how to construct a minimum risk portfolio by minimizing the [Conditional Value at Risk (CVaR)](https://www.investopedia.com/terms/c/conditional_value_at_risk.asp) based on the past year of returns:
  • Network accessline 100
    For more information and examples, see the [official Riskfolio-Lib documentation](https://riskfolio-lib.readthedocs.io/). Next, we backtest the strategy:

skills/pybroker-strategy-creator/references/wiki-10-rotational-trading.md

  • Network accessline 16
    Our strategy will involve ranking and buying stocks with the highest [price rate-of-change (ROC)](https://www.investopedia.com/terms/p/pricerateofchange.asp). To start, we'll define a 20-day ROC indicator using [TA-Lib](https://github.com/T
  • Network accessline 33
    To implement the strategy, we write a `rotate` function that sets each stock's [long_score](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.long_score) to its 20-day ROC. **PyBroker** then ran
  • Network accessline 40
    Now that we have a method for scoring stocks by their ROC, we can use the [enable_rotation](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.enable_rotation) method to turn on rotational trading
  • Network accessline 42
    We cap long positions at `2` with [set_max_long_positions](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.set_max_long_positions). Setting `worst_rank_held` to `5` liquidates any currently hel
  • Network accessline 73
    **PyBroker** will allocate our capital equally between positions by default. To customize this, we can pass a ``sizer`` function to [enable_rotation](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Stra

skills/pybroker-strategy-creator/references/wiki-11-configuring-parallelization.md

  • Network accessline 9
    **PyBroker** uses [Joblib](https://joblib.readthedocs.io/) to compute indicators, train models, and optimize parameters in parallel.
  • Network accessline 13
    [set_parallel](https://www.pybroker.com/en/latest/reference/pybroker.parallel.html#pybroker.parallel.set_parallel) updates the global Joblib configuration. The [n_jobs](https://www.pybroker.com/en/latest/reference/pybroker.parallel.html#pyb
  • Network accessline 29
    Indicators are computed **per symbol**: all indicators for a given symbol are grouped into a single task, and one task is dispatched per symbol. Passing `parallel_indicators=True` to [backtest](https://www.pybroker.com/en/latest/reference/p
  • Network accessline 68
    Standalone indicator computation with an [IndicatorSet](https://www.pybroker.com/en/latest/reference/pybroker.indicator.html#pybroker.indicator.IndicatorSet) accepts the same `parallel_indicators` flag:
  • Network accessline 83
    Model training runs serially by default. Passing `parallel_models=True` to [backtest](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.backtest) or [walkforward](https://www.pybroker.com/en/late
  • Network accessline 85
    This example adapts the linear regression model from [Training a Model](https://www.pybroker.com/en/latest/notebooks/6.%20Training%20a%20Model.html):
  • Network accessline 132
    [Ray](https://www.ray.io/) can distribute the same work across many cores or an entire cluster. Install it with `pip install ray` and then register it with Joblib via [register_ray](https://docs.ray.io/en/latest/ray-more-libs/joblib.html) (
  • Network accessline 142
    After registering Ray, pass `backend="ray"` to [set_parallel](https://www.pybroker.com/en/latest/reference/pybroker.parallel.html#pybroker.parallel.set_parallel) to make it available as a backend:
  • Network accessline 149
    **PyBroker** will now use the Ray backend for all parallel tasks. For example, calling [backtest](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.backtest) with `parallel_indicators=True`:
  • Network accessline 158
    We will explore [parameter optimization](https://www.pybroker.com/en/latest/notebooks/12.%20Parameter%20Optimization.html) in the next notebook, which can also be parallelized in certain scenarios.

skills/pybroker-strategy-creator/references/wiki-12-parameter-optimization.md

  • Network accessline 9
    **PyBroker v2** supports parameterized strategies. This allows you to backtest strategies using different combinations of parameters and automatically select the best performers. This process is known as **parameter optimization** and is ha
  • Network accessline 15
    A hyperparameter is a named, tunable value created with [hyperparam](https://www.pybroker.com/en/latest/reference/pybroker.optimize.html#pybroker.optimize.hyperparam). Each one has a [default](https://www.pybroker.com/en/latest/reference/py
  • Network accessline 19
    - **Indicators**: pass it as a keyword argument to [indicator](https://www.pybroker.com/en/latest/reference/pybroker.indicator.html#pybroker.indicator.indicator).
  • Network accessline 20
    - **Executions**: attach it with `hyperparams=` on [add_execution](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.add_execution) and read it with [ctx.hyperparam](https://www.pybroker.com/en/l
  • Network accessline 71
    The [optimize](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.optimize) method splits the data into train and test windows as specified by `train_size` (`0.5` for 50/50 by default). As Optuna 
  • Network accessline 86
    [best_params](https://www.pybroker.com/en/latest/reference/pybroker.optimize.html#pybroker.optimize.OptimizeResult.best_params) holds the best in-sample values, and [best_score](https://www.pybroker.com/en/latest/reference/pybroker.optimize
  • Network accessline 88
    Using the optimized parameters, we're able to see an improvment to the total return from before. The [result](https://www.pybroker.com/en/latest/reference/pybroker.optimize.html#pybroker.optimize.OptimizeResult.result) attribute contains th
  • Network accessline 96
    Grid search grows multiplicatively with each added hyperparameter. An alternative approach is using `sampler="tpe"`. Optuna's [TPESampler](https://optuna.readthedocs.io/en/stable/reference/samplers/generated/optuna.samplers.TPESampler.html)
  • Network accessline 111
    `sampler="random"` chooses combinations uniformly at random with Optuna's [RandomSampler](https://optuna.readthedocs.io/en/stable/reference/samplers/generated/optuna.samplers.RandomSampler.html). Like grid, random trials can be evaluated in
  • Network accessline 118
    Any [optuna.samplers.BaseSampler](https://optuna.readthedocs.io/en/stable/reference/samplers/index.html) instance can also be passed directly to [optimize](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strateg
  • Network accessline 131
    Every optimization also returns the underlying [optuna.Study](https://optuna.readthedocs.io/en/stable/reference/generated/optuna.study.Study.html) for inspecting the trials:
  • Network accessline 139
    Finally, [optimize](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.optimize) supports walkforward optimization. If you pass `> 1` to the `windows` parameter, PyBroker will independently tune t
  • Network accessline 154
    Each window is tuned separately, so the best parameters can differ between windows. The combined result contains the [best_params](https://www.pybroker.com/en/latest/reference/pybroker.optimize.html#pybroker.optimize.OptimizeResult.best_par

skills/pybroker-strategy-creator/references/wiki-13-margin-trading.md

  • Network accessline 9
    Until now, our backtests have been limited to cash-only trades. This notebook explores the margin trading features in **PyBroker v2**. We'll use [StrategyConfig](https://www.pybroker.com/en/latest/reference/pybroker.config.html#pybroker.con
  • Network accessline 20
    Margin is enabled with the [leverage](https://www.pybroker.com/en/latest/reference/pybroker.config.html#pybroker.config.StrategyConfig.leverage) config option, which multiplies buying power for both long and short positions.
  • Network accessline 42
    Position sizing is where leverage comes into play. The [ctx.calc_target_shares](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.calc_target_shares) method sizes orders as a fraction of your de
  • Network accessline 58
    [result.portfolio](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.TestResult.portfolio) records the margin balances on every bar. When a levered position is opened, a portion of cash (`entry cost / lev
  • Network accessline 60
    The [margin](https://www.pybroker.com/en/latest/reference/pybroker.portfolio.html#pybroker.portfolio.PortfolioBar.margin) column is separate and tracks the current value of open short positions, so it stays at zero when the strategy is long
  • Network accessline 69
    On the first of these filtered bars, a single entry filled. Cash dropped by `$25,413` to post half of the entry cost as collateral, while the `margin_loan` column records the borrowed remainder. While the collateral and margin loan are fixe
  • Network accessline 73
    To see the effect of leverage on our strategy, we rerun the strategy with a cash only [leverage](https://www.pybroker.com/en/latest/reference/pybroker.config.html#pybroker.config.StrategyConfig.leverage) of `1.0`. We also disable PyBroker's
  • Network accessline 98
    Leverage more than doubled the return (and nearly doubled the max drawdown), but borrowing is not free. You can simulate this financing cost using the [interest_rate](https://www.pybroker.com/en/latest/reference/pybroker.config.html#pybroke
  • Network accessline 126
    Looking at the tail of the portfolio, `cash` will stay zero. Meanwhile, the accrued interest is added to the [margin_loan](https://www.pybroker.com/en/latest/reference/pybroker.portfolio.html#pybroker.portfolio.PortfolioBar.margin_loan) and
  • Network accessline 138
    To demonstrate this, we will short symbols trading below their moving average. We will also enable [record_position_bars](https://www.pybroker.com/en/latest/reference/pybroker.config.html#pybroker.config.StrategyConfig.record_position_bars)
  • Network accessline 168
    For open short positions, the [margin](https://www.pybroker.com/en/latest/reference/pybroker.portfolio.html#pybroker.portfolio.PortfolioBar.margin) column tracks their current notional exposure, which can exceed your total equity when using
  • Network accessline 170
    When you open a short, collateral equal to `entry cost / leverage` is held from your cash, and the [margin_loan](https://www.pybroker.com/en/latest/reference/pybroker.portfolio.html#pybroker.portfolio.PortfolioBar.margin_loan) column record
  • Network accessline 172
    Your [net_cash_balance](https://www.pybroker.com/en/latest/reference/pybroker.portfolio.html#pybroker.portfolio.PortfolioBar.net_cash_balance) equals your remaining cash minus this margin loan, turning negative if the loan exceeds your avai
  • Network accessline 174
    Because we enabled [record_position_bars](https://www.pybroker.com/en/latest/reference/pybroker.config.html#pybroker.config.StrategyConfig.record_position_bars), [result.positions](https://www.pybroker.com/en/latest/reference/pybroker.strat

skills/pybroker-strategy-creator/references/wiki-14-modeling-slippage.md

  • Network accessline 11
    This notebook demonstrates **PyBroker's** three built-in slippage models added in v2. It also introduces the [SlippageModel](https://www.pybroker.com/en/latest/reference/pybroker.slippage.html#pybroker.slippage.SlippageModel) base class, wh
  • Network accessline 15
    To see the effect of each model, we reuse the dip-buying strategy from [Backtesting a Strategy](https://www.pybroker.com/en/latest/notebooks/2.%20Backtesting%20a%20Strategy.html). The rule is simple: buy when the latest close drops below th
  • Network accessline 43
    Now, we run the baseline backtest with no slippage. Every order fills at the the midpoint between the bar's low and high prices ([PriceType.MIDDLE](https://www.pybroker.com/en/latest/reference/pybroker.common.html#pybroker.common.PriceType.
  • Network accessline 53
    The [FixedSlippageModel](https://www.pybroker.com/en/latest/reference/pybroker.slippage.html#pybroker.slippage.FixedSlippageModel) applies a fixed, adverse price adjustment measured in basis points (where 1 basis point equals 0.01%). Buy pr
  • Network accessline 55
    Because the remaining examples run several more backtests, we will also disable logging with [disable_logging](https://www.pybroker.com/en/latest/reference/pybroker.scope.html#pybroker.scope.disable_logging) to keep the output short. Next, 
  • Network accessline 70
    Because slippage tends to grow as volatility rises, the [VolatilitySlippageModel](https://www.pybroker.com/en/latest/reference/pybroker.slippage.html#pybroker.slippage.VolatilitySlippageModel) ties its adverse price adjustment directly to m
  • Network accessline 83
    The [VolumeSlippageModel](https://www.pybroker.com/en/latest/reference/pybroker.slippage.html#pybroker.slippage.VolumeSlippageModel) accounts for limited market liquidity by applying two mechanics:
  • Network accessline 108
    To create your own model, subclass [SlippageModel](https://www.pybroker.com/en/latest/reference/pybroker.slippage.html#pybroker.slippage.SlippageModel) and override the [apply_slippage](https://www.pybroker.com/en/latest/reference/pybroker.

skills/pybroker-strategy-creator/references/wiki-15-multiple-time-intervals.md

  • Network accessline 27
    Your chosen interval must always be longer than the bars being compressed. For example, if you fetch daily bars from [YFinance](https://www.pybroker.com/en/latest/reference/pybroker.data.html#pybroker.data.YFinance), then `"weekly"` and `"m
  • Network accessline 46
    The [compress_bars](https://www.pybroker.com/en/latest/reference/pybroker.interval.html#pybroker.interval.compress_bars) function converts OHLCV data (either a [Pandas DataFrame](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame
  • Network accessline 52
    *   **Volume:** The sum of the volumes. *   **VWAP:** The volume-weighted average. *   **Custom columns:** The last value in the period (e.g., [YFinance](https://www.pybroker.com/en/latest/reference/pybroker.data.html#pybroker.data.YFinance
  • Network accessline 54
    *   **Custom columns:** The last value in the period (e.g., [YFinance](https://www.pybroker.com/en/latest/reference/pybroker.data.html#pybroker.data.YFinance)'s `adj_close`).
  • Network accessline 58
    Let's compress AMD into calendar weeks and view the result as a [Pandas DataFrame](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html) with [bars_to_df](https://www.pybroker.com/en/latest/reference/pybroker.common.html#pybro
  • Network accessline 77
    To use higher timeframes in your backtest, pass the `intervals` parameter to [add_execution](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.add_execution). Your execution function can then acc
  • Network accessline 81
    To prevent look-ahead bias, [ctx.interval](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.interval) only ever exposes *completed* bars. For example, the week or month that is currently formin
  • Network accessline 117
    To compute an indicator on compressed bars, bind it to one or more intervals with [Indicator.intervals(...)](https://www.pybroker.com/en/latest/reference/pybroker.indicator.html#pybroker.indicator.Indicator.intervals).
  • Network accessline 152
    **PyBroker** automatically combines bound intervals with those in the execution's `intervals` parameter. Here, the `"weekly"` interval is made accessible via [ctx.interval("weekly")](https://www.pybroker.com/en/latest/reference/pybroker.con
  • Network accessline 154
    Note that the binding will override also computing the indicator on the base timeframe of the data source. To also compute the indicator on the base timeframe of the data source, pass `"base"` to [Indicator.intervals()](https://www.pybroker
  • Network accessline 163
    You can bind models in the same way with [ModelSource.intervals(...)](https://www.pybroker.com/en/latest/reference/pybroker.model.html#pybroker.model.ModelSource.intervals). **PyBroker** will then train models for each interval using the in
  • Network accessline 165
    This example trains a [LinearRegression](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html) model to predict the next weekly return from the weekly close:
  • Network accessline 202
    During [Walkforward Analysis](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.walkforward), the `lookahead` between an interval model's train and test data is enforced using the compressed bar 

skills/pybroker-strategy-creator/references/wiki-16-time-series-models.md

  • Network accessline 11
    To show how this works, we will backtest two different strategies. The first relies on a volatility forecast from a [GARCH(1,1)](https://en.wikipedia.org/wiki/Autoregressive_conditional_heteroskedasticity) model built with the [arch](https:
  • Network accessline 25
    GARCH will model the volatility of a return series, so we start by defining an [indicator](https://www.pybroker.com/en/latest/reference/pybroker.indicator.html#pybroker.indicator.indicator) for log returns:
  • Network accessline 72
    By default, **PyBroker** passes all test window data to the model in a single call to make a make a prediction. While this vectorized approach is efficient, it fails for autoregressive models since they rely on the previous step's output to
  • Network accessline 84
    The strategy then uses the volatility forecast from [ctx.preds](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.preds) as a regime filter. It enters a long position when forecast volatility is
  • Network accessline 109
    The second strategy trains a [RandomForestRegressor](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html) to predict the next bar's return from lagged returns:
  • Network accessline 123
    The training function receives `lag_train` and `lag_test` parameters built from configuring the model with the desired number of [lags](https://www.pybroker.com/en/latest/reference/pybroker.model.html#pybroker.model.model). Each parameter i
  • Network accessline 132
    Registering the model with [lags](https://www.pybroker.com/en/latest/reference/pybroker.model.html#pybroker.model.model) set to `3` will include the past three lagged values for each column declared in [lag_cols](https://www.pybroker.com/en
  • Network accessline 144
    The strategy buys when [ctx.preds](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.preds) for the next-bar return is positive and exits when it is negative. We then run a [walkforward](https:/

skills/pybroker-strategy-creator/references/wiki-17-multi-symbol-models.md

  • Network accessline 11
    **PyBroker v2** supports training one model across all symbols passed to [Strategy.add_execution](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.add_execution), as shown in this notebook.
  • Network accessline 23
    This notebook repurposes the linear regression example from [Training a Model](https://www.pybroker.com/en/latest/notebooks/6.%20Training%20a%20Model.html). Below, one shared [LinearRegression](https://scikit-learn.org/stable/modules/genera

skills/pybroker-strategy-creator/references/wiki-18-dynamic-symbol-selection.md

  • Network accessline 11
    **PyBroker v2** now enables dynamic symbol selection with [SymbolSelector](https://www.pybroker.com/en/latest/reference/pybroker.common.html#pybroker.common.SymbolSelector).
  • Network accessline 15
    Below, data is downloaded for twenty liquid large-caps from [YFinance](https://www.pybroker.com/en/latest/reference/pybroker.data.html#pybroker.data.YFinance):
  • Network accessline 56
    Dynamic symbol selection is handled using a [SymbolSelector](https://www.pybroker.com/en/latest/reference/pybroker.common.html#pybroker.common.SymbolSelector), which can be any callable that takes a [Pandas DataFrame](https://pandas.pydata.
  • Network accessline 102
    For each [walkforward](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.walkforward) window, the `top_dollar_volume` selector runs on the train split and selects the top three stocks to trade du

skills/pybroker-strategy-creator/references/wiki-faqs.md

  • Network accessline 21
    Use [ctx.foreign](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.foreign) and pass a symbol to [ctx.indicator](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.cont
  • Network accessline 42
    You can also retrieve models, predictions, and other data for other symbols. [For more information, refer to the ExecContext reference documentation.](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecC
  • Network accessline 46
    Set [buy_limit_price](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.buy_limit_price) or [sell_limit_price](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context
  • Network accessline 67
    Set [buy_fill_price](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.buy_fill_price) and [sell_fill_price](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.E
  • Network accessline 90
    Use [positions](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.positions), [long_positions](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.lon
  • Network accessline 117
    [See the Position class for more information.](https://www.pybroker.com/en/latest/reference/pybroker.portfolio.html#pybroker.portfolio.Position)
  • Network accessline 121
    Register your custom columns with [pybroker.register_columns](https://www.pybroker.com/en/latest/reference/pybroker.scope.html#pybroker.scope.register_columns):
  • Network accessline 147
    Use the [buy_delay](https://www.pybroker.com/en/latest/reference/pybroker.config.html#pybroker.config.StrategyConfig.buy_delay) and [sell_delay](https://www.pybroker.com/en/latest/reference/pybroker.config.html#pybroker.config.StrategyConfi
  • Network accessline 170
    See the [cancel_pending_order](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.cancel_pending_order) and [cancel_all_pending_orders](https://www.pybroker.com/en/latest/reference/pybroker.conte
  • Network accessline 196
    Use the [ctx.session](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.session) dictionary:
  • Network accessline 217
    Use [sell_all_shares](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.sell_all_shares) or [cover_all_shares](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context
  • Network accessline 239
    Use [set_before_exec](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.Strategy.set_before_exec) or [set_after_exec](https://www.pybroker.com/en/latest/reference/pybroker.strategy.html#pybroker.strategy.
  • Network accessline 266
    Set the [bars_per_year](https://www.pybroker.com/en/latest/reference/pybroker.config.html#pybroker.config.StrategyConfig.bars_per_year) configuration option. For example, setting a value of ``252`` would be used to annualize daily returns.
  • Network accessline 291
    Use [param](https://www.pybroker.com/en/latest/reference/pybroker.scope.html#pybroker.scope.param) for global values shared across a session. For tunable strategy parameters used with [optimize](https://www.pybroker.com/en/latest/reference/
  • Network accessline 305
    [set_target_shares](https://www.pybroker.com/en/latest/reference/pybroker.context.html#pybroker.context.ExecContext.set_target_shares) will buy and sell enough shares to approximate a target allocation:
  • Network accessline 334
    Set [record_position_bars](https://www.pybroker.com/en/latest/reference/pybroker.config.html#pybroker.config.StrategyConfig.record_position_bars) to capture per-bar position snapshots in [result.positions](https://www.pybroker.com/en/latest

How the signals fit together

Facts from a static read of the files at the pinned commit. They describe what the code does, not why.

Some files could not be read; the facts below still hold.

Signal confidence: 500 facts

and 450 more

Only the first 500 facts are listed.

Works with

Agent compatibility, from the files in this repository
AgentStatusEvidenceInstall to
Claude CodeNativePath .claude/skills/dependency-migration-triage/SKILL.md.claude/skills/<skill-name>/
CodexCompatibleStandard SKILL.md skills/pybroker-indicator-creator/SKILL.md.agents/skills/<skill-name>/
CursorCompatibleStandard SKILL.md skills/pybroker-indicator-creator/SKILL.md.cursor/skills/<skill-name>/
Gemini CLICompatibleStandard SKILL.md skills/pybroker-indicator-creator/SKILL.md.gemini/skills/<skill-name>/
GitHub CopilotCompatibleStandard SKILL.md skills/pybroker-indicator-creator/SKILL.md.github/skills/<skill-name>/
OpenCodeCompatibleStandard SKILL.md skills/pybroker-indicator-creator/SKILL.md.opencode/skills/<skill-name>/
  • Native The repository ships a manifest, folder or frontmatter field for this agent.
  • Compatible A standard SKILL.md that this agent can read.
  • Unknown No evidence either way.

Derived automatically from paths, manifests and frontmatter. Not tested on each agent.

Add this badge to your README

It updates every night and links to this page.

edtechre/pybroker: #345 on hotskills, 3.7k stars

[![edtechre/pybroker on hotskills](https://hotskills.dev/badge/edtechre-pybroker.svg)](https://hotskills.dev/skill/edtechre-pybroker/)