Spaces:
Running
Running
File size: 17,793 Bytes
b41bee3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 | #!/usr/bin/env python3
"""
๐ฏ๐ฎ AUREON SELF-VALIDATING PREDICTION ENGINE ๐ฎ๐ฏ
===================================================
This system PREDICTS market movements BEFORE they happen,
then VALIDATES predictions against actual results.
PROCESS:
1. Collect baseline data (10 seconds)
2. Generate PREDICTION for next 30 seconds
3. WAIT for prediction window
4. VALIDATE prediction against actual movement
5. Score accuracy and adjust
Only when predictions are CONSISTENTLY CORRECT do we trade.
Gary Leckey | December 2025
"Predict. Validate. Then Trade."
"""
from aureon.core.aureon_baton_link import link_system as _baton_link; _baton_link(__name__)
import os
import sys
import time
import math
import json
import numpy as np
from datetime import datetime, timedelta
from typing import Dict, List, Tuple, Optional
from dataclasses import dataclass, field
from collections import deque
os.environ['LIVE'] = '1'
from aureon.exchanges.binance_client import BinanceClient, get_binance_client
from aureon.exchanges.kraken_client import KrakenClient, get_kraken_client
# Constants
PHI = (1 + math.sqrt(5)) / 2
FREQ_MAP = {
'ROOT': 256.0,
'TRANSFORMATION': 417.0,
'NATURAL': 432.0,
'DISTORTION': 440.0,
'LOVE': 528.0,
'CONNECTION': 639.0,
}
@dataclass
class Prediction:
"""A single prediction with validation"""
symbol: str
platform: str
timestamp: datetime
# Baseline
baseline_price: float
baseline_momentum: float
baseline_frequency: float
# Prediction (30 seconds ahead)
predicted_direction: str # UP, DOWN, FLAT
predicted_change_pct: float
predicted_price: float
confidence: float
# Validation (filled after window)
actual_price: float = 0.0
actual_change_pct: float = 0.0
actual_direction: str = ""
# Scoring
direction_correct: bool = False
magnitude_accuracy: float = 0.0 # How close was the prediction
validated: bool = False
def validate(self, actual_price: float):
"""Validate prediction against actual result"""
self.actual_price = actual_price
self.actual_change_pct = ((actual_price - self.baseline_price) / self.baseline_price) * 100
# Determine actual direction
if self.actual_change_pct > 0.01:
self.actual_direction = "UP"
elif self.actual_change_pct < -0.01:
self.actual_direction = "DOWN"
else:
self.actual_direction = "FLAT"
# Check direction accuracy
self.direction_correct = (self.predicted_direction == self.actual_direction)
# Calculate magnitude accuracy (how close was the prediction)
if self.predicted_change_pct != 0:
error = abs(self.actual_change_pct - self.predicted_change_pct)
self.magnitude_accuracy = max(0, 1 - (error / abs(self.predicted_change_pct)))
else:
self.magnitude_accuracy = 1.0 if abs(self.actual_change_pct) < 0.02 else 0.0
self.validated = True
class SelfValidatingPredictor:
"""
Prediction engine that validates its own assumptions.
"""
def __init__(self):
print("\n๐ฎ Initializing Self-Validating Prediction Engine...")
self.binance = get_binance_client()
self.kraken = get_kraken_client()
# Prediction history
self.predictions: List[Prediction] = []
self.accuracy_window = deque(maxlen=20) # Last 20 predictions
# Tracking
self.total_predictions = 0
self.correct_predictions = 0
print(" โ
Ready to predict and validate\n")
def get_price(self, platform: str, symbol: str) -> float:
"""Get current price"""
try:
if platform == 'binance':
ticker = self.binance.get_24h_ticker(symbol)
return float(ticker.get('lastPrice', 0))
elif platform == 'kraken':
ticker = self.kraken.get_24h_ticker(symbol)
return float(ticker.get('lastPrice', 0))
except:
pass
return 0.0
def collect_baseline(self, platform: str, symbol: str,
duration_sec: int = 10) -> Tuple[List[float], float, float]:
"""
Collect baseline data for prediction.
Returns (prices, avg_momentum, frequency)
"""
prices = []
prev_price = None
momentums = []
for i in range(duration_sec * 2): # 2 samples per second
price = self.get_price(platform, symbol)
if price > 0:
prices.append(price)
if prev_price:
momentum = ((price - prev_price) / prev_price) * 100
momentums.append(momentum)
prev_price = price
time.sleep(0.5)
avg_momentum = np.mean(momentums) if momentums else 0
# Calculate frequency
if len(prices) >= 2:
ratio = prices[-1] / prices[0]
frequency = 432.0 * (ratio ** PHI)
frequency = max(256, min(963, frequency))
else:
frequency = 432.0
return prices, avg_momentum, frequency
def generate_prediction(self, platform: str, symbol: str,
prices: List[float], momentum: float,
frequency: float) -> Prediction:
"""
Generate 30-second prediction based on:
- Momentum trend
- Frequency state
- Pattern analysis
"""
baseline_price = prices[-1] if prices else 0
# Analyze momentum pattern
if len(prices) >= 5:
recent_prices = prices[-5:]
price_trend = np.polyfit(range(len(recent_prices)), recent_prices, 1)[0]
momentum_strength = abs(momentum) * 10
else:
price_trend = 0
momentum_strength = 0
# Frequency influence
freq_boost = 0
if abs(frequency - FREQ_MAP['LOVE']) < 30:
freq_boost = 0.02 # Love frequency = bullish
elif abs(frequency - FREQ_MAP['NATURAL']) < 15:
freq_boost = 0.01 # Natural = slight bullish
elif abs(frequency - FREQ_MAP['DISTORTION']) < 10:
freq_boost = -0.02 # Distortion = bearish
# Calculate predicted change
# Base: momentum continuation with decay
momentum_contribution = momentum * 0.5 # 50% momentum continuation
trend_contribution = (price_trend / baseline_price) * 100 * 30 if baseline_price > 0 else 0 # Extrapolate 30 sec
frequency_contribution = freq_boost
predicted_change = momentum_contribution + trend_contribution * 0.3 + frequency_contribution
# Clamp to reasonable range
predicted_change = max(-0.5, min(0.5, predicted_change))
# Determine direction
if predicted_change > 0.01:
direction = "UP"
elif predicted_change < -0.01:
direction = "DOWN"
else:
direction = "FLAT"
# Calculate confidence
momentum_consistency = 1.0 - min(1.0, np.std(prices[-5:]) / np.mean(prices[-5:]) * 100) if len(prices) >= 5 else 0.5
confidence = min(0.9, (momentum_consistency * 0.5 + momentum_strength * 0.3 + 0.2))
predicted_price = baseline_price * (1 + predicted_change / 100)
return Prediction(
symbol=symbol,
platform=platform,
timestamp=datetime.now(),
baseline_price=baseline_price,
baseline_momentum=momentum,
baseline_frequency=frequency,
predicted_direction=direction,
predicted_change_pct=predicted_change,
predicted_price=predicted_price,
confidence=confidence
)
def run_prediction_cycle(self, platform: str, symbol: str,
prediction_window_sec: int = 30) -> Prediction:
"""
Complete prediction cycle:
1. Collect baseline
2. Make prediction
3. Wait for window
4. Validate
"""
print(f"\n{'='*60}")
print(f"๐ฎ PREDICTION CYCLE: {platform.upper()} {symbol}")
print(f"{'='*60}")
# Step 1: Collect baseline
print(f"\n๐ STEP 1: Collecting baseline (10 seconds)...")
prices, momentum, frequency = self.collect_baseline(platform, symbol, 10)
if not prices:
print(" โ Failed to collect baseline data")
return None
print(f" Baseline price: ${prices[-1]:.4f}")
print(f" Momentum: {momentum:+.4f}%/sample")
print(f" Frequency: {frequency:.1f}Hz")
# Step 2: Generate prediction
print(f"\n๐ฏ STEP 2: Generating prediction for next {prediction_window_sec} seconds...")
prediction = self.generate_prediction(platform, symbol, prices, momentum, frequency)
print(f" โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ")
print(f" โ PREDICTION: โ")
print(f" โ Direction: {prediction.predicted_direction:8} โ")
print(f" โ Change: {prediction.predicted_change_pct:+.4f}% โ")
print(f" โ Target: ${prediction.predicted_price:.4f} โ")
print(f" โ Confidence: {prediction.confidence:.1%} โ")
print(f" โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ")
# Step 3: Wait for prediction window
print(f"\nโณ STEP 3: Waiting {prediction_window_sec} seconds for validation...")
for i in range(prediction_window_sec):
current = self.get_price(platform, symbol)
current_change = ((current - prediction.baseline_price) / prediction.baseline_price) * 100
# Progress indicator
bar_len = 30
progress = int((i + 1) / prediction_window_sec * bar_len)
bar = "โ" * progress + "โ" * (bar_len - progress)
direction_icon = "โ" if current_change > 0 else "โ" if current_change < 0 else "โ"
print(f" [{bar}] {i+1}/{prediction_window_sec}s | ${current:.4f} ({current_change:+.4f}%) {direction_icon}", end='\r')
time.sleep(1)
print() # New line after progress
# Step 4: Validate
print(f"\nโ STEP 4: Validating prediction...")
actual_price = self.get_price(platform, symbol)
prediction.validate(actual_price)
# Update tracking
self.predictions.append(prediction)
self.total_predictions += 1
if prediction.direction_correct:
self.correct_predictions += 1
self.accuracy_window.append(1 if prediction.direction_correct else 0)
# Calculate running accuracy
running_accuracy = sum(self.accuracy_window) / len(self.accuracy_window) if self.accuracy_window else 0
print(f"\n โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ")
print(f" โ VALIDATION RESULT: โ")
print(f" โ Predicted: {prediction.predicted_direction:8} ({prediction.predicted_change_pct:+.4f}%) โ")
print(f" โ Actual: {prediction.actual_direction:8} ({prediction.actual_change_pct:+.4f}%) โ")
print(f" โ Direction: {'โ
CORRECT' if prediction.direction_correct else 'โ WRONG':18} โ")
print(f" โ Magnitude: {prediction.magnitude_accuracy:.1%} accurate โ")
print(f" โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ")
print(f"\n๐ RUNNING STATS:")
print(f" Total predictions: {self.total_predictions}")
print(f" Correct: {self.correct_predictions} ({self.correct_predictions/self.total_predictions:.1%})")
print(f" Last {len(self.accuracy_window)} accuracy: {running_accuracy:.1%}")
# Check if we're on the right path
if running_accuracy >= 0.7:
print(f"\n ๐ฏ ON THE RIGHT PATH! Accuracy โฅ70%")
elif running_accuracy >= 0.5:
print(f"\n โ ๏ธ NEEDS IMPROVEMENT. Accuracy 50-70%")
else:
print(f"\n โ MODEL NEEDS RECALIBRATION. Accuracy <50%")
return prediction
def run_validation_session(self, cycles: int = 5):
"""Run multiple prediction cycles to build confidence"""
# ๐ถ COMPREHENSIVE VALIDATION SYMBOLS
symbols = [
# TOP TIER
('binance', 'BTCUSDC'), ('binance', 'ETHUSDC'), ('binance', 'SOLUSDC'),
('binance', 'XRPUSDC'), ('binance', 'ADAUSDC'), ('binance', 'AVAXUSDC'),
# LAYER 2s
('binance', 'ARBUSDC'), ('binance', 'OPUSDC'), ('binance', 'SUIUSDC'),
# DEFI
('binance', 'UNIUSDC'), ('binance', 'LINKUSDC'), ('binance', 'AAVEUSDC'),
# AI
('binance', 'FETUSDC'), ('binance', 'INJUSDC'),
# MEMECOINS
('binance', 'DOGEUSDC'), ('binance', 'PEPEUSDC'), ('binance', 'BONKUSDC'),
]
print("\n" + "="*70)
print("๐ฎ SELF-VALIDATING PREDICTION SESSION")
print("="*70)
print(f"Running {cycles} prediction cycles across {len(symbols)} symbols")
print("Each cycle: 10s baseline + 30s prediction window = 40s")
print(f"Estimated time: {cycles * 40}s ({cycles * 40 / 60:.1f} min)")
print("="*70)
all_predictions = []
for cycle in range(cycles):
print(f"\n{'โ'*70}")
print(f"CYCLE {cycle + 1}/{cycles}")
print(f"{'โ'*70}")
# Rotate through symbols
platform, symbol = symbols[cycle % len(symbols)]
prediction = self.run_prediction_cycle(platform, symbol, 30)
if prediction:
all_predictions.append(prediction)
# Final summary
print("\n" + "="*70)
print("๐ FINAL VALIDATION SUMMARY")
print("="*70)
if all_predictions:
correct = sum(1 for p in all_predictions if p.direction_correct)
accuracy = correct / len(all_predictions)
avg_magnitude_acc = np.mean([p.magnitude_accuracy for p in all_predictions])
avg_confidence = np.mean([p.confidence for p in all_predictions])
print(f"\n Total Predictions: {len(all_predictions)}")
print(f" Direction Accuracy: {correct}/{len(all_predictions)} ({accuracy:.1%})")
print(f" Magnitude Accuracy: {avg_magnitude_acc:.1%}")
print(f" Avg Confidence: {avg_confidence:.1%}")
print(f"\n {'โ'*50}")
print(f" โ {'PREDICTION':10} โ {'ACTUAL':10} โ {'RESULT':10} โ")
print(f" {'โ'*50}")
for p in all_predictions:
result = "โ
CORRECT" if p.direction_correct else "โ WRONG"
print(f" โ {p.predicted_direction:10} โ {p.actual_direction:10} โ {result:10} โ")
print(f" {'โ'*50}")
# Recommendation
print(f"\n๐ฏ RECOMMENDATION:")
if accuracy >= 0.7:
print(f" โ
PREDICTIONS ARE RELIABLE ({accuracy:.0%} accuracy)")
print(f" โ
System is ON THE RIGHT PATH")
print(f" โ
Ready for live trading with confidence")
elif accuracy >= 0.5:
print(f" โ ๏ธ PREDICTIONS NEED IMPROVEMENT ({accuracy:.0%} accuracy)")
print(f" โ ๏ธ Continue validation before trading")
else:
print(f" โ PREDICTIONS ARE UNRELIABLE ({accuracy:.0%} accuracy)")
print(f" โ Model needs recalibration")
print(f" โ Do NOT trade until accuracy improves")
print("\n" + "="*70)
return all_predictions
def main():
print("\n" + "="*70)
print("๐ฏ๐ฎ AUREON SELF-VALIDATING PREDICTION ENGINE ๐ฎ๐ฏ")
print("="*70)
print("\nThis system PREDICTS market movements BEFORE they happen,")
print("then VALIDATES predictions against actual results.")
print("\nOnly when predictions are CONSISTENTLY CORRECT do we trade.")
print("="*70)
predictor = SelfValidatingPredictor()
# Run validation session
predictions = predictor.run_validation_session(cycles=5)
print("\nDone!")
if __name__ == "__main__":
main()
|