test_stats_fix.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. #!/usr/bin/env python3
  2. """
  3. Test script to verify the stats command fix
  4. """
  5. import sys
  6. from pathlib import Path
  7. # Add the project root and src directory to the path
  8. project_root = Path(__file__).parent.parent
  9. sys.path.insert(0, str(project_root))
  10. sys.path.insert(0, str(project_root / 'src'))
  11. from src.stats import TradingStats
  12. def test_stats_fix():
  13. """Test that stats work with no trades and with trades."""
  14. print("🧪 Testing Stats Fix")
  15. print("=" * 40)
  16. try:
  17. # Test 1: New stats instance (no trades)
  18. print("📊 Test 1: Empty stats (no trades)")
  19. stats = TradingStats(stats_file="test_stats.json")
  20. # Try to format stats message
  21. message = stats.format_stats_message(1000.0)
  22. print("✅ Empty stats message generated successfully")
  23. print(f"📝 Message length: {len(message)} characters")
  24. # Test 2: Performance stats with no trades
  25. print("\n📊 Test 2: Performance stats with no trades")
  26. perf_stats = stats.get_performance_stats()
  27. # Check that expectancy key exists
  28. if 'expectancy' in perf_stats:
  29. print(f"✅ Expectancy key exists: {perf_stats['expectancy']}")
  30. else:
  31. print("❌ Expectancy key missing!")
  32. return False
  33. # Check all required keys
  34. required_keys = [
  35. 'win_rate', 'profit_factor', 'avg_win', 'avg_loss',
  36. 'largest_win', 'largest_loss', 'consecutive_wins',
  37. 'consecutive_losses', 'total_wins', 'total_losses', 'expectancy'
  38. ]
  39. missing_keys = [key for key in required_keys if key not in perf_stats]
  40. if missing_keys:
  41. print(f"❌ Missing keys: {missing_keys}")
  42. return False
  43. else:
  44. print("✅ All required performance keys present")
  45. # Test 3: Add some sample trades
  46. print("\n📊 Test 3: Stats with sample trades")
  47. stats.record_trade("BTC/USDC:USDC", "buy", 0.001, 45000.0, "test1")
  48. stats.record_trade("BTC/USDC:USDC", "sell", 0.001, 46000.0, "test2")
  49. # Try to format stats message with trades
  50. message_with_trades = stats.format_stats_message(1010.0)
  51. print("✅ Stats message with trades generated successfully")
  52. # Test performance stats with trades
  53. perf_stats_with_trades = stats.get_performance_stats()
  54. print(f"✅ Win rate: {perf_stats_with_trades['win_rate']:.1f}%")
  55. print(f"✅ Expectancy: ${perf_stats_with_trades['expectancy']:.2f}")
  56. # Test 4: Error handling
  57. print("\n📊 Test 4: Error handling")
  58. try:
  59. # This should not fail due to the safe .get() access
  60. comprehensive_stats = stats.get_comprehensive_stats(1010.0)
  61. print("✅ Comprehensive stats generated successfully")
  62. except Exception as e:
  63. print(f"❌ Comprehensive stats failed: {e}")
  64. return False
  65. print("\n🎉 All stats tests passed!")
  66. print("\n📝 Sample stats message:")
  67. print("-" * 40)
  68. print(message[:200] + "..." if len(message) > 200 else message)
  69. print("-" * 40)
  70. # Clean up test file
  71. import os
  72. try:
  73. os.remove("test_stats.json")
  74. print("\n🧹 Test file cleaned up")
  75. except:
  76. pass
  77. return True
  78. except Exception as e:
  79. print(f"💥 Test failed with error: {e}")
  80. import traceback
  81. traceback.print_exc()
  82. return False
  83. if __name__ == "__main__":
  84. success = test_stats_fix()
  85. if success:
  86. print("\n🎉 Stats fix test PASSED!")
  87. print("\n✅ The /stats command should now work properly")
  88. sys.exit(0)
  89. else:
  90. print("\n💥 Stats fix test FAILED!")
  91. sys.exit(1)