Calculus & Technical Indicators
Relevant source files
The following files were used as context for generating this wiki page:
The Calculus and Technical Indicators module provides the mathematical foundation for quantitative research within the hyperdrive library. It encompasses low-level mathematical operations (Calculus) and higher-level strategy generation tools (History) used to analyze market data, identify trends, and produce trading signals.
The system is designed to transform raw OHLC (Open, High, Low, Close) and alternative data into actionable insights through statistical smoothing, differentiation, and signal processing. These components are primarily consumed by the Historian and various update scripts to generate portfolio previews and backtest results.
Sources: README.md:14-17, hyperdrive/Calculus.py, hyperdrive/History.py
Mathematical Foundations: The Calculator
The Calculator class provides fundamental mathematical utilities used throughout the library for data transformation and series analysis.
Core Mathematical Functions
| Function | Description |
|---|---|
delta | Calculates the percentage change between consecutive elements in a series. |
roll | Computes a rolling mean for a given window size. |
smooth | Applies a Savitzky-Golay filter to smooth data without significantly distorting the signal. |
derive | Calculates the rate of change (derivative) of a series. |
cv | Calculates the Coefficient of Variation (standard deviation divided by the mean). |
fib | Generates a Fibonacci sequence of a specified length. |
Sources: hyperdrive/Calculus.py, test/test_Calculus.py:10-45
Data Flow for Signal Processing
The following diagram illustrates how raw market data is processed through the Calculus module to produce signals.
This flow ensures that noise is reduced before derivatives are taken, leading to more stable signal generation.
Sources: hyperdrive/Calculus.py, hyperdrive/History.py:33-40
Quantitative Indicators and Signal Generation
The Historian class utilizes the Calculator to generate technical indicators and optimal trading signals. It bridges the gap between raw calculus and portfolio backtesting.
Signal Detection Logic
The system identifies "optimal" signals by locating local extrema (minima and maxima) within a price series. This process is used to establish a benchmark for machine learning models or random strategy comparisons.
- Local Minima: Identified as "True" (Buy) signals.
- Local Maxima: Identified as "False" (Sell) signals.
- Signal Filling: Uses forward-fill (
ffill) or nearest-neighbor interpolation to maintain continuous state between detected points.
def get_optimal_signals(self, close, n=10, method='ffill'):
close = np.array(close)
mins = argrelextrema(close, np.less_equal, order=n)[0]
maxs = argrelextrema(close, np.greater_equal, order=n)[0]
signals = np.empty_like(close, dtype='object')
signals[:] = np.nan
signals[mins] = True
signals[maxs] = False
return self.fill(signals, method=method)
Sources: hyperdrive/History.py:59-73, test/test_History.py:48-52
External Indicators
Hyperdrive integrates specific technical indicators from external data providers like Glassnode, which are standardized for use in models.
| Indicator | Source | Description |
|---|---|---|
| S2F Ratio | Glassnode | Stock-to-Flow ratio and days until halving. |
| Difficulty Ribbon | Glassnode | Moving averages of Bitcoin mining difficulty (MA9 to MA200). |
| SOPR | Glassnode | Spent Output Profit Ratio. |
| Sentiment | StockTwits | Bullish and bearish social volume scores. |
Sources: hyperdrive/DataSource.py:270-365, test/test_DataSource.py:110-150
Portfolio Analysis and Metrics
Once signals are generated, the library uses vectorbt to calculate performance metrics.
Performance Metrics Table
The library tracks the following metrics to evaluate the effectiveness of indicators and signals:
| Metric | Context | Description |
|---|---|---|
Total Return [%] | Portfolio | Total percentage gain or loss. |
Max Drawdown [%] | Risk | Maximum observed loss from a peak. |
Sharpe Ratio | Risk-Adjusted | Reward per unit of risk (volatility). |
Sortino Ratio | Risk-Adjusted | Focuses on downside volatility. |
Profit Factor | Performance | Gross profit divided by gross loss. |
Win Rate [%] | Strategy | Percentage of profitable trades. |
Sources: scripts/update_api.py:30-45, README.md:73-85
Relationship Diagram: Indicators to Portfolio
The relationship between the mathematical calculations and the final portfolio evaluation is shown below:
Statistical Preprocessing
For advanced analysis, the Historian class provides methods to prepare indicator data for machine learning models.
- Undersampling: Balances datasets by matching the number of "Buy" and "Sell" signals to prevent model bias.
- Standardization: Uses
StandardScalerto normalize feature scales. - PCA (Principal Component Analysis): Reduces the dimensionality of indicator sets while retaining a target explained variance.
Sources: hyperdrive/History.py:101-160, test/test_History.py:58-60
Summary
The Calculus & Technical Indicators module serves as the quantitative engine for hyperdrive. It transforms raw financial data into smoothed series and derivatives via the Calculator class, which are then converted into trading signals by the Historian. By combining local extrema detection with external data like Glassnode's Difficulty Ribbon, the system provides a robust framework for backtesting and evaluating algorithmic trading strategies through standardized performance metrics.
Sources: README.md:14-20, hyperdrive/History.py, scripts/update_api.py