Professional-grade SDK for algorithmic trading on prediction markets (Beta - Core features stable, advanced modules experimental)
Project description
Neural SDK
Professional-grade SDK for algorithmic trading on prediction markets
⚡ What is Neural?
Neural SDK is a comprehensive Python framework for building algorithmic trading strategies on prediction markets. It provides everything you need to collect data, develop strategies, backtest performance, and execute trades—all with production-grade reliability.
🔐 Real Data Guarantee
All market data comes from Kalshi's live production API via RSA-authenticated requests. This is the same infrastructure that powers a $100M+ trading platform—no simulations, no mocks, just real markets on real events.
⭐ Key Features
- 🔑 Authentication: Battle-tested RSA signature implementation for Kalshi API
- 📊 Historical Data: Collect and analyze real trade data with cursor-based pagination
- 🚀 Real-time Streaming: REST API and FIX protocol support for live market data
- 🧠 Strategy Framework: Pre-built strategies (mean reversion, momentum, arbitrage)
- ⚖️ Risk Management: Kelly Criterion, position sizing, stop-loss automation
- 🔬 Backtesting Engine: Test strategies on historical data before going live
- ⚡ Order Execution: Ultra-low latency FIX protocol integration (5-10ms)
🚀 Quick Start
Installation
# Basic installation
pip install neural-sdk
# With trading extras (recommended for live trading)
pip install "neural-sdk[trading]"
# Via uv (recommended)
uv pip install neural-sdk
uv pip install "neural-sdk[trading]" # with trading extras
Credentials Setup
Neural SDK connects to Kalshi's live API using RSA authentication. You'll need valid Kalshi credentials:
Environment Variables
# Option 1: Set environment variables
export KALSHI_EMAIL="your-email@example.com"
export KALSHI_PASSWORD="your-password"
export KALSHI_API_BASE="https://trading-api.kalshi.com/trade-api/v2"
.env File (Recommended)
# Option 2: Create .env file in your project root
echo "KALSHI_EMAIL=your-email@example.com" > .env
echo "KALSHI_PASSWORD=your-password" >> .env
echo "KALSHI_API_BASE=https://trading-api.kalshi.com/trade-api/v2" >> .env
The SDK will automatically load credentials from your .env file using python-dotenv.
Basic Usage
1. Authentication
from neural.auth.http_client import KalshiHTTPClient
# Initialize with credentials
client = KalshiHTTPClient()
# Verify connection
markets = client.get('/markets')
print(f"Connected! Found {len(markets['markets'])} markets")
2. Collect Historical Data
from datetime import datetime, timedelta
import pandas as pd
# Set time range
end_ts = int(datetime.now().timestamp())
start_ts = end_ts - (7 * 24 * 3600) # Last 7 days
# Collect trades with pagination
all_trades = []
cursor = None
while True:
response = client.get_trades(
ticker="KXNFLGAME-25SEP25SEAARI-SEA",
min_ts=start_ts,
max_ts=end_ts,
limit=1000,
cursor=cursor
)
trades = response.get("trades", [])
if not trades:
break
all_trades.extend(trades)
cursor = response.get("cursor")
if not cursor:
break
# Analyze
df = pd.DataFrame(all_trades)
print(f"Collected {len(df)} real trades from Kalshi")
3. Build a Trading Strategy
from neural.analysis.strategies import MeanReversionStrategy
from neural.analysis.backtesting import BacktestEngine
# Create strategy
strategy = MeanReversionStrategy(
lookback_period=20,
z_score_threshold=2.0
)
# Backtest
engine = BacktestEngine(strategy, initial_capital=10000)
results = engine.run(historical_data)
print(f"Total Return: {results['total_return']:.2%}")
print(f"Sharpe Ratio: {results['sharpe_ratio']:.2f}")
print(f"Max Drawdown: {results['max_drawdown']:.2%}")
4. Live Trading
from neural.trading.client import TradingClient
# Initialize trading client
trader = TradingClient()
# Place order
order = trader.place_order(
ticker="KXNFLGAME-25SEP25SEAARI-SEA",
side="yes",
count=100,
price=55
)
print(f"Order placed: {order['order_id']}")
📚 Documentation
Core Modules
| Module | Description |
|---|---|
neural.auth |
RSA authentication for Kalshi API |
neural.data_collection |
Historical and real-time market data |
neural.analysis.strategies |
Pre-built trading strategies |
neural.analysis.backtesting |
Strategy testing framework |
neural.analysis.risk |
Position sizing and risk management |
neural.trading |
Order execution (REST + FIX) |
SDK Module Quickstart
Authentication Module
from neural.auth.http_client import KalshiHTTPClient
# Initialize client with credentials from environment
client = KalshiHTTPClient()
# Test connection
response = client.get('/markets')
print(f"Connected! Found {len(response['markets'])} markets")
# Get specific market
market = client.get('/markets/NFLSUP-25-KCSF')
print(f"Market: {market['title']}")
Data Collection Module
from neural.data_collection.kalshi_historical import KalshiHistoricalDataSource
from neural.data_collection.base import DataSourceConfig
import pandas as pd
# Configure historical data collection
config = DataSourceConfig(
source_type="kalshi_historical",
ticker="NFLSUP-25-KCSF",
start_time="2024-01-01",
end_time="2024-12-31"
)
# Collect historical trades
source = KalshiHistoricalDataSource(config)
trades_data = []
async def collect_trades():
async for trade in source.collect():
trades_data.append(trade)
if len(trades_data) >= 1000: # Limit for example
break
# Run collection and analyze
import asyncio
asyncio.run(collect_trades())
df = pd.DataFrame(trades_data)
print(f"Collected {len(df)} trades")
print(f"Price range: {df['price'].min():.2f} - {df['price'].max():.2f}")
Trading Module
from neural.trading.client import TradingClient
# Initialize trading client
trader = TradingClient()
# Check account balance
balance = trader.get_balance()
print(f"Available balance: ${balance:.2f}")
# Place a buy order
order = trader.place_order(
ticker="NFLSUP-25-KCSF",
side="yes", # or "no"
count=10, # number of contracts
price=52 # price in cents
)
print(f"Order placed: {order['order_id']}")
# Check order status
status = trader.get_order(order['order_id'])
print(f"Order status: {status['status']}")
Examples
Explore working examples in the examples/ directory:
01_init_user.py- Authentication setupstream_prices.py- Real-time price streamingtest_historical_sync.py- Historical data collection05_mean_reversion_strategy.py- Strategy implementation07_live_trading_bot.py- Automated trading bot
Authentication Setup
-
Get API credentials from Kalshi
-
Save credentials:
# Create secrets directory mkdir secrets # Add your API key ID echo "your-api-key-id" > secrets/kalshi_api_key_id.txt # Add your private key cp ~/Downloads/kalshi_private_key.pem secrets/ chmod 600 secrets/kalshi_private_key.pem
-
Set environment variables (optional):
export KALSHI_API_KEY_ID="your-api-key-id" export KALSHI_PRIVATE_KEY_PATH="./secrets/kalshi_private_key.pem"
🧪 Testing
# Run all tests
pytest
# With coverage
pytest --cov=neural tests/
# Run specific test
pytest tests/test_auth.py -v
🤝 Contributing
We welcome contributions! Neural SDK is open source and community-driven.
How to Contribute
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Make your changes and add tests
- Run tests:
pytest - Commit:
git commit -m "Add amazing feature" - Push:
git push origin feature/amazing-feature - Open a Pull Request
See CONTRIBUTING.md for detailed guidelines.
Development Setup
# Clone repository
git clone https://github.com/IntelIP/Neural.git
cd neural
# Install in editable mode with dev dependencies
pip install -e ".[dev]"
# Run tests
pytest
# Run linting
ruff check .
black --check .
📖 Resources
- Documentation: neural-sdk.mintlify.app
- Examples: examples/
- API Reference: docs/api/
- Issues: GitHub Issues
- Discussions: GitHub Discussions
🗺️ Roadmap
Version 0.1.0 (Beta) - Current
- ✅ Core authentication
- ✅ Historical data collection
- ✅ Strategy framework
- ✅ Backtesting engine
- ⚠️ REST streaming (stable)
- ⚠️ WebSocket streaming (experimental)
Version 0.2.0 (Planned)
- 🔄 Enhanced WebSocket support
- 🔄 Real-time strategy execution
- 🔄 Portfolio optimization
- 🔄 Multi-market strategies
Version 1.0.0 (Future)
- 🚀 Deployment stack (AWS/GCP integration)
- 🚀 Production monitoring & alerting
- 🚀 Advanced risk analytics
- 🚀 Machine learning strategies
⚖️ License
This project is licensed under the MIT License - see LICENSE file for details.
What This Means
✅ You CAN:
- Use commercially
- Modify the code
- Distribute
- Use privately
❌ You CANNOT:
- Hold us liable
- Use our trademarks
📋 You MUST:
- Include the original license
- Include copyright notice
🙏 Acknowledgments
- Built for the Kalshi prediction market platform
- Inspired by the quantitative trading community
- Special thanks to all contributors
📞 Support
- Documentation: neural-sdk.mintlify.app
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Email: support@neural-sdk.dev
Built with ❤️ by the Neural community
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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file neural_sdk-0.3.0.tar.gz.
File metadata
- Download URL: neural_sdk-0.3.0.tar.gz
- Upload date:
- Size: 136.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
59f0d767e6c7dd7fadef413ba929db9104d3c6087e047992fcf56f08c339a279
|
|
| MD5 |
6d5f06a9f10ad4deb53d4ec153a0b68c
|
|
| BLAKE2b-256 |
681639883ee94e5ab3fd908fa2229217230acb90c5aa3422b6904c27a558ad54
|
File details
Details for the file neural_sdk-0.3.0-py3-none-any.whl.
File metadata
- Download URL: neural_sdk-0.3.0-py3-none-any.whl
- Upload date:
- Size: 114.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c4c19b750aaa8186ac0604b12c4d174328a011bddf2a6170e0eec7d247854539
|
|
| MD5 |
6cf71cceea0573cd5b82f81e4ffd9bc5
|
|
| BLAKE2b-256 |
9bf606255c3c1112231a921e58b6d1f35388bbb3e989c404c4dab6a3d64c0456
|