Moving Average 102
Moving Average 102
import pandas as pd
import ccxt
# Calculate EMAs
df['ema10'] = df['close'].ewm(span=10, adjust=False).mean()
df['ema50'] = df['close'].ewm(span=50, adjust=False).mean()
# Generate signals
df['signal'] = 0
df.loc[df['ema10'] > df['ema50'], 'signal'] = 1 # Buy
df.loc[df['ema10'] < df['ema50'], 'signal'] = -1 # Sell
fi
# Backtest or execute trades (simplified)
for i in range(1, len(df)):
if df['signal'].iloc[i] == 1 and
df['signal'].iloc[i-1] != 1:
print(f"Buy at {df['close'].iloc[i]}")
elif df['signal'].iloc[i] == -1 and
df['signal'].iloc[i-1] != -1:
print(f"Sell at {df['close'].iloc[i]}")
Coding MA Strategies
Beyond Python, platforms like TradingView’s Pine Script allow traders to
create custom MA indicators. For example, a dual-HMA strategy might
combine a fast Hull Moving Average (9-period) with a slow HMA (21-
period) to reduce lag while maintaining trend accuracy.
Managing Latency and Execution Risks
Algo trading with MAs requires attention to:
• Data Quality: Ensure clean, high-frequency price data.
• Latency: Minimize delays in signal generation and trade
execution.
• Slippage: Account for price changes between signal and order ll,
especially in crypto markets.
For instance, during the 2023 Bitcoin rally, high volatility caused slippage
in MA-based bots, emphasizing the need for dynamic stop-losses and
partial position entries.
Next Steps
If you’d like me to:
• Expand a speci c chapter (e.g., algorithmic trading or sentiment
analysis)
• Include more code examples (e.g., Pine Script or R)
• Analyze recent market data or X posts for real-world examples
• Create visualizations (e.g., MA crossover charts via canvas panel)
• Tailor content for a speci c market (e.g., crypto or options)
• Adjust the technical level or tone
• Please let me know, and I can re ne the content. Alternatively, I
can develop another chapter or provide a full draft of a section.
fi
fl
fi
fi