Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -11,6 +11,7 @@ from plotly.subplots import make_subplots
|
|
| 11 |
import time
|
| 12 |
import sys
|
| 13 |
import os
|
|
|
|
| 14 |
|
| 15 |
# Set matplotlib backend
|
| 16 |
plt.switch_backend('Agg')
|
|
@@ -30,42 +31,64 @@ for dir_path in ['src', 'src/environments', 'src/agents', 'src/sentiment', 'src/
|
|
| 30 |
sys.path.append('src')
|
| 31 |
|
| 32 |
# Import our custom modules
|
| 33 |
-
from src.environments.
|
| 34 |
-
from src.agents.
|
| 35 |
from src.visualizers.chart_renderer import ChartRenderer
|
|
|
|
| 36 |
|
| 37 |
-
class
|
| 38 |
def __init__(self):
|
| 39 |
self.env = None
|
| 40 |
self.agent = None
|
|
|
|
| 41 |
self.current_state = None
|
| 42 |
self.is_training = False
|
| 43 |
self.episode_history = []
|
|
|
|
| 44 |
self.chart_renderer = ChartRenderer()
|
| 45 |
self.initialized = False
|
|
|
|
| 46 |
|
| 47 |
-
def initialize_environment(self, initial_balance, risk_level, asset_type):
|
| 48 |
-
"""Initialize trading environment"""
|
| 49 |
try:
|
| 50 |
-
print(f"Initializing
|
| 51 |
|
| 52 |
-
self.
|
|
|
|
| 53 |
initial_balance=float(initial_balance),
|
| 54 |
risk_level=risk_level,
|
| 55 |
-
asset_type=asset_type
|
|
|
|
|
|
|
| 56 |
)
|
| 57 |
|
| 58 |
-
# Initialize
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
state_dim=(84, 84, 4),
|
| 61 |
-
action_dim=4
|
|
|
|
| 62 |
)
|
| 63 |
|
| 64 |
self.current_state = self.env.reset()
|
| 65 |
self.episode_history = []
|
|
|
|
| 66 |
self.initialized = True
|
| 67 |
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
except Exception as e:
|
| 71 |
error_msg = f"❌ Error initializing environment: {str(e)}"
|
|
@@ -73,21 +96,46 @@ class TradingAIDemo:
|
|
| 73 |
return error_msg
|
| 74 |
|
| 75 |
def run_single_step(self, action_choice):
|
| 76 |
-
"""Run a single step
|
| 77 |
if not self.initialized or self.env is None or self.agent is None:
|
| 78 |
-
return None, None, None, "⚠️ Please initialize environment first!"
|
| 79 |
|
| 80 |
try:
|
| 81 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
if action_choice == "AI Decision":
|
| 83 |
-
action = self.agent.select_action(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
action_source = "AI"
|
| 85 |
else:
|
| 86 |
action_mapping = {"Hold": 0, "Buy": 1, "Sell": 2, "Close": 3}
|
| 87 |
action = action_mapping[action_choice]
|
| 88 |
action_source = "Manual"
|
| 89 |
|
| 90 |
-
print(f"Executing action: {action} ({action_source})")
|
| 91 |
|
| 92 |
# Execute action
|
| 93 |
next_state, reward, done, info = self.env.step(action)
|
|
@@ -102,7 +150,9 @@ class TradingAIDemo:
|
|
| 102 |
'balance': info['balance'],
|
| 103 |
'position': info['position_size'],
|
| 104 |
'price': info['current_price'],
|
| 105 |
-
'action_source': action_source
|
|
|
|
|
|
|
| 106 |
}
|
| 107 |
self.episode_history.append(history_entry)
|
| 108 |
|
|
@@ -110,33 +160,35 @@ class TradingAIDemo:
|
|
| 110 |
price_chart = self.create_price_chart(info)
|
| 111 |
performance_chart = self.create_performance_chart()
|
| 112 |
action_chart = self.create_action_chart()
|
|
|
|
| 113 |
|
| 114 |
# Create status message
|
| 115 |
action_names = ["Hold", "Buy", "Sell", "Close"]
|
|
|
|
|
|
|
| 116 |
status = (
|
| 117 |
f"✅ Step {info['step']} Completed!\n"
|
| 118 |
f"• Action: {action_names[action]} ({action_source})\n"
|
| 119 |
f"• Reward: {reward:.3f}\n"
|
| 120 |
f"• Net Worth: ${info['net_worth']:.2f}\n"
|
| 121 |
-
f"•
|
| 122 |
-
f"•
|
| 123 |
-
f"• Current Price: ${info['current_price']:.2f}"
|
| 124 |
)
|
| 125 |
|
| 126 |
if done:
|
| 127 |
status += "\n🎯 Episode Completed!"
|
| 128 |
|
| 129 |
-
return price_chart, performance_chart, action_chart, status
|
| 130 |
|
| 131 |
except Exception as e:
|
| 132 |
error_msg = f"❌ Error during step execution: {str(e)}"
|
| 133 |
print(error_msg)
|
| 134 |
-
return None, None, None, error_msg
|
| 135 |
|
| 136 |
def run_episode(self, num_steps=20):
|
| 137 |
-
"""Run a complete episode"""
|
| 138 |
if not self.initialized or self.env is None or self.agent is None:
|
| 139 |
-
return None, None, None, "⚠️ Please initialize environment first!"
|
| 140 |
|
| 141 |
try:
|
| 142 |
# Reset environment for new episode
|
|
@@ -147,13 +199,27 @@ class TradingAIDemo:
|
|
| 147 |
print(f"Starting episode with {num_steps} steps...")
|
| 148 |
|
| 149 |
for step in range(num_steps):
|
| 150 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
next_state, reward, done, info = self.env.step(action)
|
| 152 |
self.current_state = next_state
|
| 153 |
total_reward += reward
|
| 154 |
|
| 155 |
-
# Store experience
|
| 156 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
|
| 158 |
self.episode_history.append({
|
| 159 |
'step': step,
|
|
@@ -161,6 +227,7 @@ class TradingAIDemo:
|
|
| 161 |
'reward': reward,
|
| 162 |
'net_worth': info['net_worth'],
|
| 163 |
'price': info['current_price'],
|
|
|
|
| 164 |
'action_source': 'AI'
|
| 165 |
})
|
| 166 |
|
|
@@ -174,6 +241,7 @@ class TradingAIDemo:
|
|
| 174 |
price_chart = self.create_price_chart(info)
|
| 175 |
performance_chart = self.create_performance_chart()
|
| 176 |
action_chart = self.create_action_chart()
|
|
|
|
| 177 |
|
| 178 |
# Calculate performance metrics
|
| 179 |
initial_balance = self.env.initial_balance
|
|
@@ -182,26 +250,58 @@ class TradingAIDemo:
|
|
| 182 |
if initial_balance > 0:
|
| 183 |
total_return = (final_net_worth - initial_balance) / initial_balance * 100
|
| 184 |
|
|
|
|
|
|
|
|
|
|
| 185 |
summary = (
|
| 186 |
f"🎯 Episode Completed!\n"
|
| 187 |
f"• Total Steps: {len(self.episode_history)}\n"
|
| 188 |
f"• Total Reward: {total_reward:.2f}\n"
|
| 189 |
f"• Final Net Worth: ${final_net_worth:.2f}\n"
|
| 190 |
f"• Total Return: {total_return:.2f}%\n"
|
|
|
|
| 191 |
f"• Total Trades: {info['total_trades']}"
|
| 192 |
)
|
| 193 |
|
| 194 |
-
return price_chart, performance_chart, action_chart, summary
|
| 195 |
|
| 196 |
except Exception as e:
|
| 197 |
error_msg = f"❌ Error during episode: {str(e)}"
|
| 198 |
print(error_msg)
|
| 199 |
-
return None, None, None, error_msg
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
|
| 201 |
def train_agent(self, num_episodes, learning_rate):
|
| 202 |
-
"""Train the AI agent"""
|
| 203 |
if not self.initialized or self.env is None:
|
| 204 |
-
yield None, "⚠️ Please initialize environment first!"
|
| 205 |
return
|
| 206 |
|
| 207 |
self.is_training = True
|
|
@@ -216,9 +316,26 @@ class TradingAIDemo:
|
|
| 216 |
steps = 0
|
| 217 |
|
| 218 |
while not done and steps < 100:
|
| 219 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
next_state, reward, done, info = self.env.step(action)
|
| 221 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
state = next_state
|
| 223 |
episode_reward += reward
|
| 224 |
steps += 1
|
|
@@ -270,9 +387,8 @@ class TradingAIDemo:
|
|
| 270 |
yield None, error_msg
|
| 271 |
|
| 272 |
def create_price_chart(self, info):
|
| 273 |
-
"""Create price chart with actions"""
|
| 274 |
if not self.episode_history:
|
| 275 |
-
# Return empty chart with message
|
| 276 |
fig = go.Figure()
|
| 277 |
fig.update_layout(
|
| 278 |
title="Price Chart - No Data Available",
|
|
@@ -285,6 +401,7 @@ class TradingAIDemo:
|
|
| 285 |
|
| 286 |
prices = [h['price'] for h in self.episode_history]
|
| 287 |
actions = [h['action'] for h in self.episode_history]
|
|
|
|
| 288 |
|
| 289 |
fig = go.Figure()
|
| 290 |
|
|
@@ -297,43 +414,40 @@ class TradingAIDemo:
|
|
| 297 |
line=dict(color='blue', width=3)
|
| 298 |
))
|
| 299 |
|
| 300 |
-
# Action markers
|
| 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 |
-
marker=dict(color='orange', size=10, symbol='x',
|
| 332 |
-
line=dict(width=2, color='darkorange'))
|
| 333 |
-
))
|
| 334 |
|
| 335 |
fig.update_layout(
|
| 336 |
-
title="Price Chart with Trading Actions",
|
| 337 |
xaxis_title="Step",
|
| 338 |
yaxis_title="Price",
|
| 339 |
height=350,
|
|
@@ -429,6 +543,68 @@ class TradingAIDemo:
|
|
| 429 |
|
| 430 |
return fig
|
| 431 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 432 |
def create_training_progress(self, training_history):
|
| 433 |
"""Create training progress visualization"""
|
| 434 |
if not training_history:
|
|
@@ -496,48 +672,60 @@ class TradingAIDemo:
|
|
| 496 |
return fig
|
| 497 |
|
| 498 |
# Initialize the demo
|
| 499 |
-
demo =
|
| 500 |
|
| 501 |
# Create Gradio interface
|
| 502 |
def create_interface():
|
| 503 |
-
with gr.Blocks(theme=gr.themes.Soft(), title="
|
| 504 |
gr.Markdown("""
|
| 505 |
-
# 🚀
|
| 506 |
-
**هوش مصنوعی
|
| 507 |
|
| 508 |
-
*این
|
| 509 |
""")
|
| 510 |
|
| 511 |
with gr.Row():
|
| 512 |
with gr.Column(scale=1):
|
| 513 |
# Configuration section
|
| 514 |
-
gr.Markdown("## ⚙️ پیکربندی
|
| 515 |
|
| 516 |
with gr.Row():
|
| 517 |
initial_balance = gr.Slider(
|
| 518 |
minimum=1000, maximum=50000, value=10000, step=1000,
|
| 519 |
-
label="موجودی اولیه ($)", info="میزان سرمایه اولیه
|
| 520 |
)
|
| 521 |
|
| 522 |
with gr.Row():
|
| 523 |
risk_level = gr.Radio(
|
| 524 |
["Low", "Medium", "High"],
|
| 525 |
value="Medium",
|
| 526 |
-
label="سطح ریسک"
|
| 527 |
-
info="سطح ریسک پذیری در معاملات"
|
| 528 |
)
|
| 529 |
|
| 530 |
with gr.Row():
|
| 531 |
asset_type = gr.Radio(
|
| 532 |
["Stock", "Crypto", "Forex"],
|
| 533 |
-
value="
|
| 534 |
-
label="نوع دارایی"
|
| 535 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 536 |
)
|
| 537 |
|
| 538 |
with gr.Row():
|
| 539 |
init_btn = gr.Button(
|
| 540 |
-
"🚀 راهاندازی
|
| 541 |
variant="primary",
|
| 542 |
size="lg"
|
| 543 |
)
|
|
@@ -546,8 +734,7 @@ def create_interface():
|
|
| 546 |
init_status = gr.Textbox(
|
| 547 |
label="وضعیت راهاندازی",
|
| 548 |
interactive=False,
|
| 549 |
-
|
| 550 |
-
lines=2
|
| 551 |
)
|
| 552 |
|
| 553 |
with gr.Column(scale=2):
|
|
@@ -556,8 +743,7 @@ def create_interface():
|
|
| 556 |
status_output = gr.Textbox(
|
| 557 |
label="وضعیت اجرا",
|
| 558 |
interactive=False,
|
| 559 |
-
|
| 560 |
-
lines=4
|
| 561 |
)
|
| 562 |
|
| 563 |
with gr.Row():
|
|
@@ -569,7 +755,7 @@ def create_interface():
|
|
| 569 |
["AI Decision", "Buy", "Sell", "Hold", "Close"],
|
| 570 |
value="AI Decision",
|
| 571 |
label="انتخاب اقدام",
|
| 572 |
-
info="AI Decision: ت
|
| 573 |
)
|
| 574 |
|
| 575 |
with gr.Row():
|
|
@@ -586,6 +772,13 @@ def create_interface():
|
|
| 586 |
variant="secondary",
|
| 587 |
size="lg"
|
| 588 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 589 |
|
| 590 |
with gr.Row():
|
| 591 |
# Visualization outputs
|
|
@@ -604,6 +797,11 @@ def create_interface():
|
|
| 604 |
action_chart = gr.Plot(
|
| 605 |
label="🎯 توزیع اقدامات"
|
| 606 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 607 |
|
| 608 |
with gr.Row():
|
| 609 |
gr.Markdown("## 🎓 آموزش هوش مصنوعی")
|
|
@@ -612,18 +810,16 @@ def create_interface():
|
|
| 612 |
with gr.Column(scale=1):
|
| 613 |
num_episodes = gr.Slider(
|
| 614 |
minimum=10, maximum=200, value=50, step=10,
|
| 615 |
-
label="تعداد اپیزودهای آموزش"
|
| 616 |
-
info="تعداد دورههای آموزشی"
|
| 617 |
)
|
| 618 |
|
| 619 |
learning_rate = gr.Slider(
|
| 620 |
minimum=0.0001, maximum=0.01, value=0.001, step=0.0001,
|
| 621 |
-
label="نرخ یادگیری"
|
| 622 |
-
info="سرعت یادگیری الگوریتم"
|
| 623 |
)
|
| 624 |
|
| 625 |
train_btn = gr.Button(
|
| 626 |
-
"🤖 شروع آموزش",
|
| 627 |
variant="primary",
|
| 628 |
size="lg"
|
| 629 |
)
|
|
@@ -636,60 +832,65 @@ def create_interface():
|
|
| 636 |
training_status = gr.Textbox(
|
| 637 |
label="وضعیت آموزش",
|
| 638 |
interactive=False,
|
| 639 |
-
placeholder="وضعیت آموزش اینجا نمایش داده میشود...",
|
| 640 |
lines=3
|
| 641 |
)
|
| 642 |
|
| 643 |
with gr.Row():
|
| 644 |
-
gr.Markdown("## 🧠 معماری هوش مصنوعی")
|
| 645 |
|
| 646 |
with gr.Row():
|
| 647 |
with gr.Column(scale=1):
|
| 648 |
gr.Markdown("""
|
| 649 |
-
**🎯
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 650 |
- تحلیل تصاویر نمودارهای قیمت
|
| 651 |
- تشخیص الگوهای تکنیکال
|
| 652 |
- استخراج ویژگیهای بصری
|
| 653 |
- ورودی: تصاویر 84x84 پیکسل
|
| 654 |
-
|
| 655 |
-
**🤖 Reinforcement Learning:**
|
| 656 |
-
- الگوریتم Deep Q-Network (DQN)
|
| 657 |
-
- یادگیری از طریق تعامل با محیط
|
| 658 |
-
- بهینهسازی تصمیمهای معاملاتی
|
| 659 |
-
- تجربه replay برای یادگیری پایدار
|
| 660 |
""")
|
| 661 |
|
| 662 |
with gr.Column(scale=1):
|
| 663 |
gr.Markdown("""
|
| 664 |
-
**
|
| 665 |
-
-
|
| 666 |
-
-
|
| 667 |
-
-
|
| 668 |
-
-
|
| 669 |
|
| 670 |
-
**
|
| 671 |
-
-
|
| 672 |
-
-
|
| 673 |
-
-
|
| 674 |
""")
|
| 675 |
|
| 676 |
# Event handlers
|
| 677 |
init_btn.click(
|
| 678 |
demo.initialize_environment,
|
| 679 |
-
inputs=[initial_balance, risk_level, asset_type],
|
| 680 |
outputs=[init_status]
|
| 681 |
)
|
| 682 |
|
| 683 |
step_btn.click(
|
| 684 |
demo.run_single_step,
|
| 685 |
inputs=[action_choice],
|
| 686 |
-
outputs=[price_chart, performance_chart, action_chart, status_output]
|
| 687 |
)
|
| 688 |
|
| 689 |
episode_btn.click(
|
| 690 |
demo.run_episode,
|
| 691 |
inputs=[],
|
| 692 |
-
outputs=[price_chart, performance_chart, action_chart, status_output]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 693 |
)
|
| 694 |
|
| 695 |
train_btn.click(
|
|
@@ -699,45 +900,41 @@ def create_interface():
|
|
| 699 |
)
|
| 700 |
|
| 701 |
gr.Markdown("""
|
| 702 |
-
## 🏗 جزئیات فنی
|
| 703 |
-
|
| 704 |
-
**🎯
|
| 705 |
-
- **
|
| 706 |
-
- **
|
| 707 |
-
- **
|
| 708 |
-
|
| 709 |
-
|
| 710 |
-
**
|
| 711 |
-
- **یاد
|
| 712 |
-
- **
|
| 713 |
-
- **
|
| 714 |
-
|
| 715 |
-
|
| 716 |
-
|
| 717 |
-
|
| 718 |
-
-
|
| 719 |
-
-
|
| 720 |
-
|
| 721 |
-
|
| 722 |
-
- آنالیز جامع عملکرد
|
| 723 |
-
|
| 724 |
-
*توسعه داده شده توسط Omid Sakaki - 2024*
|
| 725 |
""")
|
| 726 |
|
| 727 |
return interface
|
| 728 |
|
| 729 |
# Create and launch interface
|
| 730 |
if __name__ == "__main__":
|
| 731 |
-
print("🚀 Starting
|
| 732 |
-
print("
|
| 733 |
|
| 734 |
interface = create_interface()
|
| 735 |
|
| 736 |
-
print("✅
|
| 737 |
print("🌐 Starting server on http://0.0.0.0:7860")
|
| 738 |
-
print("📱
|
| 739 |
|
| 740 |
-
# Launch with better configuration
|
| 741 |
interface.launch(
|
| 742 |
server_name="0.0.0.0",
|
| 743 |
server_port=7860,
|
|
|
|
| 11 |
import time
|
| 12 |
import sys
|
| 13 |
import os
|
| 14 |
+
from datetime import datetime
|
| 15 |
|
| 16 |
# Set matplotlib backend
|
| 17 |
plt.switch_backend('Agg')
|
|
|
|
| 31 |
sys.path.append('src')
|
| 32 |
|
| 33 |
# Import our custom modules
|
| 34 |
+
from src.environments.advanced_trading_env import AdvancedTradingEnvironment
|
| 35 |
+
from src.agents.advanced_agent import AdvancedTradingAgent
|
| 36 |
from src.visualizers.chart_renderer import ChartRenderer
|
| 37 |
+
from src.sentiment.twitter_analyzer import AdvancedSentimentAnalyzer
|
| 38 |
|
| 39 |
+
class ProfessionalTradingAIDemo:
|
| 40 |
def __init__(self):
|
| 41 |
self.env = None
|
| 42 |
self.agent = None
|
| 43 |
+
self.sentiment_analyzer = AdvancedSentimentAnalyzer()
|
| 44 |
self.current_state = None
|
| 45 |
self.is_training = False
|
| 46 |
self.episode_history = []
|
| 47 |
+
self.sentiment_history = []
|
| 48 |
self.chart_renderer = ChartRenderer()
|
| 49 |
self.initialized = False
|
| 50 |
+
self.use_sentiment = True
|
| 51 |
|
| 52 |
+
def initialize_environment(self, initial_balance, risk_level, asset_type, use_sentiment, sentiment_influence):
|
| 53 |
+
"""Initialize professional trading environment with sentiment analysis"""
|
| 54 |
try:
|
| 55 |
+
print(f"Initializing professional trading environment...")
|
| 56 |
|
| 57 |
+
self.use_sentiment = use_sentiment
|
| 58 |
+
self.env = AdvancedTradingEnvironment(
|
| 59 |
initial_balance=float(initial_balance),
|
| 60 |
risk_level=risk_level,
|
| 61 |
+
asset_type=asset_type,
|
| 62 |
+
use_sentiment=use_sentiment,
|
| 63 |
+
sentiment_influence=float(sentiment_influence)
|
| 64 |
)
|
| 65 |
|
| 66 |
+
# Initialize sentiment analyzer if needed
|
| 67 |
+
if use_sentiment:
|
| 68 |
+
sentiment_loaded = self.sentiment_analyzer.initialize_models()
|
| 69 |
+
if not sentiment_loaded:
|
| 70 |
+
return "❌ Failed to load sentiment analysis models. Please check internet connection."
|
| 71 |
+
|
| 72 |
+
# Initialize advanced agent
|
| 73 |
+
self.agent = AdvancedTradingAgent(
|
| 74 |
state_dim=(84, 84, 4),
|
| 75 |
+
action_dim=4,
|
| 76 |
+
use_sentiment=use_sentiment
|
| 77 |
)
|
| 78 |
|
| 79 |
self.current_state = self.env.reset()
|
| 80 |
self.episode_history = []
|
| 81 |
+
self.sentiment_history = []
|
| 82 |
self.initialized = True
|
| 83 |
|
| 84 |
+
status_msg = "✅ Professional Trading Environment Initialized!"
|
| 85 |
+
if use_sentiment:
|
| 86 |
+
status_msg += f"\n🎯 Sentiment Analysis: ACTIVE (Influence: {sentiment_influence})"
|
| 87 |
+
status_msg += f"\n📊 Influencers: {len(self.sentiment_analyzer.influencers)} accounts monitored"
|
| 88 |
+
else:
|
| 89 |
+
status_msg += "\n🎯 Sentiment Analysis: DISABLED"
|
| 90 |
+
|
| 91 |
+
return status_msg
|
| 92 |
|
| 93 |
except Exception as e:
|
| 94 |
error_msg = f"❌ Error initializing environment: {str(e)}"
|
|
|
|
| 96 |
return error_msg
|
| 97 |
|
| 98 |
def run_single_step(self, action_choice):
|
| 99 |
+
"""Run a single step with sentiment analysis"""
|
| 100 |
if not self.initialized or self.env is None or self.agent is None:
|
| 101 |
+
return None, None, None, None, "⚠️ Please initialize environment first!"
|
| 102 |
|
| 103 |
try:
|
| 104 |
+
# Get current sentiment if enabled
|
| 105 |
+
current_sentiment = 0.5
|
| 106 |
+
sentiment_confidence = 0.0
|
| 107 |
+
sentiment_data = None
|
| 108 |
+
sentiment_analysis = None
|
| 109 |
+
|
| 110 |
+
if self.use_sentiment:
|
| 111 |
+
sentiment_analysis = self.env.get_sentiment_analysis()
|
| 112 |
+
current_sentiment = sentiment_analysis.get('current_sentiment', 0.5)
|
| 113 |
+
sentiment_confidence = sentiment_analysis.get('sentiment_confidence', 0.0)
|
| 114 |
+
|
| 115 |
+
# Update sentiment history
|
| 116 |
+
self.sentiment_history.append({
|
| 117 |
+
'step': len(self.episode_history),
|
| 118 |
+
'sentiment': current_sentiment,
|
| 119 |
+
'confidence': sentiment_confidence,
|
| 120 |
+
'timestamp': datetime.now()
|
| 121 |
+
})
|
| 122 |
+
if len(self.sentiment_history) > 50:
|
| 123 |
+
self.sentiment_history.pop(0)
|
| 124 |
+
|
| 125 |
+
# Select action with sentiment consideration
|
| 126 |
if action_choice == "AI Decision":
|
| 127 |
+
action = self.agent.select_action(
|
| 128 |
+
self.current_state,
|
| 129 |
+
current_sentiment,
|
| 130 |
+
sentiment_confidence
|
| 131 |
+
)
|
| 132 |
action_source = "AI"
|
| 133 |
else:
|
| 134 |
action_mapping = {"Hold": 0, "Buy": 1, "Sell": 2, "Close": 3}
|
| 135 |
action = action_mapping[action_choice]
|
| 136 |
action_source = "Manual"
|
| 137 |
|
| 138 |
+
print(f"Executing action: {action} ({action_source}) | Sentiment: {current_sentiment:.3f}")
|
| 139 |
|
| 140 |
# Execute action
|
| 141 |
next_state, reward, done, info = self.env.step(action)
|
|
|
|
| 150 |
'balance': info['balance'],
|
| 151 |
'position': info['position_size'],
|
| 152 |
'price': info['current_price'],
|
| 153 |
+
'action_source': action_source,
|
| 154 |
+
'sentiment': current_sentiment,
|
| 155 |
+
'sentiment_confidence': sentiment_confidence
|
| 156 |
}
|
| 157 |
self.episode_history.append(history_entry)
|
| 158 |
|
|
|
|
| 160 |
price_chart = self.create_price_chart(info)
|
| 161 |
performance_chart = self.create_performance_chart()
|
| 162 |
action_chart = self.create_action_chart()
|
| 163 |
+
sentiment_chart = self.create_sentiment_chart()
|
| 164 |
|
| 165 |
# Create status message
|
| 166 |
action_names = ["Hold", "Buy", "Sell", "Close"]
|
| 167 |
+
sentiment_label = "🔴 Bearish" if current_sentiment < 0.4 else "🟡 Neutral" if current_sentiment < 0.6 else "🟢 Bullish"
|
| 168 |
+
|
| 169 |
status = (
|
| 170 |
f"✅ Step {info['step']} Completed!\n"
|
| 171 |
f"• Action: {action_names[action]} ({action_source})\n"
|
| 172 |
f"• Reward: {reward:.3f}\n"
|
| 173 |
f"• Net Worth: ${info['net_worth']:.2f}\n"
|
| 174 |
+
f"• Market Sentiment: {sentiment_label} ({current_sentiment:.3f})\n"
|
| 175 |
+
f"• Sentiment Confidence: {sentiment_confidence:.1%}"
|
|
|
|
| 176 |
)
|
| 177 |
|
| 178 |
if done:
|
| 179 |
status += "\n🎯 Episode Completed!"
|
| 180 |
|
| 181 |
+
return price_chart, performance_chart, action_chart, sentiment_chart, status
|
| 182 |
|
| 183 |
except Exception as e:
|
| 184 |
error_msg = f"❌ Error during step execution: {str(e)}"
|
| 185 |
print(error_msg)
|
| 186 |
+
return None, None, None, None, error_msg
|
| 187 |
|
| 188 |
def run_episode(self, num_steps=20):
|
| 189 |
+
"""Run a complete episode with sentiment analysis"""
|
| 190 |
if not self.initialized or self.env is None or self.agent is None:
|
| 191 |
+
return None, None, None, None, "⚠️ Please initialize environment first!"
|
| 192 |
|
| 193 |
try:
|
| 194 |
# Reset environment for new episode
|
|
|
|
| 199 |
print(f"Starting episode with {num_steps} steps...")
|
| 200 |
|
| 201 |
for step in range(num_steps):
|
| 202 |
+
# Get current sentiment
|
| 203 |
+
current_sentiment = 0.5
|
| 204 |
+
sentiment_confidence = 0.0
|
| 205 |
+
|
| 206 |
+
if self.use_sentiment:
|
| 207 |
+
sentiment_info = self.env.get_sentiment_analysis()
|
| 208 |
+
current_sentiment = sentiment_info.get('current_sentiment', 0.5)
|
| 209 |
+
sentiment_confidence = sentiment_info.get('sentiment_confidence', 0.0)
|
| 210 |
+
|
| 211 |
+
# Select action with sentiment
|
| 212 |
+
action = self.agent.select_action(self.current_state, current_sentiment, sentiment_confidence)
|
| 213 |
next_state, reward, done, info = self.env.step(action)
|
| 214 |
self.current_state = next_state
|
| 215 |
total_reward += reward
|
| 216 |
|
| 217 |
+
# Store experience with sentiment data
|
| 218 |
+
sentiment_data = {
|
| 219 |
+
'sentiment': current_sentiment,
|
| 220 |
+
'confidence': sentiment_confidence
|
| 221 |
+
}
|
| 222 |
+
self.agent.store_transition(self.current_state, action, reward, next_state, done, sentiment_data)
|
| 223 |
|
| 224 |
self.episode_history.append({
|
| 225 |
'step': step,
|
|
|
|
| 227 |
'reward': reward,
|
| 228 |
'net_worth': info['net_worth'],
|
| 229 |
'price': info['current_price'],
|
| 230 |
+
'sentiment': current_sentiment,
|
| 231 |
'action_source': 'AI'
|
| 232 |
})
|
| 233 |
|
|
|
|
| 241 |
price_chart = self.create_price_chart(info)
|
| 242 |
performance_chart = self.create_performance_chart()
|
| 243 |
action_chart = self.create_action_chart()
|
| 244 |
+
sentiment_chart = self.create_sentiment_chart()
|
| 245 |
|
| 246 |
# Calculate performance metrics
|
| 247 |
initial_balance = self.env.initial_balance
|
|
|
|
| 250 |
if initial_balance > 0:
|
| 251 |
total_return = (final_net_worth - initial_balance) / initial_balance * 100
|
| 252 |
|
| 253 |
+
# Calculate average sentiment
|
| 254 |
+
avg_sentiment = np.mean([h['sentiment'] for h in self.episode_history]) if self.episode_history else 0.5
|
| 255 |
+
|
| 256 |
summary = (
|
| 257 |
f"🎯 Episode Completed!\n"
|
| 258 |
f"• Total Steps: {len(self.episode_history)}\n"
|
| 259 |
f"• Total Reward: {total_reward:.2f}\n"
|
| 260 |
f"• Final Net Worth: ${final_net_worth:.2f}\n"
|
| 261 |
f"• Total Return: {total_return:.2f}%\n"
|
| 262 |
+
f"• Average Sentiment: {avg_sentiment:.3f}\n"
|
| 263 |
f"• Total Trades: {info['total_trades']}"
|
| 264 |
)
|
| 265 |
|
| 266 |
+
return price_chart, performance_chart, action_chart, sentiment_chart, summary
|
| 267 |
|
| 268 |
except Exception as e:
|
| 269 |
error_msg = f"❌ Error during episode: {str(e)}"
|
| 270 |
print(error_msg)
|
| 271 |
+
return None, None, None, None, error_msg
|
| 272 |
+
|
| 273 |
+
def get_sentiment_analysis_report(self):
|
| 274 |
+
"""Get detailed sentiment analysis report"""
|
| 275 |
+
if not self.use_sentiment or not self.initialized:
|
| 276 |
+
return "❌ Sentiment analysis is not enabled"
|
| 277 |
+
|
| 278 |
+
try:
|
| 279 |
+
sentiment_data = self.sentiment_analyzer.get_influencer_sentiment()
|
| 280 |
+
|
| 281 |
+
report = (
|
| 282 |
+
f"📊 Real-time Market Sentiment Analysis\n"
|
| 283 |
+
f"• Overall Sentiment: {sentiment_data['market_sentiment']:.3f}\n"
|
| 284 |
+
f"• Confidence: {sentiment_data['confidence']:.1%}\n"
|
| 285 |
+
f"• Influencers Analyzed: {sentiment_data['influencer_count']}\n"
|
| 286 |
+
f"• Total Tweets: {sentiment_data['total_tweets']}\n"
|
| 287 |
+
f"• Last Update: {sentiment_data['timestamp']}"
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
# Add top influencers
|
| 291 |
+
top_influencers = list(sentiment_data['breakdown'].items())[:3]
|
| 292 |
+
for username, data in top_influencers:
|
| 293 |
+
sentiment_emoji = "🔴" if data['score'] < 0.4 else "🟡" if data['score'] < 0.6 else "🟢"
|
| 294 |
+
report += f"\n• {sentiment_emoji} {username}: {data['score']:.3f} (conf: {data['confidence']:.1%})"
|
| 295 |
+
|
| 296 |
+
return report
|
| 297 |
+
|
| 298 |
+
except Exception as e:
|
| 299 |
+
return f"❌ Error getting sentiment report: {str(e)}"
|
| 300 |
|
| 301 |
def train_agent(self, num_episodes, learning_rate):
|
| 302 |
+
"""Train the AI agent with sentiment-enhanced learning"""
|
| 303 |
if not self.initialized or self.env is None:
|
| 304 |
+
yield None, None, "⚠️ Please initialize environment first!"
|
| 305 |
return
|
| 306 |
|
| 307 |
self.is_training = True
|
|
|
|
| 316 |
steps = 0
|
| 317 |
|
| 318 |
while not done and steps < 100:
|
| 319 |
+
# Get sentiment for this step
|
| 320 |
+
current_sentiment = 0.5
|
| 321 |
+
sentiment_confidence = 0.0
|
| 322 |
+
|
| 323 |
+
if self.use_sentiment:
|
| 324 |
+
sentiment_info = self.env.get_sentiment_analysis()
|
| 325 |
+
current_sentiment = sentiment_info.get('current_sentiment', 0.5)
|
| 326 |
+
sentiment_confidence = sentiment_info.get('sentiment_confidence', 0.0)
|
| 327 |
+
|
| 328 |
+
# Select action with sentiment
|
| 329 |
+
action = self.agent.select_action(state, current_sentiment, sentiment_confidence)
|
| 330 |
next_state, reward, done, info = self.env.step(action)
|
| 331 |
+
|
| 332 |
+
# Store experience with sentiment data
|
| 333 |
+
sentiment_data = {
|
| 334 |
+
'sentiment': current_sentiment,
|
| 335 |
+
'confidence': sentiment_confidence
|
| 336 |
+
}
|
| 337 |
+
self.agent.store_transition(state, action, reward, next_state, done, sentiment_data)
|
| 338 |
+
|
| 339 |
state = next_state
|
| 340 |
episode_reward += reward
|
| 341 |
steps += 1
|
|
|
|
| 387 |
yield None, error_msg
|
| 388 |
|
| 389 |
def create_price_chart(self, info):
|
| 390 |
+
"""Create price chart with actions and sentiment markers"""
|
| 391 |
if not self.episode_history:
|
|
|
|
| 392 |
fig = go.Figure()
|
| 393 |
fig.update_layout(
|
| 394 |
title="Price Chart - No Data Available",
|
|
|
|
| 401 |
|
| 402 |
prices = [h['price'] for h in self.episode_history]
|
| 403 |
actions = [h['action'] for h in self.episode_history]
|
| 404 |
+
sentiments = [h.get('sentiment', 0.5) for h in self.episode_history]
|
| 405 |
|
| 406 |
fig = go.Figure()
|
| 407 |
|
|
|
|
| 414 |
line=dict(color='blue', width=3)
|
| 415 |
))
|
| 416 |
|
| 417 |
+
# Action markers with sentiment coloring
|
| 418 |
+
for i, (action, sentiment) in enumerate(zip(actions, sentiments)):
|
| 419 |
+
if action == 1: # Buy
|
| 420 |
+
color = 'green' if sentiment > 0.6 else 'lightgreen' if sentiment > 0.4 else 'darkgreen'
|
| 421 |
+
fig.add_trace(go.Scatter(
|
| 422 |
+
x=[i], y=[prices[i]],
|
| 423 |
+
mode='markers',
|
| 424 |
+
name='Buy' if i == 1 else '',
|
| 425 |
+
marker=dict(color=color, size=12, symbol='triangle-up',
|
| 426 |
+
line=dict(width=2, color='darkgreen')),
|
| 427 |
+
showlegend=False
|
| 428 |
+
))
|
| 429 |
+
elif action == 2: # Sell
|
| 430 |
+
color = 'red' if sentiment < 0.4 else 'lightcoral' if sentiment < 0.6 else 'darkred'
|
| 431 |
+
fig.add_trace(go.Scatter(
|
| 432 |
+
x=[i], y=[prices[i]],
|
| 433 |
+
mode='markers',
|
| 434 |
+
name='Sell' if i == 2 else '',
|
| 435 |
+
marker=dict(color=color, size=12, symbol='triangle-down',
|
| 436 |
+
line=dict(width=2, color='darkred')),
|
| 437 |
+
showlegend=False
|
| 438 |
+
))
|
| 439 |
+
elif action == 3: # Close
|
| 440 |
+
fig.add_trace(go.Scatter(
|
| 441 |
+
x=[i], y=[prices[i]],
|
| 442 |
+
mode='markers',
|
| 443 |
+
name='Close' if i == 3 else '',
|
| 444 |
+
marker=dict(color='orange', size=10, symbol='x',
|
| 445 |
+
line=dict(width=2, color='darkorange')),
|
| 446 |
+
showlegend=False
|
| 447 |
+
))
|
|
|
|
|
|
|
|
|
|
| 448 |
|
| 449 |
fig.update_layout(
|
| 450 |
+
title="Price Chart with Trading Actions (Colored by Sentiment)",
|
| 451 |
xaxis_title="Step",
|
| 452 |
yaxis_title="Price",
|
| 453 |
height=350,
|
|
|
|
| 543 |
|
| 544 |
return fig
|
| 545 |
|
| 546 |
+
def create_sentiment_chart(self):
|
| 547 |
+
"""Create sentiment analysis chart"""
|
| 548 |
+
if not self.sentiment_history:
|
| 549 |
+
fig = go.Figure()
|
| 550 |
+
fig.update_layout(
|
| 551 |
+
title="Sentiment Analysis - No Data Available",
|
| 552 |
+
height=300
|
| 553 |
+
)
|
| 554 |
+
return fig
|
| 555 |
+
|
| 556 |
+
steps = [h['step'] for h in self.sentiment_history]
|
| 557 |
+
sentiments = [h['sentiment'] for h in self.sentiment_history]
|
| 558 |
+
confidences = [h['confidence'] for h in self.sentiment_history]
|
| 559 |
+
|
| 560 |
+
fig = go.Figure()
|
| 561 |
+
|
| 562 |
+
# Sentiment line
|
| 563 |
+
fig.add_trace(go.Scatter(
|
| 564 |
+
x=steps,
|
| 565 |
+
y=sentiments,
|
| 566 |
+
mode='lines+markers',
|
| 567 |
+
name='Market Sentiment',
|
| 568 |
+
line=dict(color='purple', width=3),
|
| 569 |
+
marker=dict(size=6)
|
| 570 |
+
))
|
| 571 |
+
|
| 572 |
+
# Confidence as shaded area
|
| 573 |
+
fig.add_trace(go.Scatter(
|
| 574 |
+
x=steps,
|
| 575 |
+
y=[s + c/2 for s, c in zip(sentiments, confidences)],
|
| 576 |
+
mode='lines',
|
| 577 |
+
name='Confidence Upper',
|
| 578 |
+
line=dict(width=0),
|
| 579 |
+
showlegend=False
|
| 580 |
+
))
|
| 581 |
+
|
| 582 |
+
fig.add_trace(go.Scatter(
|
| 583 |
+
x=steps,
|
| 584 |
+
y=[s - c/2 for s, c in zip(sentiments, confidences)],
|
| 585 |
+
mode='lines',
|
| 586 |
+
name='Confidence Lower',
|
| 587 |
+
fill='tonexty',
|
| 588 |
+
fillcolor='rgba(128, 0, 128, 0.2)',
|
| 589 |
+
line=dict(width=0),
|
| 590 |
+
showlegend=False
|
| 591 |
+
))
|
| 592 |
+
|
| 593 |
+
# Add sentiment level lines
|
| 594 |
+
fig.add_hline(y=0.6, line_dash="dash", line_color="green", annotation_text="Bullish Threshold")
|
| 595 |
+
fig.add_hline(y=0.4, line_dash="dash", line_color="red", annotation_text="Bearish Threshold")
|
| 596 |
+
|
| 597 |
+
fig.update_layout(
|
| 598 |
+
title="Market Sentiment Analysis Over Time",
|
| 599 |
+
xaxis_title="Step",
|
| 600 |
+
yaxis_title="Sentiment Score",
|
| 601 |
+
height=350,
|
| 602 |
+
yaxis=dict(range=[0, 1]),
|
| 603 |
+
template="plotly_white"
|
| 604 |
+
)
|
| 605 |
+
|
| 606 |
+
return fig
|
| 607 |
+
|
| 608 |
def create_training_progress(self, training_history):
|
| 609 |
"""Create training progress visualization"""
|
| 610 |
if not training_history:
|
|
|
|
| 672 |
return fig
|
| 673 |
|
| 674 |
# Initialize the demo
|
| 675 |
+
demo = ProfessionalTradingAIDemo()
|
| 676 |
|
| 677 |
# Create Gradio interface
|
| 678 |
def create_interface():
|
| 679 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="Professional Trading AI") as interface:
|
| 680 |
gr.Markdown("""
|
| 681 |
+
# 🚀 Professional Trading AI
|
| 682 |
+
**ترکیب هوش مصنوعی پیشرفته: تحلیل توئییت + CNN + یادگیری تقویتی**
|
| 683 |
|
| 684 |
+
*این سیستم از **تحلیل احساسات توئییتهای افراد تاثیرگذار**، **پردازش بصری نمودارها با CNN** و **یادگیری تقویتی** برای تصمیمگیری هوشمند استفاده میکند.*
|
| 685 |
""")
|
| 686 |
|
| 687 |
with gr.Row():
|
| 688 |
with gr.Column(scale=1):
|
| 689 |
# Configuration section
|
| 690 |
+
gr.Markdown("## ⚙️ پیکربندی حرفهای")
|
| 691 |
|
| 692 |
with gr.Row():
|
| 693 |
initial_balance = gr.Slider(
|
| 694 |
minimum=1000, maximum=50000, value=10000, step=1000,
|
| 695 |
+
label="موجودی اولیه ($)", info="میزان سرمایه اولیه"
|
| 696 |
)
|
| 697 |
|
| 698 |
with gr.Row():
|
| 699 |
risk_level = gr.Radio(
|
| 700 |
["Low", "Medium", "High"],
|
| 701 |
value="Medium",
|
| 702 |
+
label="سطح ریسک"
|
|
|
|
| 703 |
)
|
| 704 |
|
| 705 |
with gr.Row():
|
| 706 |
asset_type = gr.Radio(
|
| 707 |
["Stock", "Crypto", "Forex"],
|
| 708 |
+
value="Crypto",
|
| 709 |
+
label="نوع دارایی"
|
| 710 |
+
)
|
| 711 |
+
|
| 712 |
+
with gr.Row():
|
| 713 |
+
use_sentiment = gr.Checkbox(
|
| 714 |
+
value=True,
|
| 715 |
+
label="فعالسازی تحلیل احساسات توئییت",
|
| 716 |
+
info="آنالیز توئییتهای افراد تاثیرگذار"
|
| 717 |
+
)
|
| 718 |
+
|
| 719 |
+
with gr.Row():
|
| 720 |
+
sentiment_influence = gr.Slider(
|
| 721 |
+
minimum=0.1, maximum=0.8, value=0.3, step=0.1,
|
| 722 |
+
label="تاثیر تحلیل احساسات",
|
| 723 |
+
info="میزان تاثیرگذاری تحلیل توئییتها بر تصمیمها"
|
| 724 |
)
|
| 725 |
|
| 726 |
with gr.Row():
|
| 727 |
init_btn = gr.Button(
|
| 728 |
+
"🚀 راهاندازی سیستم حرفهای",
|
| 729 |
variant="primary",
|
| 730 |
size="lg"
|
| 731 |
)
|
|
|
|
| 734 |
init_status = gr.Textbox(
|
| 735 |
label="وضعیت راهاندازی",
|
| 736 |
interactive=False,
|
| 737 |
+
lines=3
|
|
|
|
| 738 |
)
|
| 739 |
|
| 740 |
with gr.Column(scale=2):
|
|
|
|
| 743 |
status_output = gr.Textbox(
|
| 744 |
label="وضعیت اجرا",
|
| 745 |
interactive=False,
|
| 746 |
+
lines=5
|
|
|
|
| 747 |
)
|
| 748 |
|
| 749 |
with gr.Row():
|
|
|
|
| 755 |
["AI Decision", "Buy", "Sell", "Hold", "Close"],
|
| 756 |
value="AI Decision",
|
| 757 |
label="انتخاب اقدام",
|
| 758 |
+
info="AI Decision: ترکیب CNN + RL + تحلیل احساسات"
|
| 759 |
)
|
| 760 |
|
| 761 |
with gr.Row():
|
|
|
|
| 772 |
variant="secondary",
|
| 773 |
size="lg"
|
| 774 |
)
|
| 775 |
+
|
| 776 |
+
with gr.Column(scale=1):
|
| 777 |
+
sentiment_btn = gr.Button(
|
| 778 |
+
"📊 گزارش تحلیل احساسات",
|
| 779 |
+
variant="secondary",
|
| 780 |
+
size="lg"
|
| 781 |
+
)
|
| 782 |
|
| 783 |
with gr.Row():
|
| 784 |
# Visualization outputs
|
|
|
|
| 797 |
action_chart = gr.Plot(
|
| 798 |
label="🎯 توزیع اقدامات"
|
| 799 |
)
|
| 800 |
+
|
| 801 |
+
with gr.Column(scale=1):
|
| 802 |
+
sentiment_chart = gr.Plot(
|
| 803 |
+
label="😊 تحلیل احساسات بازار"
|
| 804 |
+
)
|
| 805 |
|
| 806 |
with gr.Row():
|
| 807 |
gr.Markdown("## 🎓 آموزش هوش مصنوعی")
|
|
|
|
| 810 |
with gr.Column(scale=1):
|
| 811 |
num_episodes = gr.Slider(
|
| 812 |
minimum=10, maximum=200, value=50, step=10,
|
| 813 |
+
label="تعداد اپیزودهای آموزش"
|
|
|
|
| 814 |
)
|
| 815 |
|
| 816 |
learning_rate = gr.Slider(
|
| 817 |
minimum=0.0001, maximum=0.01, value=0.001, step=0.0001,
|
| 818 |
+
label="نرخ یادگیری"
|
|
|
|
| 819 |
)
|
| 820 |
|
| 821 |
train_btn = gr.Button(
|
| 822 |
+
"🤖 شروع آموزش پیشرفته",
|
| 823 |
variant="primary",
|
| 824 |
size="lg"
|
| 825 |
)
|
|
|
|
| 832 |
training_status = gr.Textbox(
|
| 833 |
label="وضعیت آموزش",
|
| 834 |
interactive=False,
|
|
|
|
| 835 |
lines=3
|
| 836 |
)
|
| 837 |
|
| 838 |
with gr.Row():
|
| 839 |
+
gr.Markdown("## 🧠 معماری هوش مصنوعی پیشرفته")
|
| 840 |
|
| 841 |
with gr.Row():
|
| 842 |
with gr.Column(scale=1):
|
| 843 |
gr.Markdown("""
|
| 844 |
+
**🎯 تحلیل احساسات توئییت:**
|
| 845 |
+
- آنالیز توئییتهای ۸ فرد تاثیرگذار
|
| 846 |
+
- استفاده از ۵ مدل مختلف sentiment analysis
|
| 847 |
+
- تشخیص فوریت و کلمات کلیدی
|
| 848 |
+
- وزندهی بر اساس اعتبار افراد
|
| 849 |
+
|
| 850 |
+
**🖼️ CNN (پردازش بصری):**
|
| 851 |
- تحلیل تصاویر نمودارهای قیمت
|
| 852 |
- تشخیص الگوهای تکنیکال
|
| 853 |
- استخراج ویژگیهای بصری
|
| 854 |
- ورودی: تصاویر 84x84 پیکسل
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 855 |
""")
|
| 856 |
|
| 857 |
with gr.Column(scale=1):
|
| 858 |
gr.Markdown("""
|
| 859 |
+
**🤖 Reinforcement Learning:**
|
| 860 |
+
- الگوریتم Deep Q-Network پیشرفته
|
| 861 |
+
- ترکیب دادههای بصری و احساساتی
|
| 862 |
+
- یادگیری از طریق تعامل با محیط
|
| 863 |
+
- تجربه replay برای یادگیری پایدار
|
| 864 |
|
| 865 |
+
**📊 افراد تاثیرگذار تحت نظر:**
|
| 866 |
+
- Elon Musk, CZ Binance, Michael Saylor
|
| 867 |
+
- Peter Brandt, Nic Carter, Andreas Antonopoulos
|
| 868 |
+
- و سایر متخصصان بازار
|
| 869 |
""")
|
| 870 |
|
| 871 |
# Event handlers
|
| 872 |
init_btn.click(
|
| 873 |
demo.initialize_environment,
|
| 874 |
+
inputs=[initial_balance, risk_level, asset_type, use_sentiment, sentiment_influence],
|
| 875 |
outputs=[init_status]
|
| 876 |
)
|
| 877 |
|
| 878 |
step_btn.click(
|
| 879 |
demo.run_single_step,
|
| 880 |
inputs=[action_choice],
|
| 881 |
+
outputs=[price_chart, performance_chart, action_chart, sentiment_chart, status_output]
|
| 882 |
)
|
| 883 |
|
| 884 |
episode_btn.click(
|
| 885 |
demo.run_episode,
|
| 886 |
inputs=[],
|
| 887 |
+
outputs=[price_chart, performance_chart, action_chart, sentiment_chart, status_output]
|
| 888 |
+
)
|
| 889 |
+
|
| 890 |
+
sentiment_btn.click(
|
| 891 |
+
demo.get_sentiment_analysis_report,
|
| 892 |
+
inputs=[],
|
| 893 |
+
outputs=[status_output]
|
| 894 |
)
|
| 895 |
|
| 896 |
train_btn.click(
|
|
|
|
| 900 |
)
|
| 901 |
|
| 902 |
gr.Markdown("""
|
| 903 |
+
## 🏗 جزئیات فنی پیشرفته
|
| 904 |
+
|
| 905 |
+
**🎯 ترکیب سه تکنولوژی:**
|
| 906 |
+
- **تحلیل احساسات**: ۵ مدل مختلف + VADER + TextBlob
|
| 907 |
+
- **پردازش بصری**: CNN با ۳ لایه کانولوشن
|
| 908 |
+
- **یادگیری تقویتی**: DQN پیشرفته با تجربه replay
|
| 909 |
+
|
| 910 |
+
**🛠 فناوریهای به کار رفته:**
|
| 911 |
+
- **Transformers**: Hugging Face برای تحلیل احساسات
|
| 912 |
+
- **PyTorch**: پیادهسازی CNN و RL
|
| 913 |
+
- **Gradio**: رابط کاربری پیشرفته
|
| 914 |
+
- **Plotly**: ویژوالیزیشن حرفهای
|
| 915 |
+
|
| 916 |
+
**📊 افراد تاثیرگذار تحت نظر:**
|
| 917 |
+
- Elon Musk (تاثیر: ۹۰٪) - همه بازارها
|
| 918 |
+
- CZ Binance (تاثیر: ۸۰٪) - بازار کریپتو
|
| 919 |
+
- Michael Saylor (تاثیر: ۷۰٪) - بیتکوین
|
| 920 |
+
- و ۵ فرد تاثیرگذار دیگر
|
| 921 |
+
|
| 922 |
+
*سیستم حرفهای توسعه داده شده توسط Omid Sakaki - 2024*
|
|
|
|
|
|
|
|
|
|
| 923 |
""")
|
| 924 |
|
| 925 |
return interface
|
| 926 |
|
| 927 |
# Create and launch interface
|
| 928 |
if __name__ == "__main__":
|
| 929 |
+
print("🚀 Starting Professional Trading AI Application...")
|
| 930 |
+
print("🧠 Loading: Sentiment Analysis + CNN + Reinforcement Learning...")
|
| 931 |
|
| 932 |
interface = create_interface()
|
| 933 |
|
| 934 |
+
print("✅ All components initialized successfully!")
|
| 935 |
print("🌐 Starting server on http://0.0.0.0:7860")
|
| 936 |
+
print("📱 Access the professional trading AI in your browser")
|
| 937 |
|
|
|
|
| 938 |
interface.launch(
|
| 939 |
server_name="0.0.0.0",
|
| 940 |
server_port=7860,
|