VisualTradingAI / app.py
OmidSakaki's picture
Update app.py
0671748 verified
raw
history blame
22.4 kB
import gradio as gr
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
import io
import base64
from PIL import Image
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import time
import sys
import os
import threading
from datetime import datetime, timedelta
# Set matplotlib backend
plt.switch_backgeround('Agg')
# Create directories and init files
os.makedirs('src/environments', exist_ok=True)
os.makedirs('src/agents', exist_ok=True)
os.makedirs('src/sentiment', exist_ok=True)
os.makedirs('src/visualizers', exist_ok=True)
os.makedirs('src/utils', exist_ok=True)
for dir_path in ['src', 'src/environments', 'src/agents', 'src/sentiment', 'src/visualizers', 'src/utils']:
init_file = os.path.join(dir_path, '__init__.py')
with open(init_file, 'w') as f:
f.write('')
sys.path.append('src')
# Import our custom modules
from src.environments.visual_trading_env import VisualTradingEnvironment
from src.agents.visual_agent import VisualTradingAgent
class RealTimeTradingDemo:
def __init__(self):
self.env = None
self.agent = None
self.current_state = None
self.is_training = False
self.training_complete = False
self.live_trading = False
self.trading_thread = None
self.live_data = []
self.performance_data = []
self.action_history = []
self.initialized = False
self.start_time = None
def initialize_environment(self, initial_balance, risk_level, asset_type):
"""Initialize trading environment"""
try:
print(f"🚀 Initializing Real-Time Trading Environment...")
self.env = VisualTradingEnvironment(
initial_balance=float(initial_balance),
risk_level=risk_level,
asset_type=asset_type
)
self.agent = VisualTradingAgent(
state_dim=(84, 84, 4),
action_dim=4
)
self.current_state = self.env.reset()
self.live_data = []
self.performance_data = []
self.action_history = []
self.training_complete = False
self.live_trading = False
self.initialized = True
self.start_time = datetime.now()
# Initialize live data
self._initialize_live_data()
return "✅ محیط معاملاتی Real-Time راه‌اندازی شد!\n\n🎯 آماده برای شروع آموزش هوش مصنوعی..."
except Exception as e:
error_msg = f"❌ خطا در راه‌اندازی محیط: {str(e)}"
print(error_msg)
return error_msg
def _initialize_live_data(self):
"""Initialize live trading data"""
# Generate realistic initial data
base_price = 100
for i in range(50):
price = base_price + np.random.normal(0, 2)
self.live_data.append({
'timestamp': datetime.now() - timedelta(seconds=50-i),
'price': price,
'action': 0,
'net_worth': self.env.initial_balance if self.env else 10000
})
def train_agent(self, num_episodes):
"""Train the AI agent and show real-time progress"""
if not self.initialized or self.env is None:
yield "❌ لطفا اول محیط را راه‌اندازی کنید!", None
return
self.is_training = True
self.training_complete = False
training_history = []
try:
num_episodes = int(num_episodes)
for episode in range(num_episodes):
state = self.env.reset()
episode_reward = 0.0
done = False
steps = 0
while not done and steps < 100:
action = self.agent.select_action(state)
next_state, reward, done, info = self.env.step(action)
self.agent.store_transition(state, action, reward, next_state, done)
state = next_state
episode_reward += reward
steps += 1
# Update agent
loss = self.agent.update()
training_history.append({
'episode': episode,
'reward': episode_reward,
'net_worth': info['net_worth'],
'loss': loss,
'steps': steps
})
# Create real-time training progress
progress_chart = self._create_training_progress(training_history)
# Update status message
progress_percent = (episode + 1) / num_episodes * 100
status = (
f"🔄 در حال آموزش هوش مصنوعی...\n"
f"📊 پیشرفت: {episode+1}/{num_episodes} ({progress_percent:.1f}%)\n"
f"🎯 Reward این اپیزود: {episode_reward:.3f}\n"
f"💰 ارزش پرتفولیو: ${info['net_worth']:.2f}\n"
f"📉 Loss: {loss:.4f}\n"
f"🎲 Epsilon: {self.agent.epsilon:.3f}"
)
yield status, progress_chart
time.sleep(0.1)
self.is_training = False
self.training_complete = True
# Calculate final metrics
final_reward = np.mean([h['reward'] for h in training_history])
final_net_worth = training_history[-1]['net_worth']
completion_status = (
f"✅ آموزش هوش مصنوعی با موفقیت تکمیل شد!\n\n"
f"🎯 نتایج نهایی:\n"
f"• تعداد اپیزودها: {num_episodes}\n"
f"• میانگین Reward: {final_reward:.3f}\n"
f"• ارزش نهایی پرتفولیو: ${final_net_worth:.2f}\n"
f"• Epsilon نهایی: {self.agent.epsilon:.3f}\n\n"
f"🚀 آماده برای معامله Real-Time!"
)
yield completion_status, self._create_training_progress(training_history)
except Exception as e:
self.is_training = False
error_msg = f"❌ خطا در آموزش: {str(e)}"
print(f"Training error: {e}")
yield error_msg, None
def start_live_trading(self):
"""Start real-time live trading demo"""
if not self.training_complete:
return "❌ لطفا اول آموزش را کامل کنید!", None, None
if self.live_trading:
return "⚠️ معامله Real-Time در حال اجراست!", None, None
self.live_trading = True
self.live_data = []
self.performance_data = []
self.action_history = []
self._initialize_live_data()
# Start live trading in a separate thread
self.trading_thread = threading.Thread(target=self._live_trading_loop)
self.trading_thread.daemon = True
self.trading_thread.start()
return "🎯 معامله Real-Time شروع شد!", self._create_live_chart(), self._create_performance_chart()
def _live_trading_loop(self):
"""Main live trading loop"""
step_count = 0
max_steps = 200 # Stop after 200 steps for demo
while self.live_trading and step_count < max_steps:
try:
# Get AI decision
action = self.agent.select_action(self.current_state)
# Execute action
next_state, reward, done, info = self.env.step(action)
self.current_state = next_state
# Update live data
current_time = datetime.now()
self.live_data.append({
'timestamp': current_time,
'price': info['current_price'],
'action': action,
'net_worth': info['net_worth']
})
# Keep only last 100 data points
if len(self.live_data) > 100:
self.live_data.pop(0)
self.action_history.append({
'step': step_count,
'action': action,
'reward': reward,
'timestamp': current_time
})
step_count += 1
time.sleep(1) # 1 second between steps
except Exception as e:
print(f"Error in live trading: {e}")
break
self.live_trading = False
def get_live_update(self):
"""Get real-time update for the interface"""
if not self.live_trading:
return "🛑 معامله Real-Time متوقف شده", None, None
current_data = self.live_data[-1] if self.live_data else None
if not current_data:
return "📊 در حال آماده‌سازی داده...", None, None
action_names = ["نگهداری", "خرید", "فروش", "بستن"]
action = current_data['action']
action_text = action_names[action]
status = (
f"🎯 معامله Real-Time در حال اجرا...\n"
f"💰 قیمت فعلی: ${current_data['price']:.2f}\n"
f"🎪 اقدام: {action_text}\n"
f"💼 ارزش پرتفولیو: ${current_data['net_worth']:.2f}\n"
f"⏰ آخرین بروزرسانی: {datetime.now().strftime('%H:%M:%S')}"
)
return status, self._create_live_chart(), self._create_performance_chart()
def stop_live_trading(self):
"""Stop the live trading demo"""
self.live_trading = False
if self.trading_thread and self.trading_thread.is_alive():
self.trading_thread.join(timeout=1.0)
final_net_worth = self.live_data[-1]['net_worth'] if self.live_data else self.env.initial_balance
initial_balance = self.env.initial_balance
performance = (
f"🛑 معامله Real-Time متوقف شد\n\n"
f"📈 عملکرد نهایی:\n"
f"• سرمایه اولیه: ${initial_balance:.2f}\n"
f"• سرمایه نهایی: ${final_net_worth:.2f}\n"
f"• سود/زیان: ${final_net_worth - initial_balance:.2f}\n"
f"• درصد تغییر: {((final_net_worth - initial_balance) / initial_balance * 100):.2f}%\n"
f"• تعداد اقدامات: {len(self.action_history)}"
)
return performance, self._create_live_chart(), self._create_performance_chart()
def _create_live_chart(self):
"""Create real-time trading chart"""
if not self.live_data:
fig = go.Figure()
fig.update_layout(
title="📊 نمودار Real-Time - در حال آماده‌سازی...",
height=400
)
return fig
times = [d['timestamp'] for d in self.live_data]
prices = [d['price'] for d in self.live_data]
actions = [d['action'] for d in self.live_data]
fig = go.Figure()
# Price line
fig.add_trace(go.Scatter(
x=times,
y=prices,
mode='lines',
name='قیمت',
line=dict(color='blue', width=3)
))
# Action markers
buy_times = [times[i] for i, action in enumerate(actions) if action == 1]
buy_prices = [prices[i] for i, action in enumerate(actions) if action == 1]
sell_times = [times[i] for i, action in enumerate(actions) if action == 2]
sell_prices = [prices[i] for i, action in enumerate(actions) if action == 2]
close_times = [times[i] for i, action in enumerate(actions) if action == 3]
close_prices = [prices[i] for i, action in enumerate(actions) if action == 3]
if buy_times:
fig.add_trace(go.Scatter(
x=buy_times,
y=buy_prices,
mode='markers',
name='خرید',
marker=dict(color='green', size=10, symbol='triangle-up')
))
if sell_times:
fig.add_trace(go.Scatter(
x=sell_times,
y=sell_prices,
mode='markers',
name='فروش',
marker=dict(color='red', size=10, symbol='triangle-down')
))
if close_times:
fig.add_trace(go.Scatter(
x=close_times,
y=close_prices,
mode='markers',
name='بستن',
marker=dict(color='orange', size=8, symbol='x')
))
fig.update_layout(
title="🎯 نمودار معاملات Real-Time",
xaxis_title="زمان",
yaxis_title="قیمت",
height=400,
showlegend=True,
template="plotly_white"
)
return fig
def _create_performance_chart(self):
"""Create performance chart"""
if not self.live_data:
fig = go.Figure()
fig.update_layout(
title="📈 عملکرد پرتفولیو - در حال آماده‌سازی...",
height=300
)
return fig
times = [d['timestamp'] for d in self.live_data]
net_worths = [d['net_worth'] for d in self.live_data]
fig = go.Figure()
fig.add_trace(go.Scatter(
x=times,
y=net_worths,
mode='lines+markers',
name='ارزش پرتفولیو',
line=dict(color='green', width=3),
marker=dict(size=4)
))
# Add initial balance line
if self.env:
fig.add_hline(y=self.env.initial_balance, line_dash="dash",
line_color="red", annotation_text="سرمایه اولیه")
fig.update_layout(
title="💼 عملکرد پرتفولیو در زمان واقعی",
xaxis_title="زمان",
yaxis_title="ارزش ($)",
height=300,
template="plotly_white"
)
return fig
def _create_training_progress(self, training_history):
"""Create training progress visualization"""
if not training_history:
fig = go.Figure()
fig.update_layout(
title="📊 پیشرفت آموزش - در حال آماده‌سازی...",
height=400
)
return fig
episodes = [h['episode'] for h in training_history]
rewards = [h['reward'] for h in training_history]
net_worths = [h['net_worth'] for h in training_history]
fig = make_subplots(
rows=2, cols=1,
subplot_titles=['📈 Reward اپیزودها', '💰 ارزش پرتفولیو'],
vertical_spacing=0.15
)
# Rewards
fig.add_trace(go.Scatter(
x=episodes, y=rewards, mode='lines+markers',
name='Reward', line=dict(color='blue', width=2),
marker=dict(size=4)
), row=1, col=1)
# Portfolio value
fig.add_trace(go.Scatter(
x=episodes, y=net_worths, mode='lines+markers',
name='Net Worth', line=dict(color='green', width=2),
marker=dict(size=4)
), row=2, col=1)
fig.update_layout(
height=400,
showlegend=True,
title_text="🎯 پیشرفت آموزش هوش مصنوعی",
template="plotly_white"
)
return fig
# Initialize the demo
demo = RealTimeTradingDemo()
# Create Gradio interface
def create_interface():
with gr.Blocks(theme=gr.themes.Soft(), title="Real-Time Trading AI") as interface:
gr.Markdown("""
# 🚀 هوش مصنوعی معامله‌گر Real-Time
**آموزش و اجرای بلادرنگ روی نمودارهای زنده**
*این سیستم ابتدا هوش مصنوعی را آموزش می‌دهد، سپس به صورت Real-Time روی بازار معامله می‌کند*
""")
with gr.Row():
with gr.Column(scale=1):
# Configuration section
gr.Markdown("## ⚙️ پیکربندی سیستم")
with gr.Row():
initial_balance = gr.Slider(
minimum=1000, maximum=50000, value=10000, step=1000,
label="سرمایه اولیه ($)"
)
with gr.Row():
risk_level = gr.Radio(
["Low", "Medium", "High"],
value="Medium",
label="سطح ریسک"
)
with gr.Row():
asset_type = gr.Radio(
["Stock", "Crypto", "Forex"],
value="Stock",
label="نوع دارایی"
)
with gr.Row():
init_btn = gr.Button(
"🚀 راه‌اندازی محیط",
variant="primary"
)
with gr.Row():
init_status = gr.Textbox(
label="وضعیت سیستم",
interactive=False,
lines=3
)
with gr.Column(scale=2):
# Status output
gr.Markdown("## 📊 وضعیت جاری")
status_output = gr.Textbox(
label="وضعیت عملیات",
interactive=False,
lines=4
)
with gr.Row():
gr.Markdown("## 🎓 فاز ۱: آموزش هوش مصنوعی")
with gr.Row():
with gr.Column(scale=1):
num_episodes = gr.Slider(
minimum=10, maximum=100, value=30, step=5,
label="تعداد اپیزودهای آموزش"
)
train_btn = gr.Button(
"🤖 شروع آموزش",
variant="primary",
size="lg"
)
with gr.Column(scale=2):
training_plot = gr.Plot(
label="📈 پیشرفت آموزش"
)
with gr.Row():
gr.Markdown("## 🎯 فاز ۲: معامله Real-Time")
with gr.Row():
with gr.Column(scale=1):
start_btn = gr.Button(
"▶️ شروع معامله Real-Time",
variant="secondary",
size="lg"
)
stop_btn = gr.Button(
"⏹️ توقف معامله",
variant="stop",
size="lg"
)
with gr.Column(scale=1):
update_btn = gr.Button(
"🔄 بروزرسانی لحظه‌ای",
variant="secondary",
size="lg"
)
with gr.Row():
with gr.Column(scale=1):
live_chart = gr.Plot(
label="📊 نمودار معاملات Real-Time"
)
with gr.Column(scale=1):
performance_chart = gr.Plot(
label="💼 عملکرد پرتفولیو"
)
# Event handlers
init_btn.click(
demo.initialize_environment,
inputs=[initial_balance, risk_level, asset_type],
outputs=[init_status]
)
train_btn.click(
demo.train_agent,
inputs=[num_episodes],
outputs=[status_output, training_plot]
)
start_btn.click(
demo.start_live_trading,
inputs=[],
outputs=[status_output, live_chart, performance_chart]
)
update_btn.click(
demo.get_live_update,
inputs=[],
outputs=[status_output, live_chart, performance_chart]
)
stop_btn.click(
demo.stop_live_trading,
inputs=[],
outputs=[status_output, live_chart, performance_chart]
)
gr.Markdown("""
## 🧠 نحوه کار سیستم:
1. **راه‌اندازی محیط**: تنظیم پارامترهای اولیه
2. **آموزش هوش مصنوعی**: آموزش مدل با ۳۰ اپیزود
3. **معامله Real-Time**: اجرای بلادرنگ روی نمودار زنده
4. **مانیتورینگ**: مشاهده عملکرد لحظه‌ای
*توسعه داده شده توسط Omid Sakaki - 2024*
""")
return interface
# Create and launch interface
if __name__ == "__main__":
print("🚀 Starting Real-Time Trading AI Demo...")
interface = create_interface()
interface.launch(
server_name="0.0.0.0",
server_port=7860,
share=False
)