Qt Step1
In this chapter, we will first look at a simple application example of Python quantitative trading, which uses a moving average strategy and Yahoo Finance data.
The basic idea of this strategy is to generate buy and sell signals by comparing short-term and long-term moving averages.
Before doing this simple example, you need to install three packages first:
pip install pandas numpy matplotlib yfinance
**Package Description:**
* **pandas** is a powerful open-source data processing and analysis library, specifically designed for efficient data analysis and manipulation.
* **numpy** provides support for arrays and matrices, used for mathematical calculations.
* **yfinance** is a library for obtaining financial data, supporting the retrieval of stocks, indices, and other financial market data from Yahoo Finance.
* **matplotlib** is a two-dimensional plotting library used to create static, dynamic, and interactive data visualization charts.
### Getting Historical Stock Data
Use yfinance to get historical stock data. Here is a simple example:
## Example
import yfinance as yf
# Get stock data
symbol="600519.SS"
start_date ="2022-01-01"
end_date ="2023-01-01"
data = yf.download(symbol, start=start_date, end=end_date)
print(data.head())
The output is as follows:
Open High Low Close Adj Close VolumeDate 2022-01-04 2055.00000 2068.949951 2014.000000 2051.229980 1973.508057 33842622022-01-05 2045.00000 2065.000000 2018.000000 2024.000000 1947.309937 28395512022-01-06 2022.01001 2036.000000 1938.510010 1982.219971 1907.112915 51794752022-01-07 1975.00000 1988.880005 1939.319946 1942.000000 1868.416870 29816692022-01-10 1928.01001 1977.000000 1917.550049 1966.000000 1891.507446 2962670
### Simple Data Analysis and Visualization
Use pandas for data analysis and matplotlib for visualization:
## Example
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
# Get stock data
symbol="600519.SS"
start_date ="2022-01-01"
end_date ="2023-01-01"
data = yf.download(symbol, start=start_date, end=end_date)
# Simple data analysis
print(data.describe())
# Plot stock price trend
data['Close'].plot(figsize=(10,6), label=symbol)
plt.title(f"{symbol} Stock Price")
plt.xlabel("Date")
plt.ylabel("Price")
plt.legend()
plt.show()
The trend chart is shown below:
!(#)
### Moving Average Crossover Strategy
Then, we can use the Yahoo Finance library (yfinance) to get stock data for Kweichow Moutai (600519.SS) and demonstrate a simple example based on the moving average strategy:
## Example
import pandas as pd
import yfinance as yf
import matplotlib.pyplot as plt
# Get Kweichow Moutai stock data
symbol="600519.SS"
start_date ="2022-05-01"
end_date ="2023-12-01"
data = yf.download(symbol, start=start_date, end=end_date)
# Calculate short-term (50-day) and long-term (200-day) moving averages
data['MA_50']= data['Close'].rolling(window=50).mean()
data['MA_200']= data['Close'].rolling(window=200).mean()
# Generate buy and sell signals
data['Signal']=0
data['Signal'][data['MA_50']> data['MA_200']]=1# Short-term MA crosses above long-term MA, generate buy signal
data['Signal'][data['MA_50']< data['MA_200']]= -1# Short-term MA crosses below long-term MA, generate sell signal
# Plot stock price and moving averages
plt.figure(figsize=(10,6))
plt.plot(data['Close'], label='Close Price')
plt.plot(data['MA_50'], label='50-day Moving Average')
plt.plot(data['MA_200'], label='200-day Moving Average')
# Mark buy and sell signals
plt.scatter(data[data['Signal']==1].index, data[data['Signal']==1]['MA_50'], marker='^', color='g', label='Buy Signal')
plt.scatter(data[data['Signal']== -1].index, data[data['Signal']== -1]['MA_50'], marker='v', color='r', label='Sell Signal')
plt.title("Maotai Stock Price with Moving Averages")
plt.xlabel("Date")
plt.ylabel("Price (CNY)")
plt.legend()
plt.show()
The above example code uses Kweichow Moutai (600519.SS) stock data, calculates the 50-day and 200-day moving averages, and generates buy and sell signals by comparing the relationship between the two.
Finally, Matplotlib is used to plot the stock price trend chart and mark the buy and sell signals.
Please remember to carefully research and test strategies in actual trading, and do not make actual investments based solely on the above.
When you execute the above code, the output chart is as follows: the green part is the buy signal, and the red part is the sell signal. Click the image to enlarge:
[!(#)](#)
### Backtesting Strategy
I used the positive and negative daily returns of the stock to generate trading signals to demonstrate a simple example. You can modify this condition according to your own strategy.
## Example
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
# Get stock data
symbol="600519.SS"
start_date ="2023-01-01"
end_date ="2023-12-01"
data = yf.download
YouTip