-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclean_example.py
More file actions
317 lines (253 loc) · 11 KB
/
clean_example.py
File metadata and controls
317 lines (253 loc) · 11 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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
#!/usr/bin/env python3
"""
Clean Pandas-TA Example with Proper DataFrame Operations
=========================================================
This script demonstrates the power of pandas-ta for technical analysis
without any pandas warnings. It showcases:
- Multiple technical indicators
- Trading signal detection
- Basic strategy backtesting
- Proper DataFrame operations (no warnings)
"""
import pandas as pd
import numpy as np
import warnings
import pandas_ta as ta
# Suppress pandas warnings for cleaner output
warnings.filterwarnings('ignore', category=FutureWarning)
warnings.filterwarnings('ignore', category=pd.errors.SettingWithCopyWarning)
# Create simulated stock data that looks realistic
def create_realistic_data():
"""Generate realistic stock price data with trends and volatility"""
np.random.seed(42) # For reproducible results
days = 252 # Trading year
dates = pd.date_range(start='2023-01-01', periods=days, freq='D')
# Base price with trend
base_price = 150
trend = np.linspace(0, 15, days) # Gradual uptrend
# Add volatility
returns = np.random.normal(0.001, 0.02, days) # Daily returns
price_changes = np.cumsum(returns) * base_price * 0.1
# Combine trend and volatility
prices = base_price + trend + price_changes
# Calculate OHLC from close prices
high = prices * (1 + np.abs(np.random.normal(0, 0.01, days)))
low = prices * (1 - np.abs(np.random.normal(0, 0.01, days)))
open_prices = np.roll(prices, 1)
open_prices[0] = prices[0]
# Create volume with some correlation to price movements
volume = np.abs(np.random.normal(1000000, 300000, days))
df = pd.DataFrame({
'date': dates,
'open': open_prices,
'high': high,
'low': low,
'close': prices,
'volume': volume.astype(int)
})
df.set_index('date', inplace=True)
return df
def main():
print("🚀 Pandas-TA Clean Example")
print("=" * 50)
# Create sample data
print("📊 Creating sample stock data...")
df = create_realistic_data()
print(f"✅ Generated {len(df)} days of data")
# Show basic info
print(f"💰 Starting price: ${df['close'].iloc[0]:.2f}")
print(f"💰 Ending price: ${df['close'].iloc[-1]:.2f}")
print(f"📈 Total return: {((df['close'].iloc[-1] / df['close'].iloc[0]) - 1) * 100:.1f}%")
print()
# Calculate indicators
print("🔢 Calculating technical indicators...")
# Moving averages
df['SMA_20'] = ta.sma(df['close'], length=20)
df['SMA_50'] = ta.sma(df['close'], length=50)
df['EMA_12'] = ta.ema(df['close'], length=12)
# Momentum indicators
df['RSI'] = ta.rsi(df['close'], length=14)
macd = ta.macd(df['close'])
df = pd.concat([df, macd], axis=1)
# Bollinger Bands
bb = ta.bbands(df['close'], length=20)
df = pd.concat([df, bb], axis=1)
# Volatility
df['ATR'] = ta.atr(df['high'], df['low'], df['close'], length=14)
# Volume
df['OBV'] = ta.obv(df['close'], df['volume'])
print("✅ Technical indicators calculated")
# Create trading signals (proper DataFrame operations)
print("📡 Generating trading signals...")
# Initialize signal columns with zeros
df['Golden_Cross'] = 0
df['Death_Cross'] = 0
df['RSI_Oversold'] = 0
df['RSI_Overbought'] = 0
df['MACD_Bullish'] = 0
df['MACD_Bearish'] = 0
df['Buy_Signal'] = 0
df['Sell_Signal'] = 0
# Calculate signals using proper indexing
# Golden Cross: SMA_20 crosses above SMA_50
df.loc[(df['SMA_20'] > df['SMA_50']) &
(df['SMA_20'].shift(1) <= df['SMA_50'].shift(1)), 'Golden_Cross'] = 1
# Death Cross: SMA_20 crosses below SMA_50
df.loc[(df['SMA_20'] < df['SMA_50']) &
(df['SMA_20'].shift(1) >= df['SMA_50'].shift(1)), 'Death_Cross'] = 1
# RSI signals
df.loc[df['RSI'] < 30, 'RSI_Oversold'] = 1
df.loc[df['RSI'] > 70, 'RSI_Overbought'] = 1
# MACD signals
df.loc[(df['MACD_12_26_9'] > df['MACDs_12_26_9']) &
(df['MACD_12_26_9'].shift(1) <= df['MACDs_12_26_9'].shift(1)), 'MACD_Bullish'] = 1
df.loc[(df['MACD_12_26_9'] < df['MACDs_12_26_9']) &
(df['MACD_12_26_9'].shift(1) >= df['MACDs_12_26_9'].shift(1)), 'MACD_Bearish'] = 1
# Combined buy/sell signals
df.loc[(df['Golden_Cross'] == 1) | (df['RSI_Oversold'] == 1) | (df['MACD_Bullish'] == 1), 'Buy_Signal'] = 1
df.loc[(df['Death_Cross'] == 1) | (df['RSI_Overbought'] == 1) | (df['MACD_Bearish'] == 1), 'Sell_Signal'] = 1
print("✅ Trading signals generated")
# Simple strategy backtesting
print("🎯 Running strategy backtest...")
# Initialize position tracking
df['Position'] = 0
df['Strategy_Return'] = 0.0
current_position = 0 # 0 = cash, 1 = long
for i in range(1, len(df)):
# Check for signals
if df.iloc[i]['Buy_Signal'] == 1 and current_position == 0:
current_position = 1
elif df.iloc[i]['Sell_Signal'] == 1 and current_position == 1:
current_position = 0
# Update position
df.iloc[i, df.columns.get_loc('Position')] = current_position
# Calculate returns
if current_position == 1:
daily_return = (df.iloc[i]['close'] / df.iloc[i-1]['close']) - 1
df.iloc[i, df.columns.get_loc('Strategy_Return')] = daily_return
# Calculate cumulative returns
df['Cumulative_Strategy'] = (1 + df['Strategy_Return']).cumprod()
df['Cumulative_BuyHold'] = df['close'] / df['close'].iloc[0]
# Strategy performance
total_strategy_return = (df['Cumulative_Strategy'].iloc[-1] - 1) * 100
total_buyhold_return = (df['Cumulative_BuyHold'].iloc[-1] - 1) * 100
outperformance = total_strategy_return - total_buyhold_return
# Count signals
total_buy_signals = df['Buy_Signal'].sum()
total_sell_signals = df['Sell_Signal'].sum()
print("✅ Backtest completed")
print()
# Display results
print("📊 STRATEGY PERFORMANCE")
print("=" * 30)
print(f"📈 Buy & Hold Return: {total_buyhold_return:.1f}%")
print(f"🎯 Strategy Return: {total_strategy_return:.1f}%")
print(f"📊 Outperformance: {outperformance:.1f}%")
print(f"🔄 Total buy signals: {total_buy_signals}")
print(f"🔄 Total sell signals: {total_sell_signals}")
print()
# Show available indicators
print("🛠️ AVAILABLE INDICATORS")
print("=" * 30)
indicator_columns = [col for col in df.columns
if col not in ['open', 'high', 'low', 'close', 'volume', 'date']]
for i, col in enumerate(indicator_columns, 1):
print(f"{i:2d}. {col}")
print()
# Summary
print("📋 SUMMARY")
print("=" * 20)
print(f"📊 Data period: {df.index[0].strftime('%Y-%m-%d')} to {df.index[-1].strftime('%Y-%m-%d')}")
print(f"📈 Price change: ${df['close'].iloc[0]:.2f} → ${df['close'].iloc[-1]:.2f} ({total_buyhold_return:.1f}%)")
print(f"🔢 Total columns: {len(df.columns)}")
print(f"📋 Indicators calculated: {len(indicator_columns)}")
print()
# Show last few rows
print("📋 Last 5 days of key indicators:")
display_cols = ['close', 'SMA_20', 'RSI', 'MACD_12_26_9', 'Position']
print(df[display_cols].tail().round(3))
print()
# Quick pandas-ta features demo
print("🔍 PANDAS-TA FEATURES DEMO")
print("=" * 30)
# Show some key feature categories
print("� Main indicator categories available:")
print(" • Overlap: SMA, EMA, VWMA, ALMA, etc.")
print(" • Momentum: RSI, MACD, Stochastic, Williams %R, etc.")
print(" • Volatility: ATR, Bollinger Bands, Keltner Channels, etc.")
print(" • Volume: OBV, Volume SMA, A/D Line, etc.")
print(" • Trend: ADX, Aroon, PSAR, Supertrend, etc.")
print(" • Statistics: Variance, Standard Deviation, Z-Score, etc.")
print(" • 130+ indicators total!")
print()
print("🎯 READY TO EXPERIMENT!")
print("=" * 30)
print("💡 Try modifying this script to:")
print(" • Change indicator parameters")
print(" • Add new indicators from the 130+ available")
print(" • Create your own trading strategies")
print(" • Test different signal combinations")
print(" • Use real data with yfinance")
print()
# Auto-generate charts
print("📊 Auto-generating charts...")
try:
import matplotlib.pyplot as plt
create_auto_charts(df)
except ImportError:
print("📦 Install matplotlib to see charts: pip install matplotlib")
return df
def create_auto_charts(df):
"""Automatically create and save charts"""
import matplotlib.pyplot as plt
plt.style.use('dark_background')
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 10))
fig.patch.set_facecolor('#1e1e1e')
# Price chart
ax1.plot(df.index, df['close'], label='Close', color='white', linewidth=2)
if 'SMA_20' in df.columns:
ax1.plot(df.index, df['SMA_20'], label='SMA 20', color='cyan', alpha=0.8)
if 'SMA_50' in df.columns:
ax1.plot(df.index, df['SMA_50'], label='SMA 50', color='magenta', alpha=0.8)
ax1.set_title('📈 Price & Moving Averages', color='white', fontweight='bold')
ax1.legend()
ax1.grid(True, alpha=0.3)
ax1.set_facecolor('#2d2d30')
# RSI chart
if 'RSI' in df.columns:
ax2.plot(df.index, df['RSI'], color='orange', linewidth=2)
ax2.axhline(y=70, color='red', linestyle='--', alpha=0.7)
ax2.axhline(y=30, color='green', linestyle='--', alpha=0.7)
ax2.fill_between(df.index, 70, 100, alpha=0.1, color='red')
ax2.fill_between(df.index, 0, 30, alpha=0.1, color='green')
ax2.set_title('📊 RSI', color='white', fontweight='bold')
ax2.set_ylim(0, 100)
ax2.grid(True, alpha=0.3)
ax2.set_facecolor('#2d2d30')
# Volume chart
ax3.bar(df.index, df['volume'], alpha=0.6, color='lightblue')
ax3.set_title('📦 Volume', color='white', fontweight='bold')
ax3.grid(True, alpha=0.3)
ax3.set_facecolor('#2d2d30')
# ATR chart
if 'ATR' in df.columns:
ax4.plot(df.index, df['ATR'], color='purple', linewidth=2)
ax4.fill_between(df.index, df['ATR'], alpha=0.3, color='purple')
ax4.set_title('📊 Average True Range', color='white', fontweight='bold')
ax4.grid(True, alpha=0.3)
ax4.set_facecolor('#2d2d30')
# Style all axes
for ax in [ax1, ax2, ax3, ax4]:
ax.tick_params(colors='white')
for spine in ax.spines.values():
spine.set_color('white')
plt.tight_layout()
# Save chart
chart_filename = 'auto_generated_chart.png'
plt.savefig(chart_filename, dpi=300, bbox_inches='tight', facecolor='#1e1e1e')
print(f"📁 Chart automatically saved as: {chart_filename}")
# Show chart
plt.show()
if __name__ == "__main__":
df = main()
print("📁 Data stored in variable 'df' for further analysis")