-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_example.py
More file actions
281 lines (227 loc) · 9.67 KB
/
Copy pathsimple_example.py
File metadata and controls
281 lines (227 loc) · 9.67 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
#!/usr/bin/env python3
"""
Simple and working pandas-ta example for experimentation
"""
import pandas as pd
import pandas_ta as ta
import numpy as np
def create_sample_data(days=252):
"""Create realistic sample stock data"""
print(f"Creating {days} days of sample stock data...")
dates = pd.date_range('2023-01-01', periods=days, freq='B') # Business days
np.random.seed(42) # For reproducible results
# Start with a base price
base_price = 150.0
prices = [base_price]
# Generate price series with some trend and volatility
for i in range(days - 1):
# Daily return with slight upward bias and realistic volatility
daily_return = np.random.normal(0.0005, 0.015) # 0.05% avg return, 1.5% volatility
new_price = prices[-1] * (1 + daily_return)
prices.append(max(new_price, 1.0)) # Prevent negative prices
# Create OHLCV data
data = []
for i, close_price in enumerate(prices):
# Create realistic OHLC within daily range
daily_volatility = close_price * np.random.uniform(0.005, 0.025)
# Generate high and low
high = close_price + daily_volatility * np.random.uniform(0, 1)
low = close_price - daily_volatility * np.random.uniform(0, 1)
# Generate open (influenced by previous close)
if i == 0:
open_price = close_price
else:
gap = np.random.normal(0, 0.002) # Small gaps
open_price = max(low, min(high, prices[i-1] * (1 + gap)))
# Ensure OHLC relationships are valid
high = max(high, open_price, close_price)
low = min(low, open_price, close_price)
volume = np.random.randint(500000, 2000000)
data.append({
'open': round(open_price, 2),
'high': round(high, 2),
'low': round(low, 2),
'close': round(close_price, 2),
'volume': volume
})
df = pd.DataFrame(data, index=dates)
print(f"✅ Created stock data: {df['close'].iloc[0]:.2f} → {df['close'].iloc[-1]:.2f}")
return df
def basic_analysis(df):
"""Perform basic technical analysis"""
print("\n" + "="*50)
print("BASIC TECHNICAL ANALYSIS")
print("="*50)
# 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_data = ta.macd(df['close'])
df = pd.concat([df, macd_data], axis=1)
# Volatility
bb_data = ta.bbands(df['close'], length=20)
df = pd.concat([df, bb_data], axis=1)
df['ATR'] = ta.atr(df['high'], df['low'], df['close'], length=14)
# Volume
df['OBV'] = ta.obv(df['close'], df['volume'])
# Get latest values
latest = df.iloc[-1]
print(f"📊 Current Price: ${latest['close']:.2f}")
print(f"📈 20-day SMA: ${latest['SMA_20']:.2f}")
print(f"📈 50-day SMA: ${latest['SMA_50']:.2f}")
# Trend analysis
if latest['close'] > latest['SMA_20'] > latest['SMA_50']:
trend = "🔥 STRONG UPTREND"
elif latest['close'] > latest['SMA_20']:
trend = "📈 UPTREND"
elif latest['close'] < latest['SMA_20'] < latest['SMA_50']:
trend = "❄️ STRONG DOWNTREND"
elif latest['close'] < latest['SMA_20']:
trend = "📉 DOWNTREND"
else:
trend = "➡️ SIDEWAYS"
print(f"Trend: {trend}")
# RSI analysis
rsi = latest['RSI']
print(f"🎯 RSI: {rsi:.1f}", end=" ")
if rsi > 70:
print("(OVERBOUGHT)")
elif rsi < 30:
print("(OVERSOLD)")
else:
print("(NEUTRAL)")
# MACD analysis
macd_line = latest['MACD_12_26_9']
macd_signal = latest['MACDs_12_26_9']
print(f"📡 MACD: {macd_line:.3f} vs Signal: {macd_signal:.3f}", end=" ")
if macd_line > macd_signal:
print("(BULLISH)")
else:
print("(BEARISH)")
# Bollinger Bands
bb_pos = (latest['close'] - latest['BBL_20_2.0']) / (latest['BBU_20_2.0'] - latest['BBL_20_2.0'])
print(f"🎈 Bollinger Position: {bb_pos:.1%}", end=" ")
if bb_pos > 0.8:
print("(NEAR UPPER BAND)")
elif bb_pos < 0.2:
print("(NEAR LOWER BAND)")
else:
print("(MIDDLE RANGE)")
return df
def find_signals(df):
"""Find trading signals"""
print("\n" + "="*50)
print("TRADING SIGNALS")
print("="*50)
# Golden Cross and Death Cross
df['Golden_Cross'] = (df['SMA_20'] > df['SMA_50']) & (df['SMA_20'].shift(1) <= df['SMA_50'].shift(1))
df['Death_Cross'] = (df['SMA_20'] < df['SMA_50']) & (df['SMA_20'].shift(1) >= df['SMA_50'].shift(1))
# RSI signals
df['RSI_Oversold'] = (df['RSI'] < 30) & (df['RSI'].shift(1) >= 30)
df['RSI_Overbought'] = (df['RSI'] > 70) & (df['RSI'].shift(1) <= 70)
# MACD signals
df['MACD_Bullish'] = (df['MACD_12_26_9'] > df['MACDs_12_26_9']) & (df['MACD_12_26_9'].shift(1) <= df['MACDs_12_26_9'].shift(1))
df['MACD_Bearish'] = (df['MACD_12_26_9'] < df['MACDs_12_26_9']) & (df['MACD_12_26_9'].shift(1) >= df['MACDs_12_26_9'].shift(1))
# Count recent signals (last 30 days)
recent = df.tail(30)
signals = {
'Golden Cross': recent['Golden_Cross'].sum(),
'Death Cross': recent['Death_Cross'].sum(),
'RSI Oversold': recent['RSI_Oversold'].sum(),
'RSI Overbought': recent['RSI_Overbought'].sum(),
'MACD Bullish': recent['MACD_Bullish'].sum(),
'MACD Bearish': recent['MACD_Bearish'].sum(),
}
print("📅 Signals in last 30 days:")
for signal, count in signals.items():
if count > 0:
print(f" {signal}: {count}")
# Find most recent signals
print("\n🔍 Most recent signals:")
for signal_name in ['Golden_Cross', 'Death_Cross', 'RSI_Oversold', 'RSI_Overbought', 'MACD_Bullish', 'MACD_Bearish']:
recent_signal = df[df[signal_name]].tail(1)
if not recent_signal.empty:
date = recent_signal.index[0].strftime('%Y-%m-%d')
price = recent_signal['close'].iloc[0]
print(f" {signal_name}: {date} at ${price:.2f}")
return df
def strategy_backtest(df):
"""Simple strategy backtest"""
print("\n" + "="*50)
print("SIMPLE STRATEGY BACKTEST")
print("="*50)
# Simple strategy: Buy when RSI < 30, Sell when RSI > 70
df['Buy_Signal'] = df['RSI'] < 30
df['Sell_Signal'] = df['RSI'] > 70
# Calculate returns
df['Strategy_Position'] = 0
position = 0
for i in range(len(df)):
if df['Buy_Signal'].iloc[i] and position <= 0:
position = 1
elif df['Sell_Signal'].iloc[i] and position >= 0:
position = 0
df['Strategy_Position'].iloc[i] = position
# Calculate strategy returns
df['Price_Return'] = df['close'].pct_change()
df['Strategy_Return'] = df['Price_Return'] * df['Strategy_Position'].shift(1)
# Performance metrics
total_return = (1 + df['Price_Return']).prod() - 1
strategy_return = (1 + df['Strategy_Return']).prod() - 1
print(f"📈 Buy & Hold Return: {total_return:.1%}")
print(f"🎯 Strategy Return: {strategy_return:.1%}")
print(f"📊 Outperformance: {strategy_return - total_return:.1%}")
# Trade statistics
trades = df[df['Buy_Signal'] | df['Sell_Signal']].copy()
print(f"🔄 Total signals: {len(trades)}")
print(f"📥 Buy signals: {df['Buy_Signal'].sum()}")
print(f"📤 Sell signals: {df['Sell_Signal'].sum()}")
return df
def show_summary(df):
"""Show final summary"""
print("\n" + "="*50)
print("SUMMARY")
print("="*50)
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} ({((df['close'].iloc[-1]/df['close'].iloc[0])-1)*100:.1f}%)")
print(f"🔢 Total columns: {len(df.columns)}")
print(f"📋 Indicators calculated: {len([col for col in df.columns if col not in ['open', 'high', 'low', 'close', 'volume']])}")
print("\n🛠️ Available indicators in this DataFrame:")
indicator_cols = [col for col in df.columns if col not in ['open', 'high', 'low', 'close', 'volume']]
for i, col in enumerate(indicator_cols, 1):
print(f" {i:2d}. {col}")
def main():
"""Main function"""
print("🚀 PANDAS TA - TECHNICAL ANALYSIS PLAYGROUND")
print("=" * 60)
# Create data
df = create_sample_data(252) # 1 year of trading days
# Run analysis
df = basic_analysis(df)
df = find_signals(df)
df = strategy_backtest(df)
show_summary(df)
print("\n" + "="*60)
print("🎯 READY TO EXPERIMENT!")
print("="*60)
print("\n💡 Try modifying this script to:")
print(" • Change indicator parameters (SMA lengths, RSI periods, etc.)")
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(f"\n📁 DataFrame saved as 'df' with {len(df)} rows and {len(df.columns)} columns")
return df
if __name__ == "__main__":
# Run the analysis
df = main()
# Optional: Save to CSV
# df.to_csv('technical_analysis.csv')
# print("\n💾 Data saved to technical_analysis.csv")
# Optional: Show recent data
print("\n📋 Last 5 days of data:")
display_cols = ['close', 'SMA_20', 'RSI', 'MACD_12_26_9', 'BBP_20_2.0']
if all(col in df.columns for col in display_cols):
print(df[display_cols].tail().round(3))