increase prediction horizon
This commit is contained in:
@@ -849,7 +849,116 @@ class TradingExecutor:
|
||||
def get_trade_history(self) -> List[TradeRecord]:
|
||||
"""Get trade history"""
|
||||
return self.trade_history.copy()
|
||||
|
||||
|
||||
def export_trades_to_csv(self, filename: Optional[str] = None) -> str:
|
||||
"""Export trade history to CSV file with comprehensive analysis"""
|
||||
import csv
|
||||
from pathlib import Path
|
||||
|
||||
if not self.trade_history:
|
||||
logger.warning("No trades to export")
|
||||
return ""
|
||||
|
||||
# Generate filename if not provided
|
||||
if filename is None:
|
||||
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
filename = f"trade_history_{timestamp}.csv"
|
||||
|
||||
# Ensure .csv extension
|
||||
if not filename.endswith('.csv'):
|
||||
filename += '.csv'
|
||||
|
||||
# Create trades directory if it doesn't exist
|
||||
trades_dir = Path("trades")
|
||||
trades_dir.mkdir(exist_ok=True)
|
||||
filepath = trades_dir / filename
|
||||
|
||||
try:
|
||||
with open(filepath, 'w', newline='', encoding='utf-8') as csvfile:
|
||||
fieldnames = [
|
||||
'symbol', 'side', 'quantity', 'entry_price', 'exit_price',
|
||||
'entry_time', 'exit_time', 'pnl', 'fees', 'confidence',
|
||||
'hold_time_seconds', 'hold_time_minutes', 'leverage',
|
||||
'pnl_percentage', 'net_pnl', 'profit_loss', 'trade_duration',
|
||||
'entry_hour', 'exit_hour', 'day_of_week'
|
||||
]
|
||||
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
|
||||
writer.writeheader()
|
||||
|
||||
total_pnl = 0
|
||||
winning_trades = 0
|
||||
losing_trades = 0
|
||||
|
||||
for trade in self.trade_history:
|
||||
# Calculate additional metrics
|
||||
pnl_percentage = (trade.pnl / trade.entry_price) * 100 if trade.entry_price != 0 else 0
|
||||
net_pnl = trade.pnl - trade.fees
|
||||
profit_loss = "PROFIT" if net_pnl > 0 else "LOSS"
|
||||
trade_duration = trade.exit_time - trade.entry_time
|
||||
hold_time_minutes = trade.hold_time_seconds / 60
|
||||
|
||||
# Track statistics
|
||||
total_pnl += net_pnl
|
||||
if net_pnl > 0:
|
||||
winning_trades += 1
|
||||
else:
|
||||
losing_trades += 1
|
||||
|
||||
writer.writerow({
|
||||
'symbol': trade.symbol,
|
||||
'side': trade.side,
|
||||
'quantity': trade.quantity,
|
||||
'entry_price': trade.entry_price,
|
||||
'exit_price': trade.exit_price,
|
||||
'entry_time': trade.entry_time.strftime('%Y-%m-%d %H:%M:%S'),
|
||||
'exit_time': trade.exit_time.strftime('%Y-%m-%d %H:%M:%S'),
|
||||
'pnl': trade.pnl,
|
||||
'fees': trade.fees,
|
||||
'confidence': trade.confidence,
|
||||
'hold_time_seconds': trade.hold_time_seconds,
|
||||
'hold_time_minutes': hold_time_minutes,
|
||||
'leverage': trade.leverage,
|
||||
'pnl_percentage': pnl_percentage,
|
||||
'net_pnl': net_pnl,
|
||||
'profit_loss': profit_loss,
|
||||
'trade_duration': str(trade_duration),
|
||||
'entry_hour': trade.entry_time.hour,
|
||||
'exit_hour': trade.exit_time.hour,
|
||||
'day_of_week': trade.entry_time.strftime('%A')
|
||||
})
|
||||
|
||||
# Create summary statistics file
|
||||
summary_filename = filename.replace('.csv', '_summary.txt')
|
||||
summary_filepath = trades_dir / summary_filename
|
||||
|
||||
total_trades = len(self.trade_history)
|
||||
win_rate = (winning_trades / total_trades * 100) if total_trades > 0 else 0
|
||||
avg_pnl = total_pnl / total_trades if total_trades > 0 else 0
|
||||
avg_hold_time = sum(t.hold_time_seconds for t in self.trade_history) / total_trades if total_trades > 0 else 0
|
||||
|
||||
with open(summary_filepath, 'w', encoding='utf-8') as f:
|
||||
f.write("TRADE ANALYSIS SUMMARY\n")
|
||||
f.write("=" * 50 + "\n")
|
||||
f.write(f"Total Trades: {total_trades}\n")
|
||||
f.write(f"Winning Trades: {winning_trades}\n")
|
||||
f.write(f"Losing Trades: {losing_trades}\n")
|
||||
f.write(f"Win Rate: {win_rate:.1f}%\n")
|
||||
f.write(f"Total P&L: ${total_pnl:.2f}\n")
|
||||
f.write(f"Average P&L per Trade: ${avg_pnl:.2f}\n")
|
||||
f.write(f"Average Hold Time: {avg_hold_time:.1f} seconds ({avg_hold_time/60:.1f} minutes)\n")
|
||||
f.write(f"Export Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
|
||||
f.write(f"Data File: {filename}\n")
|
||||
|
||||
logger.info(f"📊 Trade history exported to: {filepath}")
|
||||
logger.info(f"📈 Trade summary saved to: {summary_filepath}")
|
||||
logger.info(f"📊 Total Trades: {total_trades} | Win Rate: {win_rate:.1f}% | Total P&L: ${total_pnl:.2f}")
|
||||
|
||||
return str(filepath)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error exporting trades to CSV: {e}")
|
||||
return ""
|
||||
|
||||
def get_daily_stats(self) -> Dict[str, Any]:
|
||||
"""Get daily trading statistics with enhanced fee analysis"""
|
||||
total_pnl = sum(trade.pnl for trade in self.trade_history)
|
||||
|
Reference in New Issue
Block a user