Minfeng International Futures Quantitative Trading Strategy Source Code Collection

1. Alpha hedging (futures)

Investors face systemic risks (i.e. Beta or Beta risk) and non-systematic risks (i.e. Alpha or Alpha, α risk) in market transactions. By measuring and separating systemic risks, investors can obtain excess A strategy combination with absolute returns (i.e. alpha returns) is an alpha strategy.

alpha hedging source code:

import pandas as pd

# Load historical data Europe and America 5.5

data = pd.read_csv('data.csv')

# Calculate Alpha

data['Alpha'] = data['Alpha_Indicator'] - data['Beta_Indicator']

# Generate trading signalGreater Hang Seng Index 35

data['Signal'] = 0

data.loc[data['Alpha'] > 0, 'Signal'] = 1 #Buy when Alpha indicator is greater than 0

data.loc[data['Alpha'] < 0, 'Signal'] = -1 # Sell when the Alpha indicator is less than 0

# Calculate positionSmall Hang Seng Index 25

data['Position'] = data['Signal'].diff()

# backtest

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

data['Strategy_Return'] = data['Position'].shift() * data['Return']

data['Cumulative_Return'] = (1 + data['Strategy_Return']).cumprod()

# Output result deduction 1839716836

print(data)

The code uses the pandas library to process data and calculate indicators. You need to install and import the library in advance. In addition, data.csv is a CSV file containing historical price data and Alpha indicator data. You need to prepare the corresponding data files according to your own needs. At the same time, the Alpha indicator needs to be calculated and adjusted according to the actual situation. In this example, two indicators, Alpha_Indicator and Beta_Indicator, are used to calculate Alpha.

2, Double moving average strategy (futures)

The dual moving average strategy is an enhanced version of the simple moving average strategy. The purpose of the moving average is to filter out high-frequency disturbances in the time series and retain useful low-frequency trends. It gains smoothness at the cost of lag. For example, after a bull market, only when the price retraces significantly will it be reflected on the moving average, which will be greatly increased for investors. transaction costs. If you use a dual moving average strategy, you can take into account the long-term trend as well as the more sensitive small-cycle trend. This is undoubtedly an effective method to solve the lagging weakness of the simple moving average.
 

Double moving average strategy source code:

import pandas as pd

#Load historical data

data = pd.read_csv('data.csv')

# Calculate short-term moving average

data['Short_MA'] = data['Close'].rolling(window=10).mean()

# Calculate long-term moving average

data['Long_MA'] = data['Close'].rolling(window=20).mean()

# Generate trading signals

data['Signal'] = 0

data.loc[data['Short_MA'] > data['Long_MA'], 'Signal'] = 1 # Buy when the short-term moving average crosses the long-term moving average

data.loc[data['Short_MA'] < data['Long_MA'], 'Signal'] = -1 # Sell when the short-term moving average crosses the long-term moving average out

# Calculate positions

data['Position'] = data['Signal'].diff()

# backtest

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

data['Strategy_Return'] = data['Position'].shift() * data['Return']

data['Cumulative_Return'] = (1 + data['Strategy_Return']).cumprod()

# Output results

print(data)

The pandas library is used in the code to process data and calculate indicators. This library needs to be installed and imported in advance. In addition, data.csv is a CSV file containing historical price data. You need to prepare the corresponding data files according to your own needs.

3. Market maker trading (futures)

The main profit of market makers comes from the bid-ask spread of two-way quotations. Therefore, market makers need to calculate the theoretical price of options, gradually accumulate the difference between each transaction price and the theoretical price in a large number of buying and selling transactions, and dynamically adjust the spread based on the characteristics of the position. Since market makers mainly engage in passive transactions, they may face losses if some counterparties continue to engage in large amounts of unilateral transactions.

Market maker trading futures source code:

import pandas as pd

#Load historical data

data = pd.read_csv('data.csv')

# Set market maker parameters

spread = 0.01 # Bid-ask spread

inventory = 100 # Initial inventory

position = 0 # Initial position

# Generate trading signals

data['Signal'] = 0

data.loc[data['Ask_Price'] - data['Bid_Price'] > spread, 'Signal'] = 1 # When the bid-ask spread is greater than the set value Trading

# Calculate positions

data['Position'] = data['Signal'].diff()

# Execute market maker trading strategy

for i, row in data.iterrows():

         if row['Position'] == 1: # BUY SIGNAL

             position += inventory

         elif row['Position'] == -1: # Sell signal

             position -= inventory

        data.at[i, 'Position'] = position

# backtest

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

data['Strategy_Return'] = data['Position'].shift() * data['Return']

data['Cumulative_Return'] = (1 + data['Strategy_Return']).cumprod()

# Output results

print(data)

The code uses the pandas library to process data, which needs to be installed and imported in advance. In addition, data.csv is a CSV file containing historical price data and buying and selling price data. You need to prepare the corresponding data files according to your own needs. At the same time, you can also set and adjust the parameters of the market maker strategy according to the actual situation. In this example, the bid-ask spread and initial inventory amount are set.

4. Fiari four prices (futures)

Yesterday's high point, yesterday's low point, yesterday's closing price, and today's opening price can be collectively called the four prices of Fiari. It is the main breakout trading reference system used by Japanese futures champion Fiari. In addition, Yinfi Ali's subjective mental trading model determines that it also combines and uses a large number of "resistance and overflow lines" in actual transactions, that is, resistance lines and support lines.

Main features: Intraday trading strategy, close positions at closing; Fiari four prices refer to yesterday's high, yesterday's low, yesterday's close, and today's open; upper track = yesterday's high; lower track = yesterday's low; when the price breaks through the upper track, Buy to open a position; when the price falls below the lower track, sell to open a position.

Fiari four-price strategy source code:

import pandas as pd

# Load historical data data = pd.read_csv('data.csv')

# Calculate Fiari indicator

data['High_MA'] = data['High'].rolling(window=5).mean()

data['Low_MA'] = data['Low'].rolling(window=5).mean()

data['Close_MA'] = data['Close'].rolling(window=5).mean()

# Generate trading signals

data['Signal'] = 0

data.loc[(data['Close'] > data['High_MA']) & (data['Close'] > data['Close_MA']), 'Signal'] = 1

data.loc[(data['Close'] < data['Low_MA']) & (data['Close'] < data['Close_MA']), 'Signal'] = -1

# Calculate positions

data['Position'] = data['Signal'].diff()

# backtest

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

data['Strategy_Return'] = data['Position'].shift() * data['Return']

data['Cumulative_Return'] = (1 + data['Strategy_Return']).cumprod()

# Output results

print(data)

The code uses the pandas library to process data and calculate indicators. You need to install and import the library in advance. In addition, data.csv is a CSV file containing historical price data. You need to prepare the corresponding data files according to your own needs. At the same time, parameters can be set and adjusted according to the actual situation. In this example, the 5-day moving average is used as the calculation window of the Fiari indicator.

5. R-Breaker (futures)

R-Breaker is a short-term intraday trading strategy that has survived in the market for twenty years. Especially when the index fluctuates greatly, the strategy performs better. According to S&P statistics as of the end of 2011, R-Breaker -Break has also been ranked in the top ten many times. Since the performance of the trading systems entering the list is not stable, especially the one-year performance list, which often changes, the stability and consistency of the model are actually more critical than short-term rankings. The magazine gave the top ten trading models with the best consistency in the long term, including models such as R-Breaker. Their performance may not always be ranked in the top ten, but they have a high long-term performance. consistency.

R-Breaker strategy source code:

import pandas as pd

#Load historical data

data = pd.read_csv('data.csv')

#Set R-Breaker policy parameters

n = 20 # Bollinger channel calculation window

k1 = 0.4 # The threshold for breaking through the upper track

k2 = 0.4 # The threshold for breaking through the lower track

# Calculate Bollinger Bands indicator

data['MA'] = data['Close'].rolling(window=n).mean()

data['STD'] = data['Close'].rolling(window=n).std()

data['Upper'] = data['MA'] + k1 * data['STD']

data['Lower'] = data['MA'] - k2 * data['STD']

# Generate trading signals

data['Signal'] = 0

data.loc[data['Close'] > data['Upper'], 'Signal'] = 1 # Buy when the price breaks through the upper track

data.loc[data['Close'] < data['Lower'], 'Signal'] = -1 # Sell when the price breaks through the lower track

# Calculate positions

data['Position'] = data['Signal'].diff()

# backtest

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

data['Strategy_Return'] = data['Position'].shift() * data['Return']

data['Cumulative_Return'] = (1 + data['Strategy_Return']).cumprod()

# Output results

print(data)

The pandas library is used in the code to process data and calculate indicators. This library needs to be installed and imported in advance. In addition, data.csv is a CSV file containing historical price data. You need to prepare the corresponding data files according to your own needs. At the same time, you can also set and adjust the R-Breaker strategy parameters according to the actual situation. In this example, the Bollinger Band indicator is used to calculate the upper and lower rails, and the thresholds for breaking through the upper rail and the lower rail are set.

6. Bollinger Bands Mean Reversion (Futures)

The BOLL indicator is a very simple and practical technical analysis indicator designed by American stock market analyst John Bolin based on the standard deviation principle in statistics. Generally speaking, the movement of stock prices always moves within a certain range around a certain value center (such as moving average, cost line, etc.). It is on the basis of the above conditions that the Bollinger Bands indicator introduces the concept of "stock price channel" , which believes that the width of the stock price channel changes with the magnitude of the stock price fluctuation, and the stock price channel has variability, and it will automatically adjust as the stock price changes. Since most of the previous trading strategies were stock picking or trend following timing, we designed a mean reversion trading strategy based on this indicator.

Bollinger Bands Mean Reversion Strategy Source Code:

import pandas as pd

# Load historical data data = pd.read_csv('data.csv')

#Set Bollinger Band mean reversion strategy parameters

n = 20 # Bollinger channel calculation window

k = 2 # multiple of Bollinger band width

# Calculate Bollinger Bands indicator

data['MA'] = data['Close'].rolling(window=n).mean()

data['STD'] = data['Close'].rolling(window=n).std()

data['Upper'] = data['MA'] + k * data['STD']

data['Lower'] = data['MA'] - k * data['STD']

# Generate trading signals

data['Signal'] = 0

data.loc[data['Close'] < data['Lower'], 'Signal'] = 1 # Buy when the price is below the lower track

data.loc[data['Close'] > data['Upper'], 'Signal'] = -1 # Sell when the price is higher than the upper track

# Calculate positions

data['Position'] = data['Signal'].diff()

# backtest

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

data['Strategy_Return'] = data['Position'].shift() * data['Return']

data['Cumulative_Return'] = (1 + data['Strategy_Return']).cumprod()

# Output results

print(data)

The pandas library is used in the code to process data and calculate indicators. This library needs to be installed and imported in advance. In addition, data.csv is a CSV file containing historical price data. You need to prepare the corresponding data files according to your own needs. At the same time, you can also set and adjust the Bollinger Band mean reversion strategy parameters according to the actual situation. In this example, the Bollinger Band indicator is used to calculate the upper and lower rails, and the multiple of the Bollinger Band width is set.

7. Dual Thrust (futures)

Dual Thrust is a trend following system developed by Michael Chalek in the 1980s and has been named one of the most profitable strategies by Future Thrust magazine. The Dual Thrust system is easy to use and has wide applicability. It has a simple idea and few parameters. With different parameters, stop-profit, stop-loss and position management, it can bring long-term stable income to investors and is widely used by investors. Applied to stocks, currencies, precious metals, bonds, energy and stock index futures markets, etc.

R-Breaker strategy source code:

import pandas as pd

#Load historical data

data = pd.read_csv('data.csv')

#Set R-Breaker policy parameters

n = 20 # Calculate the window size of Bollinger Bands

m = 0.3 # Parameters for determining the breakout buying price

l = 0.3 # Parameters for determining breakout selling price #

Calculate Bollinger Bands indicator

data['MA'] = data['Close'].rolling(window=n).mean()

data['STD'] = data['Close'].rolling(window=n).std()

data['Upper'] = data['MA'] + m * data['STD']

data['Lower'] = data['MA'] - l * data['STD']

# Generate trading signals

data['Signal'] = 0

data.loc[data['Close'] > data['Upper'].shift(1), 'Signal'] = 1 # The price breaks through the upper track When buying data.loc[data['Close'] < data['Lower'].shift(1), 'Signal'] = -1 # Sell ​​when the price breaks through the lower band

# Calculate positions

data['Position'] = data['Signal'].diff()

# backtest

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

data['Strategy_Return'] = data['Position'].shift() * data['Return']

data['Cumulative_Return'] = (1 + data['Strategy_Return']).cumprod()

# Output results

print(data)

The pandas library is used in the code to process data and calculate indicators. This library needs to be installed and imported in advance. In addition, data.csv is a CSV file containing historical price data. You need to prepare the corresponding data files according to your own needs. At the same time, you can also set and adjust the R-Breaker strategy parameters according to the actual situation. In this example, the Bollinger Band indicator is used to calculate the upper and lower rails, and the parameters for the breakout buying price and the breakout selling price are set.

8. Grid trading (futures)

Grid trading is an active trading strategy that takes advantage of market fluctuations to make profits. Its essence is to use the repeated movement of the price of the investment target within the grid range during a period of volatile market conditions to increase or decrease positions in order to maximize investment returns. the goal of. In layman's terms, it is based on establishing grids of different quantities and sizes, opening positions when breaking through the grid, and reducing positions when returning to the grid, striving to capture the oscillating trend of prices and achieve the purpose of profit.

Grid trading strategy source code:

import pandas as pd

# Load historical data data = pd.read_csv('data.csv')

# Set grid trading strategy parameters

grid_size = 0.02 # Grid size

initial_price = data['Close'].iloc[0] # Initial price

num_grids = 10 # Number of grids

upper_price = initial_price * (1 + grid_size) # Upper limit price

lower_price = initial_price * (1 - grid_size) # Lower limit price

# Generate trading signals

data['Signal'] = 0

data.loc[data['Close'] >= upper_price, 'Signal'] = -1 # Sell when the price goes above the upper limit price data.loc[data[' ;Close'] <= lower_price, 'Signal'] = 1 # Buy when the price falls below the lower limit price

# Calculate positions

data['Position'] = data['Signal'].diff()

# backtest

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

data['Strategy_Return'] = data['Position'].shift() * data['Return']

data['Cumulative_Return'] = (1 + data['Strategy_Return']).cumprod()

# Output results

print(data)

The code uses the pandas library to process data, which needs to be installed and imported in advance. In addition, data.csv is a CSV file containing historical price data. You need to prepare the corresponding data files according to your own needs. At the same time, the grid trading strategy parameters can also be set and adjusted according to the actual situation. In this example, the grid size, grid quantity, upper limit price, and lower limit price are set.

9. Turtle Trading Method (Futures)

The turtle trading rule belongs to trend trading. First, establish the Donchian channel (explained in detail below), that is, determine the upper breakthrough line and lower breakthrough line. If the price breaks through the upper line, go long. If the price breaks through the lower line, close the position or go short.

Turtle Trading Strategy Source Code:

import pandas as pd

# Load historical data data = pd.read_csv('data.csv')

#Set turtle trading strategy parameters

entry_window = 20 # Entry window size

exit_window = 10 # Exit window size

n = 2 # Volatility unit multiple

# Calculate ATR indicator

data['High_Low'] = data['High'] - data['Low']

data['High_PreviousClose'] = abs(data['High'] - data['Close'].shift())

data['Low_PreviousClose'] = abs(data['Low'] - data['Close'].shift())

data['TR'] = data[['High_Low', 'High_PreviousClose', 'Low_PreviousClose']].max(axis=1)

data['ATR'] = data['TR'].rolling(window=entry_window).mean()

# Generate trading signals

data['Signal'] = 0

data.loc[data['Close'] > data['Close'].shift(), 'Signal'] = 1 # Buy when the price rises

data.loc[data['Close'] < data['Close'].shift(), 'Signal'] = -1 # Sell when the price drops out

# Calculate positions

data['Position'] = data['Signal'].diff()

# Exit conditions

data['Exit_Signal'] = data['Close'].rolling(window=exit_window).mean()

# backtest

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

data['Strategy_Return'] = data['Position'].shift() * data['Return']

data['Cumulative_Return'] = (1 + data['Strategy_Return']).cumprod()

# Output results

print(data)

10. Intertemporal arbitrage (futures)

Intertemporal arbitrage is a method of establishing trading positions of equal quantity and opposite direction on different month contracts of the same futures variety, and finally ending the transaction through hedging or delivery to obtain profits. The simplest intertemporal arbitrage is to buy the near-term futures variety and sell the forward futures variety.

Intertemporal arbitrage strategy source code:

import pandas as pd

# Load historical data data = pd.read_csv('data.csv')

#Set intertemporal arbitrage strategy parameters

near_contract = 'ContractA' # Near month contract

far_contract = 'ContractB' # Far month contract

# Generate trading signals

data['Signal'] = 0

data.loc[data[far_contract] - data[near_contract] > 0, 'Signal'] = 1 # Buy when the far-month contract price is higher than the near-month contract price

data.loc[data[far_contract] - data[near_contract] < 0, 'Signal'] = -1 # Sell when the far-month contract price is lower than the near-month contract price

# Calculate positions

data['Position'] = data['Signal'].diff()

# backtest

data['Return'] = data[near_contract].pct_change() # The return rate of the near-month contract is used as the strategy return rate

data['Strategy_Return'] = data['Position'].shift() * data['Return']

data['Cumulative_Return'] = (1 + data['Strategy_Return']).cumprod()

# Output results

print(data)

11. Cross-species arbitrage (futures)

Cross-variety arbitrage refers to using the contract price difference between two different but interrelated commodities to conduct arbitrage transactions, that is, buying a certain commodity contract in a certain delivery month and selling another mutually related commodity in the same delivery month. Commodity contracts, with a view to simultaneously hedging and closing the two contracts at a favorable opportunity to make a profit. The dominant idea of ​​cross-variety arbitrage is to find a relatively stable relationship (difference, ratio or other) between two or more different but related commodities, and take relevant reverse operations to obtain profits when they deviate from the normal track. . According to the relationship between arbitrage commodities, cross-variety arbitrage can be divided into two types: related commodity arbitrage and industrial chain cross-variety arbitrage.

Cross-variety arbitrage strategy source code:

import pandas as pd

# Load historical data data = pd.read_csv('data.csv')

#Set cross-variety arbitrage strategy parameters

productA = 'ProductA' # species A

productB = 'ProductB' # Variety B

# Generate trading signals

data['Signal'] = 0

data.loc[data[productB] - data[productA] > 0, 'Signal'] = 1 # When the price of variety B is higher than the price of variety A, buy variety A and sell variety B

data.loc[data[productB] - data[productA] < 0, 'Signal'] = -1 # When the price of variety B is lower than the price of variety A, sell variety A and buy variety B

# Calculate positions

data['Position'] = data['Signal'].diff()

# backtest

data['Return'] = data[productA].pct_change() # The rate of return of variety A is used as the strategy rate of return

data['Strategy_Return'] = data['Position'].shift() * data['Return']

data['Cumulative_Return'] = (1 + data['Strategy_Return']).cumprod()

# Output results

print(data)

The code uses the pandas library to process data. You need to install and import the library in advance. In addition, data.csv is a CSV file containing historical price data. You need to prepare the corresponding data files according to your own needs. At the same time, it is also necessary to set the names of variety A and variety B according to the actual situation, and generate buy and sell signals based on specific cross-variety arbitrage strategies. In this example, if the price of variety B is higher than the price of variety A, signals to buy variety A and sell variety B will be generated; if the price of variety B is lower than the price of variety A, signals to sell variety A and sell will be generated. Signal to buy type B.

Guess you like

Origin blog.csdn.net/v85365700536/article/details/131225908