Monday, December 26, 2022

Backtesting: A simple moving average in python.

 

Here is an example of how you can backtest a simple moving average strategy in Python:

 

Collect historical data for the asset you want to trade. You will need a dataset that includes the opening, closing, high, and low prices for each day.

Calculate the moving average for the asset using the closing prices and the desired number of days (in this case, 20).

Create a loop that will iterate through the dataset and apply the moving average strategy. For each day in the dataset, check if the closing price is above or below the moving average. If the closing price is above the moving average, you can assume that the asset is in an uptrend and consider buying. If the closing price is below the moving average, you can assume that the asset is in a downtrend and consider selling.

Calculate the profit or loss for each trade by comparing the entry price to the exit price.

After the loop has completed, calculate the overall profit or loss for the entire backtesting period.

Here is some sample code that demonstrates how to backtest a moving average strategy in Python:

 

Copy code

# Load the dataset

df = pd.read_csv('historical_data.csv')

# Calculate the 20-day moving average

df['20-day MA'] = df['Close'].rolling(20).mean()

# Initialize a list to store the trade results

results = []

# Iterate through the data and apply the moving average strategy

for index, row in df.iterrows():

  # If the closing price is above the moving average, buy

  if row['Close'] > row['20-day MA']:

    # Calculate the profit or loss

    result = row['Close'] - row['Open']

  # If the closing price is below the moving average, sell

  else:

    # Calculate the profit or loss

    result = row['Open'] - row['Close']

  # Append the result to the list

  results.append(result)

 

# Calculate the overall profit or loss

profit = sum(results)

print(f'Overall profit or loss: {profit}')

This code assumes that the historical data is stored in a CSV file called "historical_data.csv" and includes columns for the opening, closing, high, and low prices. The code calculates the 20-day moving average for the closing prices, then iterates through the data and applies the moving average strategy. The profit or loss for each trade is calculated and added to a list, and the overall profit or loss is calculated by summing the values in the list.

No comments:

Post a Comment

Backtesting: A simple moving average in python.

  Here is an example of how you can backtest a simple moving average strategy in Python:   Collect historical data for the asset you wan...