Skip to main content

JBAC Strategy Foundry - A production-grade quantitative research engine

Project description

JSF-Core: JBAC Strategy Foundry

PyPI version Python Version License: MIT Tests Code style: black

⚠️ EDUCATIONAL PURPOSE ONLY — This software is for learning and research only. It is NOT intended for trading with real money. See Disclaimer.

JSF-Core is a production-grade, open-source quantitative research engine for building, backtesting, and optimizing algorithmic trading strategies. It ships with a real-time Streamlit monitoring dashboard, FinBERT-powered sentiment analysis, live paper trading via Alpaca, and multi-channel alert support.


Table of Contents


Features

Category What's Included
Backtesting Transaction costs, slippage, position tracking, multi-symbol
Signals 10+ signal types: Momentum, Mean-Reversion, Volatility, Sentiment
Portfolio 24 components: Equal weight, Risk Parity, Kelly, Min-Variance
Strategies Pre-built Momentum, Mean-Reversion, Trend-Following templates
ML XGBoost, LightGBM, Neural Networks, walk-forward validation
NLP FinBERT sentiment signals (positive/negative/neutral on news)
Dashboard Real-time Streamlit UI: P&L, Portfolio, Trades, Risk pages
Alerts Telegram, Console, Email notifications
Live Trading Alpaca paper/live trading integration
Metrics 20+ metrics: Sharpe, Sortino, Calmar, VaR, CVaR, Win Rate

Installation

Step 1 — Create a Virtual Environment

# Windows
python -m venv venv
venv\Scripts\activate

# macOS / Linux
python3 -m venv venv
source venv/bin/activate

Step 2 — Install from PyPI

# Core backtesting engine only (lightest install)
pip install jsf-core

# + NLP / FinBERT sentiment analysis
pip install jsf-core[ml]

# + Streamlit monitoring dashboard
pip install jsf-core[dashboard]

# + Alpaca live/paper trading
pip install jsf-core[trading]

# + Telegram & alert system
pip install jsf-core[alerts]

# Everything at once (recommended for full feature set)
pip install jsf-core[ml,dashboard,trading,alerts]

Install from Source (development)

git clone https://github.com/JaiAnshSB26/JBAC-Strategy-Foundry.git
cd JBAC-Strategy-Foundry
python -m venv venv
venv\Scripts\activate       # Windows — use "source venv/bin/activate" on Mac/Linux
pip install -e ".[dev]"
pre-commit install

Configuration

JSF-Core supports two configuration methods — use whichever fits your workflow. Both can be used together (YAML for settings, .env for secrets).

Option A — .env file (API keys and secrets)

cp .env.example .env    # Mac/Linux
copy .env.example .env  # Windows

Then edit .env:

# Alpaca paper trading — get free keys at https://alpaca.markets
ALPACA_API_KEY=PKxxxxxxxxxxxxxxxxxx
ALPACA_SECRET_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
ALPACA_BASE_URL=https://paper-api.alpaca.markets

# News / market data — get free key at https://www.alphavantage.co
ALPHA_VANTAGE_API_KEY=your_key_here

# Telegram alerts — create a bot via @BotFather on Telegram
TELEGRAM_BOT_TOKEN=1234567890:ABCdef...
TELEGRAM_CHAT_IDS=your_chat_id

# App settings
APP_ENV=development
LOG_LEVEL=INFO
ENABLE_TELEGRAM_ALERTS=true

.env is in .gitignore — your secrets never touch git.

Option B — config.yml (backtesting and dashboard settings)

cp config.example.yml config.yml    # Mac/Linux
copy config.example.yml config.yml  # Windows

Then edit config.yml:

environment: development

backtest:
  initial_capital: 100000
  transaction_cost: 0.001     # 10 basis points per trade
  slippage: 0.0005            # 5 basis points
  benchmark: "SPY"
  risk_free_rate: 0.05

broker:
  provider: alpaca
  mode: paper                 # paper | live
  alpaca:
    api_key: ""               # or set ALPACA_API_KEY in .env
    secret_key: ""
    base_url: https://paper-api.alpaca.markets

dashboard:
  symbols: [AAPL, GOOGL, MSFT, AMZN, NVDA]
  initial_capital: 100000
  history_days: 90
  refresh_interval: 30        # seconds (0 = disabled)

alerts:
  channels:
    telegram:
      enabled: true
      bot_token: ""           # or set TELEGRAM_BOT_TOKEN in .env
    console: true

See config.example.yml for all available options including ML, email alerts, and IB.

Getting API Keys (all free)

Service Purpose Sign up
Alpaca Paper/live trading + market data alpaca.markets
Alpha Vantage Historical market data (25 req/day) alphavantage.co
Telegram Bot Trade alerts on your phone @BotFather on Telegram

Quick Start

Backtesting a Strategy

from jsf.data import load_data
from jsf.strategies import MomentumStrategy
from jsf.simulation import BacktestEngine, BacktestConfig

# Load synthetic data (no API key needed)
data = load_data(
    source="synthetic",
    symbols=["AAPL", "GOOGL", "MSFT", "AMZN"],
    start_date="2020-01-01",
    end_date="2023-12-31",
)

# Create strategy
strategy = MomentumStrategy(name="momentum_60d", lookback=60, long_only=True)

# Configure and run backtest
config = BacktestConfig(
    initial_capital=100_000,
    transaction_cost=0.001,
    slippage=0.0005,
)
engine = BacktestEngine(config)
result = engine.run_strategy(strategy, data)

print(f"Total Return : {result.total_return:.2%}")
print(f"Sharpe Ratio : {result.sharpe_ratio:.2f}")
print(f"Max Drawdown : {result.max_drawdown:.2%}")

Backtesting with Real Data (Alpaca)

from jsf.data import load_data

# Requires: pip install jsf-core[trading]
# Set ALPACA_API_KEY and ALPACA_SECRET_KEY in environment or .env file
data = load_data(
    source="alpaca",
    symbols=["AAPL", "MSFT"],
    start_date="2023-01-01",
    end_date="2023-12-31",
)

Custom Signal

from jsf.signals import BaseSignal, SignalResult
import pandas as pd

class MyMomentumSignal(BaseSignal):
    def generate(self, data: pd.DataFrame) -> SignalResult:
        score = data["close"].pct_change(20).iloc[-1]
        return SignalResult(
            value=score,
            direction="long" if score > 0 else "short",
        )

Running the Example Scripts

Example scripts are included in the repository (not in the pip package). Clone the repo to run them:

git clone https://github.com/JaiAnshSB26/JBAC-Strategy-Foundry.git
cd JBAC-Strategy-Foundry
pip install -e ".[dev]"

python examples/quickstart.py                   # Simple backtest
python examples/complete_backtest_example.py    # Full metrics + charts
python examples/ml_example.py                   # ML strategy
python examples/paper_trading_alerts.py         # Live paper trading

Running the Dashboard

The Streamlit dashboard provides a live monitoring UI with P&L, positions, trades, risk analytics, and interactive backtesting.

Launch

# Requires: pip install jsf-core[dashboard]

# Option 1: CLI command (recommended)
jsf dashboard

# Option 2: Python module
python -m jsf.dashboard

Opens at http://localhost:8501

Demo Mode (no API keys needed)

Click "Start Demo Mode" in the sidebar. This instantly generates:

  • 90 days of historical mock equity data
  • 40 mock trades across AAPL, GOOGL, MSFT, AMZN, NVDA
  • Full metrics: Sharpe, drawdown, VaR, win rate, monthly heatmap

Dashboard Pages

Page What it shows
Overview Current positions table, allocation pie chart
Portfolio Detailed position breakdown, weights, sector allocation
P&L Equity curve, drawdown, daily returns, monthly heatmap, date range filters
Trades Full trade history, buy/sell breakdown, filters by symbol/date, CSV export
Risk VaR, CVaR, volatility, Calmar ratio, exposure analysis
Backtest Interactive strategy tester with all 3 strategy types, parameter sliders, equity/drawdown charts
Settings Connection status, version info, auto-refresh interval

Connect to Your Alpaca Account

Go to Settings in the dashboard sidebar and enter your Alpaca API key and secret. The dashboard will display your actual paper trading portfolio and update in real time.


Live Paper Trading

Connect to Alpaca paper trading to run strategies with real-time market data (no real money).

# Requires: pip install jsf-core[trading,alerts]
from jsf.broker import AlpacaBroker
from jsf.live import LiveTradingEngine, EngineConfig
from jsf.strategies import MomentumStrategy

# Initialize broker (reads from ALPACA_API_KEY env var)
broker = AlpacaBroker(paper=True)

# Create strategy
strategy = MomentumStrategy(name="live_momentum", lookback=20)

# Configure and start engine
config = EngineConfig(symbols=["AAPL", "MSFT"], poll_interval=60)
engine = LiveTradingEngine(broker=broker, strategy=strategy, config=config)
engine.start()

Set up Telegram alerts:

jsf setup-telegram

This wizard guides you through creating a Telegram bot and saves the credentials to .env.


Sentiment Analysis (NLP)

Requires pip install jsf-core[ml]. Downloads the FinBERT model (~400 MB on first run, then cached).

Single prediction

from jsf.ml.transformers.bert import FinBERT

model = FinBERT()

result = model.predict_one("Apple reports record earnings, beating analyst estimates by 20%.")
print(result.label.value)      # 'positive'
print(f"{result.score:.0%}")   # e.g. 96%
print(result.probabilities)    # {'positive': 0.96, 'negative': 0.01, 'neutral': 0.03}

Batch prediction

headlines = [
    "Revenue grew 25% year over year",
    "Company faces bankruptcy and mass layoffs",
    "Quarterly report was released on schedule",
]
for text, r in zip(headlines, model.predict(headlines)):
    print(f"{r.label.value:8s}  {r.score:.0%}  {text}")

# positive   94%  Revenue grew 25% year over year
# negative   97%  Company faces bankruptcy and mass layoffs
# neutral    81%  Quarterly report was released on schedule

Sentiment signal in strategy

from jsf.signals.sentiment import SentimentMomentumSignal

signal = SentimentMomentumSignal(
    name="finbert_momentum",
    model_type="finbert",       # "simple" for lightweight rule-based version
    lookback=7,
    sentiment_threshold=0.3,
    momentum_threshold=0.1,
)
# BUY  when sentiment > threshold AND price momentum rising
# SELL when sentiment < -threshold AND price momentum falling

Module Reference

jsf/
├── config/         Configuration schemas and YAML/env loaders
├── data/           Data loaders: Synthetic, Alpaca, YFinance, AlphaVantage
├── signals/        Signal generators: Momentum, MeanReversion, Volatility, Sentiment
├── portfolio/      Position sizing, optimization, rebalancing, risk constraints
├── strategies/     Ready-made strategies: Momentum, MeanReversion, TrendFollowing
├── simulation/     BacktestEngine with transaction costs, slippage, tracking
├── optimization/   Grid search and walk-forward parameter optimization
├── evaluation/     Performance metrics (20+ metrics)
├── ml/             XGBoost, LightGBM, Neural Networks, FinBERT NLP
├── broker/         Alpaca and Interactive Brokers live trading
├── dashboard/      Streamlit real-time monitoring dashboard
├── alerts/         Telegram, Console, Email alert system
├── cli/            Command-line tools (setup_telegram, etc.)
└── utils/          Shared utilities and helpers

Project Structure

JBAC-Strategy-Foundry/
├── src/jsf/                    Main package source
├── tests/                      Test suite (635 tests)
├── examples/                   Runnable example scripts
│   ├── quickstart.py
│   ├── complete_backtest_example.py
│   ├── ml_example.py
│   └── paper_trading_alerts.py
├── demos/                      Feature demo scripts
│   ├── demo_real_sentiment.py
│   ├── demo_ml_pipeline.py
│   └── demo_realtime_news.py
├── docs/                       Extended documentation
├── config.example.yml          Config template  →  copy to config.yml
├── .env.example                API key template →  copy to .env
├── pyproject.toml              Package metadata and dependencies
├── requirements.txt            Full dependency list with comments
└── Makefile                    Dev shortcuts: test, lint, format, build

Development

make test        # Run all 635 tests with coverage report
make test-fast   # Run tests without coverage
make lint        # ruff + mypy
make format      # black formatter
make check       # lint + test (run before committing)
make build       # Build wheel + sdist into dist/
make clean       # Remove build artifacts

Disclaimer

EDUCATIONAL PURPOSE ONLY

This software is provided for educational and research purposes only. It is designed to help students, researchers, and developers learn about quantitative trading concepts, backtesting methodologies, and algorithmic strategy development.

  1. NOT FINANCIAL ADVICE — Nothing here constitutes investment, tax, or legal advice.
  2. NO REAL TRADING — This software is not intended for use with real money.
  3. PAST PERFORMANCE — Backtested results do not guarantee future returns.
  4. SUBSTANTIAL RISK — Trading involves substantial risk of total capital loss.
  5. NO WARRANTY — Provided "AS IS" with no liability for any losses or damages.

By using this software you accept full responsibility for any outcomes.


Contributing

Contributions are welcome! Please read CONTRIBUTING.md for guidelines.

License

MIT License — see LICENSE for details.

Contact

JBAC EdTech · GitHub: @JaiAnshSB26

PyPI: pypi.org/project/jsf-core

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

jsf_core-0.7.2.tar.gz (298.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

jsf_core-0.7.2-py3-none-any.whl (313.7 kB view details)

Uploaded Python 3

File details

Details for the file jsf_core-0.7.2.tar.gz.

File metadata

  • Download URL: jsf_core-0.7.2.tar.gz
  • Upload date:
  • Size: 298.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.4

File hashes

Hashes for jsf_core-0.7.2.tar.gz
Algorithm Hash digest
SHA256 8dea2ac08199e1bf55de1261f37dc78f97f090c944a9a3df01fd7c7455e55d2f
MD5 877d877c00ec575c42b46cdcec7eb46b
BLAKE2b-256 cfd0ca9c603cda9d29a4f25828911a19b28afe8856ed576053a4a36d8ff35fb4

See more details on using hashes here.

File details

Details for the file jsf_core-0.7.2-py3-none-any.whl.

File metadata

  • Download URL: jsf_core-0.7.2-py3-none-any.whl
  • Upload date:
  • Size: 313.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.4

File hashes

Hashes for jsf_core-0.7.2-py3-none-any.whl
Algorithm Hash digest
SHA256 623fc09b8394f9af15fe1e2cde6fcd2b792aaa3e8caabc84deaa029ae85bba92
MD5 1ed03a18fc2505138e4504e6fe0cd395
BLAKE2b-256 7c5bd27c2110609b6b5901aa53fdb077da100ea585a33b0affec80e4462f27b0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page