Quantitative research framework investigating correlations between astronomical ephemeris geometry (Swiss Ephemeris natal charts, planetary longitudes, retrograde cycles, and harmonic transits) and equity price action using Dask parallelization and XGBoost gradient-boosted trees.
Overview โข Capabilities โข Methodology โข Architecture โข Structure โข Setup & Usage โข API
Warning
Educational & Experimental Research Only: pyAstroTrader investigates planetary ephemeris correlations with market series as an academic machine learning exercise. Do NOT use model outputs for live trading or investment decisions.
pyAstroTrader combines high-precision astronomical calculations via Swiss Ephemeris (pyswisseph) with XGBoost regression/classification pipelines executed through automated Jupyter notebooks and a Flask REST server. Given an equity or ETF ticker and its historical listing ("natal") timestamp, the system computes daily geocentric/sidereal planetary longitudes, pairwise angular separations, and natal-to-transit aspects, then trains boosted tree models to predict directional price-change or swing-trade targets across upcoming trading days.
The notebooks/input/ and notebooks/output/ directories contain ready-to-inspect datasets, trained .model files, ranked feature-importance logs, and 30-calendar-day forecast workbooks for 9 US equities and ETFs:
| Ticker | Daily Bars (notebooks/input/) |
Trained Model (notebooks/output/) |
Recorded Training MSE (*.score.price.change.txt) |
Ranked Features | Top Feature |
|---|---|---|---|---|---|
AAPL |
100 rows (2025-08-15 โ 2026-01-07) |
AAPL_price_change.model |
3.64e-07 |
40 | ASTRO_SUN_POSITION |
DIA |
100 rows (2025-08-15 โ 2026-01-07) |
DIA_price_change.model |
1.55e-07 |
40 | ASTRO_SUN_POSITION |
GLD |
100 rows (2025-11-07 โ 2026-04-02) |
GLD_price_change.model |
2.49e-07 |
45 | ASTRO_SUN_POSITION |
GOOGL |
100 rows (2025-11-07 โ 2026-04-02) |
GOOGL_price_change.model |
4.98e-07 |
45 | ASTRO_SUN_POSITION |
MSFT |
100 rows (2025-08-15 โ 2026-01-07) |
MSFT_price_change.model |
8.94e-07 |
39 | ASTRO_SUN_POSITION |
NVDA |
100 rows (2025-08-15 โ 2026-01-07) |
NVDA_price_change.model |
8.93e-07 |
41 | ASTRO_SUN_POSITION |
QQQ |
100 rows (2025-08-15 โ 2026-01-07) |
QQQ_price_change.model |
3.60e-07 |
41 | ASTRO_SUN_POSITION |
SLV |
100 rows (2025-08-15 โ 2026-01-07) |
SLV_price_change.model |
3.47e-07 |
40 | ASTRO_SUN_POSITION |
SPY |
100 rows (2025-08-15 โ 2026-01-07) |
SPY_price_change.model |
4.74e-07 |
41 | ASTRO_SUN_POSITION |
Note: Brazilian equities (
PETR4.SA,VALE3.SA,ITUB4.SA,BBDC4.SA,ABEV3.SA) and^BVSPalso have configured natal timestamps innotebooks/settings.pyandassets_to_calculate.txt.
| Component | Path | Responsibility |
|---|---|---|
| Ephemeris Core | pyastrotrader/calculate/calculate.py |
Computes Julian Day UT (swe.julday), ecliptic positions (swe.calc_ut), Placidus house cusps (swe.houses), coordinate flags (truegeo, topo, helio), sidereal mode (FAGAN_BRADLEY), and retrograde flags. |
| Aspect & Transit Engine | pyastrotrader/transits/transits.py |
Evaluates intra-chart (calculate_aspects) and radix-to-transit (calculate_transits) angular separations across 11 aspects (0ยฐโ180ยฐ) within a 4ยฐ orb tolerance. |
| Celestial Constants | pyastrotrader/constants.py |
Indexes 35 bodies/points (SUN through TRUE_LILITH) and 11 aspect definitions (CONJUNCTION, SEMISEXTILE, SEMISQUARE, SEXTILE, QUINTILE, SQUARE, TRINE, SESQUIQUADRATE, BIQUINTILE, QUINCUNX, OPPOSITION). |
| Market Data Fetcher | pyastrotrader/data_fetcher.py |
Provides fetch_data_yfinance (20-year history via yfinance), fetch_data_alphavantage (TIME_SERIES_DAILY), and fetch_stock_data(..., source='auto') fallback. |
| Config & Input Builder | pyastrotrader/config.py, pyastrotrader/utils/__init__.py |
Validates SWISSEPH_PATH and chart JSON schema; builds input payloads using default_config.json and default_parameters.json. |
| Feature & Label Helpers | notebooks/helpers.py, notebooks/settings.py |
Generates trend/swing/volatility labels, quantized planetary features, iterative XGBoost boosting (get_best_booster), and clamped predictions (predict_score). |
| Notebook Pipeline | notebooks/*.ipynb |
DownloadData.ipynb โ CreateModel.price.change.ipynb / CreateModel.swing.trade.ipynb โ Predict.price.change.ipynb / Predict.swing.trade.ipynb. |
| Flask API & Runners | astrotrader_server.py, run_astro.ps1, run_notebooks*.sh |
Automates end-to-end execution via jupyter nbconvert and serves prediction results over HTTP JSON endpoints. |
For each trading date 10:00:00-03:00 in generate_charts), CreateModel.price.change.ipynb computes ecliptic longitudes PLANETS_TO_CALCULATE = [SUN, MOON, VENUS, MERCURY, MARS, JUPITER, SATURN] and quantizes features into ASTRO_{i}_POSITION for non-Saturn bodies and pairwise differences across all pairs):
When ASPECTS_TO_CALCULATE is populated, binary flags (is_aspected, is_aspected_transiting) test whether
-
Daily Price-Change Signal (
TARGET_PRICE_CHANGE): $$y_t = \begin{cases} +1 & \text{if } \left(\frac{P_t}{P_{t-1}} - 1\right)\times 100 > 1% \ -1 & \text{if } \left(\frac{P_t}{P_{t-1}} - 1\right)\times 100 < -1% \ 0 & \text{otherwise} \end{cases}$$ -
Swing-Trade Signals (
CreateModel.swing.trade.ipynb): Compares backward and forwardSWING_TRADE_DURATION = 5day trends againstIntradayVolatility($\times 3.5$ ) and detects local5-bar lows (TARGET_IS_SWING_BOTTOM) or directional moves exceedingSTAGNATION_THRESHOLD = 5%.
helpers.py trains xgb.train (booster='gbtree', objective='reg:squarederror', eta=0.3, max_depth=7, subsample=0.5, num_round=1000) sequentially up to MAX_INTERACTIONS = 50 rounds on random 70/30 splits (xgb_model=booster), retaining the model minimizing full-sample Predict.*.ipynb cover the next DAYS_TO_PREDICT = 30 calendar days (excluding weekends) and clamp outputs to
flowchart TD
subgraph Ingestion["Market Data Ingestion"]
AV["Alpha Vantage API\n(DownloadData.ipynb)"]
YF["Yahoo Finance\n(pyastrotrader/data_fetcher.py)"]
IN["notebooks/input/{TICKER}_Daily.csv"]
end
subgraph Ephemeris["Swiss Ephemeris Computation"]
SWE["pyastrotrader/swisseph/*.se1"]
CALC["pyastrotrader/calculate\n(Natal & Daily Charts)"]
TRN["pyastrotrader/transits\n(Aspects & Transits)"]
end
subgraph Features["Dask Feature Pipeline & Training"]
FEAT["notebooks/helpers.py\n(3-deg Quantized Positions & Targets)"]
XGB["XGBoost Booster\n(get_best_booster, up to 50 iterations)"]
MOD["notebooks/output/{TICKER}_price_change.model\n+ .score + .features + .Analisys.xlsx"]
end
subgraph Serving["Forecasting and API Layer"]
PRED["Predict.price.change.ipynb\n(30-Day Weekday Forecast)"]
XLSX["notebooks/output/{TICKER}.Predict.Simplified.xlsx"]
FLASK["astrotrader_server.py\n(Flask REST API on :5000)"]
end
AV --> IN
YF -.-> IN
IN --> FEAT
SWE --> CALC --> TRN --> FEAT
FEAT --> XGB --> MOD
MOD --> PRED --> XLSX
XLSX --> FLASK
pyAstroTrader-master/
โโโ .gitattributes
โโโ .gitignore
โโโ LICENSE # MIT License
โโโ README.md
โโโ requirements.txt # Flask, yfinance, XGBoost, pyswisseph, Dask, Jupyter
โโโ assets_to_calculate.txt # Batch ticker list (PETR4.SA..ABEV3.SA)
โโโ astrotrader_server.py # Flask REST API wrapping run_astro.ps1 & Excel outputs
โโโ run_astro.ps1 # Windows PowerShell end-to-end notebook runner
โโโ run_all.sh # Batch wrapper running assets_to_calculate.txt
โโโ run_notebooks.sh # Linux/macOS single-asset pipeline runner
โโโ run_notebooks_multiple.sh # Iterative multi-model runner (PRICE_CHANGE / SWING_TRADE)
โโโ start_notebooks.sh # Launches JupyterLab on port 8080
โโโ clean_notebooks.sh # Strips outputs from notebooks/*.ipynb
โโโ debug_runner.py # Standalone runner for debug_create_model_price_change.py
โโโ test_api.py # Alpha Vantage API connectivity check
โโโ extract_script.py # Exports CreateModel.ipynb code cells to Python
โโโ fix_multiprocessing.py # Notebook multiprocessing patch utility
โโโ patch_notebook.py # Patches DownloadData.ipynb API parameters
โโโ patch_notebook_threads.py # Switches Dask scheduler to threads in Predict
โโโ patch_notebook_xls.py # Converts .xls output paths to .xlsx in Predict
โโโ docs/
โ โโโ jpmorgan.jpg
โโโ pyastrotrader/
โ โโโ __init__.py # Public API exports
โ โโโ config.py # SWISSEPH_PATH & JSON schema validation
โ โโโ constants.py # Planet & aspect IDs and angle tables
โ โโโ data_fetcher.py # Yahoo Finance + Alpha Vantage fetcher
โ โโโ calculate/
โ โ โโโ __init__.py
โ โ โโโ calculate.py # Swiss Ephemeris chart & house calculation
โ โโโ transits/
โ โ โโโ __init__.py
โ โ โโโ transits.py # Planetary aspects, transits & angular separation
โ โโโ utils/
โ โ โโโ __init__.py # create_input_json helper
โ โโโ swisseph/ # Swiss Ephemeris data files (*.se1, fixstars.cat)
โ โโโ test/ # default_config.json, default_parameters.json, sample natal JSON
โโโ notebooks/
โ โโโ settings.py # Natal dates, hyperparameters & environment checks
โ โโโ helpers.py # Indicator, aspect & XGBoost training helpers
โ โโโ debug_create_model_price_change.py # Script export of CreateModel.price.change
โ โโโ DownloadData.ipynb # Alpha Vantage daily quote downloader
โ โโโ CreateModel.price.change.ipynb # Price-change (+/-1%) XGBoost training notebook
โ โโโ CreateModel.swing.trade.ipynb # Swing-trade bottom XGBoost training notebook
โ โโโ Predict.price.change.ipynb # 30-day price-change inference notebook
โ โโโ Predict.swing.trade.ipynb # 30-day swing-trade inference notebook
โ โโโ config/ # default_config.json, default_parameters.json
โ โโโ input/ # {TICKER}_Daily.csv & .xlsx for 9 assets
โ โโโ output/ # Trained .model, .cache, .Analisys.xlsx & .Predict*.xlsx
โโโ test/
โโโ test_calculate.py # Swiss Ephemeris natal chart & transit smoke test
- Python
3.8+(noterequirements.txtcontains pinned legacy versions such asxgboost==0.90,pandas==0.25.3, andpyswisseph==2.0.0.post2alongsideflask>=3.0.0andyfinance>=0.2.0; if installing on Python3.12+, install current compatible wheels fornumpy,pandas,dask[dataframe],scikit-learn,xgboost,pyswisseph,openpyxl,plotly,jupyter,flask,flask-cors, andyfinance) - Alpha Vantage API Key (required by
DownloadData.ipynband/api/run-prediction; optional when usingpyastrotrader/data_fetcher.pydirectly withyfinance)
git clone https://github.com/khalid-naami/pyAstroTrader-master.git
cd pyAstroTrader-master
python -m venv .venv# Windows (PowerShell)
.venv\Scripts\Activate.ps1# macOS / Linux
source .venv/bin/activatepip install -r requirements.txt# Windows (PowerShell)
$Env:ASSET_TO_CALCULATE = "AAPL"
$Env:ALPHAVANTAGE_KEY = "YOUR_ALPHAVANTAGE_API_KEY"
$Env:PYTHONPATH = "$PWD;$PWD\notebooks"
$Env:SWISSEPH_PATH = "$PWD\pyastrotrader\swisseph"# macOS / Linux
export ASSET_TO_CALCULATE="AAPL"
export ALPHAVANTAGE_KEY="YOUR_ALPHAVANTAGE_API_KEY"
export PYTHONPATH="$PWD:$PWD/notebooks"
export SWISSEPH_PATH="$PWD/pyastrotrader/swisseph"# Windows PowerShell (executes DownloadData -> CreateModel.price.change -> Predict.price.change)
.\run_astro.ps1 -Asset "AAPL" -ApiKey "YOUR_ALPHAVANTAGE_API_KEY"# Linux / macOS (JupyterLab interactive mode)
./start_notebooks.sh
# Or run Swiss Ephemeris unit smoke test from test/
cd test && python test_calculate.pyfrom pyastrotrader.data_fetcher import fetch_stock_data
df = fetch_stock_data("AAPL", source="yfinance")
print(df.head())Start the Flask API server on port 5000:
python astrotrader_server.py| Endpoint | Method | Behavior |
|---|---|---|
/api/run-prediction |
POST |
Accepts JSON {"ticker": "AAPL", "apiKey": "YOUR_KEY"}, runs run_astro.ps1 (10-minute timeout), and returns parsed predictions and model MSE score. |
/api/get-results/<ticker> |
GET |
Reads notebooks/output/{TICKER}.Predict.Simplified.xlsx and {TICKER}.score.price.change.txt and returns JSON predictions. |
/api/available-tickers |
GET |
Scans notebooks/output/*.Predict.Simplified.xlsx and lists all tickers with generated forecasts. |
/ |
GET |
Serves astrotrader_web.html if present in the repository root (note: only the JSON REST endpoints are tracked in the current repository). |
Released under the MIT License โ see LICENSE for full terms.
