Automating Trades with a Simple Moving Average Strategy
Share trading is fast emerging as one of the most sought-after alternatives for generating passive income. While many believe that trading requires full-time commitment, advancements in technology have changed this perception. With the rise of automation and scripting languages like Python, even part-time traders can automate their strategies efficiently.
In fact, most brokerage houses now encourage automation. It reduces emotional decision-making and ensures that trades are executed purely on predefined logic and indicators. To support this, brokers provide APIs with real-time quotes, along with detailed documentation that allows traders to build their own automated systems.
Today, we’ll walk through a very simple and crude trading strategy based on moving averages. We’ll also look at how Python can be used to automate buy, sell, and exit decisions, along with a visualization of the signals.
Step 1: Fetching Data from Broker API
Data from broker APIs usually comes in a complex dictionary or JSON format. This raw data needs to be transformed into a structured format like a DataFrame (using pandas) or written into a CSV file for further calculations.
import pandas as pd
# Example API response (simplified)
data = [
{"timestamp": "2025-09-21 09:15:00", "price": 24500},
{"timestamp": "2025-09-21 09:16:00", "price": 24520},
{"timestamp": "2025-09-21 09:17:00", "price": 24480}
]
# Convert to DataFrame
df = pd.DataFrame(data)
df["timestamp"] = pd.to_datetime(df["timestamp"])
df.set_index("timestamp", inplace=True)
print(df.head())
Step 2: Calculating Moving Averages
For this strategy, we’ll calculate two moving averages:
- 30-period Moving Average (fast MA)
- 50-period Moving Average (slow MA)
When the 30-period MA crosses above the 50-period MA, we take a buy position. When the 30-period MA falls below the 50-period MA, we take a sell position.
# Calculate moving averages
df["MA30"] = df["price"].rolling(window=30).mean()
df["MA50"] = df["price"].rolling(window=50).mean()
# Generate signals
df["signal"] = 0
df.loc[df["MA30"] > df["MA50"], "signal"] = 1 # Buy
df.loc[df["MA30"] < df["MA50"], "signal"] = -1 # Sell
Step 3: Visualizing Buy/Sell Signals
A chart makes it easier to see where the strategy would buy and sell.
import matplotlib.pyplot as plt
plt.figure(figsize=(12,6))
# Plot price and moving averages
plt.plot(df.index, df["price"], label="Price", alpha=0.7)
plt.plot(df.index, df["MA30"], label="30-period MA", color="green")
plt.plot(df.index, df["MA50"], label="50-period MA", color="red")
# Mark buy signals
plt.scatter(df.index[df["signal"] == 1],
df["price"][df["signal"] == 1],
label="Buy", marker="^", color="blue", s=100)
# Mark sell signals
plt.scatter(df.index[df["signal"] == -1],
df["price"][df["signal"] == -1],
label="Sell", marker="v", color="black", s=100)
plt.title("Moving Average Strategy - Buy/Sell Signals")
plt.xlabel("Time")
plt.ylabel("Price")
plt.legend()
plt.grid(True)
plt.show()
Step 4: Trade Management
Once we have signals, we need to manage open trades:
- Stop Loss Check: If price hits the stop loss, exit immediately.
- Profit Booking: If price meets target profit, square off the trade.
- End of Day Exit: At 03:20 PM (10 minutes before market close), exit all open trades to avoid overnight risk.
This ensures that the system runs independently without manual intervention.
Step 5: Testing the Strategy
It is always advisable to start with paper trading before deploying the strategy live. Paper trading allows you to validate your logic, fine-tune stop loss/profit rules, and check if the signals align with your expectations. Once tested, the system can be connected to broker APIs for live trading.
Conclusion
This was a basic introduction to moving average-based trade automation. The aim here is not to build the perfect strategy, but to kickstart our series on trading automation.
In upcoming posts, we’ll move towards more advanced strategies such as calculating Option Greeks in Python and using them for decision-making in options trading.
If you’d like to get your trades automated or need guidance in building your own trading strategy, feel free to reach out at 7003426212 for support.
No comments:
Post a Comment