Automated Trading using Python (original) (raw)

**Automated trading using Python involves building a program that can analyze market data and make trading decisions. We’ll use **yfinance to get stock market data, **Pandas and **NumPy to organize and analyze it and**Matplotlib to create simple charts to see **trends and **patterns. The idea is to use past stock prices and some basic calculations to decide when to buy or sell. Before using it in real trading, we’ll test the system with historical data to see how well it works. This will help us create a simple, smart trading system that runs on its own.

Why-Python-Is-Used-For-Developing-Automated-Trading-Strategy1

**Developing Automated Trading System

Step 1: Install Required Libraries

These libraries will be used for fetching data, performing calculations and visualizing results.

pip install yfinance pandas numpy matplotlib

Step 2: Import Libraries

Once the libraries are installed, import them into Python script or notebook.

Python `

import yfinance as yf # For stock data import pandas as pd # For data manipulation import numpy as np # For numerical operations import matplotlib.pyplot as plt # For visualizations

`

Step 3: Fetch Historical Stock Data

We need historical price data to analyze and backtest our trading strategy.

Define parameters

ticker = "AAPL" # Apple stock start_date = "2010-01-01" end_date = "2020-01-01"

Fetch historical stock data

data = yf.download(ticker, start=start_date, end=end_date)

Display first few rows

print(data.head())

`

**Output:

[100%**] 1 of 1 completed
Price Close High Low Open Volume
Ticker AAPL AAPL AAPL AAPL AAPL
Date
2010-01-04 6.447412 6.462175 6.398306 6.429939 493729600
2010-01-05 6.458560 6.495014 6.424517 6.465188 601904800
2010-01-06 6.355828 6.484168 6.349200 6.458560 552160000
2010-01-07 6.344079 6.386859 6.297985 6.379327 477131200
2010-01-08 6.386256 6.386859 6.298287 6.335643 447610800

**Explanation:

Step 4: Calculate Technical Indicators

Indicators help identify trends and generate trading signals. Moving averages smooth out the price data over a set number of days, making it easier to identify trends and filter out short-term noise.

**1. Simple Moving Averages (SMA):

2. **Use rolling().mean() to compute the averages over a specified window.

Python `

Calculate Simple Moving Averages

short_window = 50 # Short-term SMA long_window = 200 # Long-term SMA

data['SMA50'] = data['Close'].rolling(window=short_window).mean() data['SMA200'] = data['Close'].rolling(window=long_window).mean()

`

**Step 5: Define Buy/Sell Signals

**Why signals are used:

Trading signals are created based on SMA crossovers:

Define signals

data['Signal'] = 0 # Initialize Signal column with 0 data.loc[data['SMA50'] > data['SMA200'], 'Signal'] = 1 # Buy data.loc[data['SMA50'] < data['SMA200'], 'Signal'] = -1 # Sell

`

**Explanation:

Step 6: Simulate Trades

Simulate the strategy by calculating daily and cumulative returns.

Python `

Create positions (shift signals to avoid look-ahead bias)

data['Position'] = data['Signal'].shift(1)

Calculate daily percentage change in stock prices

data['Daily Return'] = data['Close'].pct_change()

Calculate returns based on the strategy

data['Strategy Return'] = data['Position'] * data['Daily Return']

Calculate cumulative returns

data['Cumulative Market Return'] = (1 + data['Daily Return']).cumprod() data['Cumulative Strategy Return'] = (1 + data['Strategy Return']).cumprod()

`

**Explanation:

Step 7: Visualize Data

Visualize the stock price, SMA and returns to better understand the strategy.

(a) Plot Stock Price and SMAs:

Python `

plt.figure(figsize=(14, 7)) plt.plot(data['Close'], label='Close Price', alpha=0.5) plt.plot(data['SMA50'], label='SMA50', alpha=0.75) plt.plot(data['SMA200'], label='SMA200', alpha=0.75) plt.title(f"{ticker} Price and Moving Averages") plt.legend() plt.show()

`

**Output:

Screenshot-2025-01-13-143442

Output

(b) Plot Cumulative Returns:

Python `

plt.figure(figsize=(14, 7)) plt.plot(data['Cumulative Market Return'], label='Market Return', alpha=0.75) plt.plot(data['Cumulative Strategy Return'], label='Strategy Return', alpha=0.75) plt.title("Cumulative Returns") plt.legend() plt.show()

`

**Output:

Screenshot-2025-01-13-143506

Output

**Explanation:

Step 8: Evaluate Performance

Compare the cumulative returns of the strategy vs. holding the market.

Python `

total_strategy_return = data['Cumulative Strategy Return'].iloc[-1] - 1 total_market_return = data['Cumulative Market Return'].iloc[-1] - 1

print(f"Total Strategy Return: {total_strategy_return:.2%}") print(f"Total Market Return: {total_market_return:.2%}")

`

**Output:

Total Strategy Return: 291.62%
Total Market Return: 1003.89%

**Why this step is important: