# Time Cycle Forecaster & Market Harmonics Analytics (`khnaami/time-cycle-forecaster-market-harmonics-analytics`) Actor

Detects multi-year macro market cycles (18Y Stock, 16Y Commodity, 4Y Halving, 8Y FX), FFT spectral harmonics, historical analog fractal projections, and SARIMA turning points across multi-asset classes.

- **URL**: https://apify.com/khnaami/time-cycle-forecaster-market-harmonics-analytics.md
- **Developed by:** [khalid naami](https://apify.com/khnaami) (community)
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per usage

This Actor is paid per platform usage. The Actor is free to use, and you only pay for the Apify platform usage, which gets cheaper the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-usage

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Time Cycle Forecaster & Market Harmonics 🔄📈

**Time Cycle Forecaster** is an institutional quantitative Apify Actor that models and forecasts multi-year financial market cycles, spectral harmonics (via Fast Fourier Transform), historical analog trajectories, and statistical time series models (ARIMA / SARIMAX).

***

### 🌟 Key Features

1. **Multi-Year Institutional Cycle Profiles:**
   - **Stock Market Cycle (18-Year Real Estate & Business Cycle):** 15.5Y Bullish phase, 3.5Y Bearish phase.
   - **Commodities Supercycle (16-Year Cycle):** 10.7Y Expansion phase, 5.3Y Contraction phase.
   - **Crypto Market Cycle (4-Year Halving Cycle):** 3Y Expansion phase, 1Y Contraction phase.
   - **Forex Dollar Cycle (8-Year Currency Cycle):** 4Y Bullish phase, 4Y Bearish phase.
   - **All Cycles Composite Overlay:** Weighted superposition of all macro cycles into a single unified momentum wave score ($-1.0$ to $+1.0$).

2. **Historical Cycle Analog Forecasting:**
   - Shifts back 1 full cycle duration ($t - \text{cycle\_len}$) to compute relative percentage return trajectory from that baseline and projects forward with 90% and 110% confidence bands.
   - Includes automatic cycle-modulated linear trend fallback.

3. **Fast Fourier Transform (FFT) Spectral Decomposition:**
   - Detrends log prices to extract empirical dominant harmonic cycles (periods in months and years) and calculates power spectral density (PSD) shares.

4. **Statistical Forecasting & Diagnostics:**
   - Fits **ARIMA(2,1,2)** and seasonal **SARIMA(2,1,2)(1,1,1)\[12]** models on monthly log prices with AIC/BIC metrics and forward projection paths.
   - **OLS Regression:** `Price = a + b * Cycle_Wave` ($R^2$ fit percentage and p-values).
   - **Seasonal Decomposition:** Trend, Seasonal, and Residual component variances.

5. **Historical Cycle Phase Ledger & Win Rates:**
   - Comprehensive ledger of all completed, active, and future phases with exact start/end prices, % returns, max peak drawdowns, and regime prediction accuracy (Bullish vs. Bearish win rates).

6. **Turning Point Countdown:**
   - Predicts exact upcoming cycle turning points (Peaks / Tops and Troughs / Bottoms) with countdown in days and months.

***

### 📥 Input Configuration

| Parameter | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `symbols` | `array` | `["SPY", "QQQ", "BTC-USD", "GC=F"]` | List of tickers, indices, commodities, currencies, or crypto. |
| `cycleTemplate` | `string` | `"all"` | `"all"`, `"stock_18y"`, `"commodity_16y"`, `"crypto_4y"`, or `"forex_8y"`. |
| `forecastHorizonMonths` | `integer` | `36` | Number of months into the future to project (6 to 120 months). |
| `yearsBack` | `integer` | `30` | Number of historical years of market data to fetch. |
| `enableArimaForecasts` | `boolean` | `true` | Fit ARMA, ARIMA, and seasonal SARIMA statistical models. |
| `enableSpectralFFT` | `boolean` | `true` | Compute Fast Fourier Transform to extract empirical dominant frequencies. |
| `includeHistoricalLedger` | `boolean` | `true` | Include historical Bullish/Bearish phase performance table. |
| `includeTimeSeries` | `boolean` | `true` | Include monthly OHLC and cycle wave historical series. |

***

### 📤 Output Schema

Each record in the dataset provides:

```json
{
  "symbol": "SPY",
  "cycleProfile": "all",
  "currentPrice": 585.20,
  "primaryCycle": "Stock Market Cycle (18Y)",
  "currentPhase": "Bullish 🟢",
  "phaseStartDate": "2024-03-01",
  "phaseEndDate": "2039-09-01",
  "daysRemaining": 4721,
  "monthsRemaining": 157,
  "compositeWaveScore": 0.452,
  "historicalBullishAccuracyPct": 88.5,
  "historicalBearishAccuracyPct": 75.0,
  "olsR2Pct": 68.4,
  "nextTurningPointDate": "2039-09-01",
  "nextTurningPointType": "Peak / Top",
  "projectedReturn1YPct": 12.8,
  "projectedReturn3YPct": 38.5,
  "fftDominantCyclesMonths": [216.0, 96.0, 48.0],
  "fftHarmonics": [
    {
      "periodMonths": 216.0,
      "periodYears": 18.0,
      "powerSharePct": 52.4
    }
  ],
  "statisticalModels": {
    "arima": { ... },
    "sarima": { ... }
  },
  "analogForecastSeries": [
    { "date": "2026-10-31", "projectedPrice": 595.4, "lowerCi": 535.86, "upperCi": 654.94 }
  ],
  "historicalLedger": [ ... ],
  "executiveSummary": "SPY is currently in a 🟢 BULLISH regime of the Stock Market Cycle (18Y)..."
}
```

***

### 🚀 Running Locally

```bash
uv run --with apify --with pandas --with numpy --with scipy --with statsmodels --with yfinance --with requests --with pytz python -m src.main
```

# Actor input Schema

## `symbols` (type: `array`):

List of tickers, indices, commodities, currencies, or crypto symbols to analyze cycles for (e.g. SPY, QQQ, BTC-USD, GC=F, EURUSD=X, AAPL, NVDA).

## `cycleTemplate` (type: `string`):

Select predefined institutional cycle templates or multi-cycle composite overlay.

## `forecastHorizonMonths` (type: `integer`):

Number of months into the future to project analog cycles and statistical ARIMA models (e.g. 36 months = 3 years).

## `yearsBack` (type: `integer`):

Number of historical years of market data to fetch for phase extraction and analog matching.

## `enableArimaForecasts` (type: `boolean`):

Enable fitting ARMA, ARIMA, and seasonal SARIMA statistical models on monthly log prices.

## `enableSpectralFFT` (type: `boolean`):

Perform power spectral density (PSD) decomposition to detect dominant periodic cycles.

## `includeHistoricalLedger` (type: `boolean`):

Include complete table of past Bullish/Bearish phases with start/end prices, % returns, drawdowns, and accuracy.

## `includeTimeSeries` (type: `boolean`):

Include monthly historical price and composite wave time series arrays.

## Actor input object example

```json
{
  "symbols": [
    "SPY",
    "QQQ",
    "BTC-USD",
    "GC=F"
  ],
  "cycleTemplate": "all",
  "forecastHorizonMonths": 36,
  "yearsBack": 30,
  "enableArimaForecasts": true,
  "enableSpectralFFT": true,
  "includeHistoricalLedger": true,
  "includeTimeSeries": true
}
```

# Actor output Schema

## `results` (type: `string`):

Dataset items and records produced by the Actor

## `overview` (type: `string`):

Summary report stored in Key-Value store

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "symbols": [
        "SPY",
        "QQQ",
        "BTC-USD",
        "GC=F"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("khnaami/time-cycle-forecaster-market-harmonics-analytics").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "symbols": [
        "SPY",
        "QQQ",
        "BTC-USD",
        "GC=F",
    ] }

# Run the Actor and wait for it to finish
run = client.actor("khnaami/time-cycle-forecaster-market-harmonics-analytics").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "symbols": [
    "SPY",
    "QQQ",
    "BTC-USD",
    "GC=F"
  ]
}' |
apify call khnaami/time-cycle-forecaster-market-harmonics-analytics --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,khnaami/time-cycle-forecaster-market-harmonics-analytics"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/WJJDppm1kxJ2l6pWb/builds/xTYBUFYqps8euZoKw/openapi.json
