follow the market

Add Your Heading Text Here

This market following algorithm uses no classic indicators, but instead follows the market by comparing the current price to the previous price. If the current price is higher than the previous price, it enters a long position. If the current price is lower than the previous price, it enters a short position. The algorithm also has a small profit taking gap, which it uses to check for profit taking opportunities. If the current price is higher than the previous

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Define a class for the market following algorithm
class MarketFollowingAlgo:
    def __init__(self, data, gap=0.01):
        self.data = data
        self.gap = gap
        self.positions = []
        self.profits = []
        
    def follow_market(self):
        for i in range(1, len(self.data)):
            # Check if the current price is higher than the previous price
            if self.data[i] > self.data[i-1]:
                # If so, enter a long position
                self.positions.append(1)
                # Check for profit taking opportunity by comparing current price to previous price + gap
                if self.data[i] >= self.data[i-1] + self.gap:
                    # If so, exit the position and record the profit
                    self.positions.pop()
                    profit = self.data[i] - self.data[i-1] - self.gap
                    self.profits.append(profit)
            # Check if the current price is lower than the previous price
            elif self.data[i] < self.data[i-1]:
                # If so, enter a short position
                self.positions.append(-1)
                # Check for profit taking opportunity by comparing current price to previous price - gap
                if self.data[i] <= self.data[i-1] - self.gap:
                    # If so, exit the position and record the profit
                    self.positions.pop()
                    profit = self.data[i-1] - self.data[i] - self.gap
                    self.profits.append(profit)
                    
    def plot_results(self):
        # Plot the data and positions
        plt.plot(self.data, '-', label='Data')
        for i in range(len(self.positions)):
            if self.positions[i] == 1:
                plt.axvline(i, color='g', linestyle='--', label='Long Position')
            elif self.positions[i] == -1:
                plt.axvline(i, color='r', linestyle='--', label='Short Position')
        plt.legend()
        plt.show()
        
        # Plot the profits
        plt.plot(self.profits, '-', label='Profits')
        plt.legend()
        plt.show()

# Create an instance of the algorithm and run it on example data
data = [100, 101, 99, 102, 98, 101, 105, 110, 115, 120]
algo = MarketFollowingAlgo(data, gap=0.02)
algo.follow_market()
algo.plot_results()

Leave a Reply