-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathai.py
More file actions
171 lines (129 loc) · 5.77 KB
/
Copy pathai.py
File metadata and controls
171 lines (129 loc) · 5.77 KB
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
# -*- coding: utf-8 -*-
"""Copy of Ai.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1vUpFvkYZHVz6r6jYkIMHiw63Gwj84xvy
"""
from google.colab import files
uploaded = files.upload()
import pandas as pd
trades = pd.read_csv("historical_data.csv")
fear = pd.read_csv("fear_greed_index (1).csv")
print(trades.head())
print(fear.head())
trades.info()
fear.info()
trades = trades.drop_duplicates()
fear = fear.drop_duplicates()
trades['Date'] = pd.to_datetime(trades['Timestamp IST'], format='%d-%m-%Y %H:%M')
fear['Date'] = pd.to_datetime(fear['date'])
merged = pd.merge(
trades,
fear,
on='Date',
how='left'
)
merged.groupby('classification')['Closed PnL'].mean()
merged.groupby('classification')['Size USD'].mean()
merged.groupby('classification')['Size USD'].mean()
merged['win'] = merged['Closed PnL'] > 0
merged.groupby('classification')['win'].mean()
import matplotlib.pyplot as plt
# Sort the merged DataFrame by 'Date' to ensure the line plot is sequential
merged_sorted = merged.sort_values(by='Date')
plt.figure(figsize=(15, 7))
plt.plot(merged_sorted['Date'], merged_sorted['Closed PnL'], label='Closed PnL Over Time')
plt.title('Closed PnL Trend Over Time')
plt.xlabel('Date')
plt.ylabel('Closed PnL')
plt.grid(True)
plt.legend()
plt.tight_layout()
plt.show()
import matplotlib.pyplot as plt
import seaborn as sns
# Prepare data: Sort by date and calculate cumulative profit
plot_df = merged.sort_values('Date').dropna(subset=['value'])
plot_df['Cumulative PnL'] = plot_df['Closed PnL'].cumsum()
fig, ax1 = plt.subplots(figsize=(16, 8))
# Plot 1: Fear & Greed Index (Area Plot)
ax1.fill_between(plot_df['Date'], plot_df['value'], color='gray', alpha=0.2, label='Fear & Greed Index')
ax1.plot(plot_df['Date'], plot_df['value'], color='gray', alpha=0.5, linewidth=1)
ax1.set_ylabel('Fear & Greed Index Value', color='gray', fontsize=12)
ax1.tick_params(axis='y', labelcolor='gray')
ax1.set_ylim(0, 100) # Fear & Greed is always 0-100
# Create a second y-axis for Cumulative PnL
ax2 = ax1.twinx()
ax2.plot(plot_df['Date'], plot_df['Cumulative PnL'], color='#1f77b4', linewidth=2.5, label='Cumulative Profit (USD)')
ax2.set_ylabel('Cumulative Profit (USD)', color='#1f77b4', fontsize=12)
ax2.tick_params(axis='y', labelcolor='#1f77b4')
# Add horizontal line at 0 for Profit
ax2.axhline(0, color='red', linestyle='--', linewidth=1, alpha=0.5)
# Styling
plt.title('Historical Performance vs. Market Sentiment', fontsize=16, fontweight='bold')
ax1.set_xlabel('Date', fontsize=12)
ax1.grid(True, which='both', linestyle=':', alpha=0.5)
# Add legend
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper left')
plt.tight_layout()
plt.show()
import matplotlib.pyplot as plt
import pandas as pd
# Prepare sequential data
df_plot = merged.sort_values('Date').dropna(subset=['value'])
df_plot['Cum Profit'] = df_plot['Closed PnL'].cumsum()
df_plot['Rolling Win Rate'] = df_plot['win'].rolling(window=10).mean()
fig, axes = plt.subplots(4, 1, figsize=(15, 20), sharex=True)
metrics = [
('Cum Profit', 'Cumulative Profit (USD)', '#2ecc71'),
('Size USD', 'Trade Size (USD)', '#3498db'),
('value', 'Fear & Greed Index', '#95a5a6'),
('Rolling Win Rate', 'Win Rate (10-Trade Rolling)', '#e74c3c')
]
for i, (col, label, color) in enumerate(metrics):
ax = axes[i]
# Overlay Fear & Greed Index in background of every plot for context
ax_bg = ax.twinx()
ax_bg.fill_between(df_plot['Date'], df_plot['value'], color='gray', alpha=0.1)
ax_bg.set_yticks([])
# Plot main metric
ax.plot(df_plot['Date'], df_plot[col], color=color, linewidth=2, label=label)
ax.set_ylabel(label, fontweight='bold')
ax.grid(True, alpha=0.3)
ax.legend(loc='upper left')
plt.title('Professional Performance Dashboard', y=4.1, fontsize=16)
plt.tight_layout()
plt.show()
import matplotlib.pyplot as plt
import seaborn as sns
# Prepare summary for the heatmap
# Note: 'summary' was calculated in previous steps
heatmap_data = summary.set_index('classification')[['Closed PnL', 'Size USD', 'win']]
heatmap_data.columns = ['Avg Profit', 'Avg Size', 'Win Rate']
# Create a single 2x2 Professional Grid
fig, axes = plt.subplots(2, 2, figsize=(16, 12))
sns.set_style('whitegrid')
# 1. Violin Plot for Profit Distribution
sns.violinplot(ax=axes[0,0], x='classification', y='Closed PnL', data=merged, hue='classification', palette='viridis', inner='quartile', legend=False)
axes[0,0].set_title('Profit Density Distribution (Violin)', fontweight='bold')
axes[0,0].axhline(0, color='red', linestyle='--', alpha=0.5)
# 2. Box Plot for Trade Size
sns.boxplot(ax=axes[0,1], x='classification', y='Size USD', data=merged, hue='classification', palette='mako', legend=False)
axes[0,1].set_title('Trade Size Range & Outliers (Box)', fontweight='bold')
# 3. Performance Heatmap (KPI Overview)
sns.heatmap(ax=axes[1,0], data=heatmap_data, annot=True, cmap='RdYlGn', fmt='.2f', cbar=True)
axes[1,0].set_title('Sentiment KPI Heatmap', fontweight='bold')
# 4. Strip Plot (Individual trade outcomes)
# sampling to keep the plot clean if the dataset is large
sample_data = merged.dropna(subset=['classification']).sample(min(1000, len(merged.dropna(subset=['classification']))))
sns.stripplot(ax=axes[1,1], x='classification', y='Closed PnL', data=sample_data, hue='classification', palette='rocket', jitter=True, alpha=0.4, legend=False)
axes[1,1].set_title('Individual Trade Samples (Strip Plot)', fontweight='bold')
axes[1,1].axhline(0, color='black', linestyle='-', alpha=0.2)
for ax in axes.flat:
ax.tick_params(axis='x', rotation=30)
ax.set_xlabel('')
plt.suptitle('Unified Sentiment Performance Dashboard', fontsize=20, fontweight='bold', y=1.02)
plt.tight_layout()
plt.show()