Rajandran R Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, USDINR and High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in)

Implementing Flip and Exrem Functions in Python Pandas Structure

2 min read

In (AFL), Flip and ExRem are two useful functions often used in trading system development. Let’s explore each of them:

Flip Function

The Flip function is used to toggle a variable between two states (True and False) based on two given conditions. This function is particularly useful for tracking the state of a trade or an indicator between two events, such as entry and exit signals in a trading strategy.

Syntax: Flip(Buy, Sell)

  • Buy and Sell are conditions (expressions that return True or False).
  • When Buy is True, Flip returns True.
  • Once Flip has flipped to True, it stays True until Sell becomes True.

Example Usage:

Buy = Cross(MA(Close, 5), MA(Close, 20)); // Buy when short MA crosses above long MA
Sell = Cross(MA(Close, 20), MA(Close, 5)); // Sell when long MA crosses above short MA
Buycontinue = Flip(Buy, Sell); // Buycontinue is True between Buy and Sell signals

In this example, Buycontinue will be True from the point where the Buy condition is met until the Sell condition occurs.

ExRem Function

The ExRem function stands for “Exclude Remnant” and is used to eliminate opposing signals within a given window. Essentially, it ensures that once a Buy or Sell signal is given, subsequent signals of the opposite type are ignored until an opposing signal is generated.

Syntax: ExRem(Buy, Sell)

  • Buy and Sell are again conditions.
  • ExRem removes remnant (extra) Buy signals that occur after the first Buy signal and before the first Sell signal. The same logic applies to Sell signals.

Example Usage:

Buy = Cross(MA(Close, 5), MA(Close, 20)); 
Sell = Cross(MA(Close, 20), MA(Close, 5));
Buy = ExRem(Buy, Sell); // Removes extra Buy signals after the first Buy and before the first Sell
Sell = ExRem(Sell, Buy); // Removes extra Sell signals after the first Sell and before the first Buy

Here, ExRem is used to filter out additional Buy signals that occur after an initial Buy and before the next Sell signal, and vice versa for Sell signals.

Both Flip and ExRem are powerful tools in the AFL toolbox, particularly useful for signal processing in trading strategies to manage entry and exit points more effectively. They help in simplifying the logic and avoiding unnecessary trades or signal overlaps.

Code Implementation of Flip and Exrem Functions in Pandas Dataframe

The provided code defines two functions, exrem and flip, both of which are designed to work with boolean series in a pandas DataFrame. These functions are modeled after the ExRem and Flip functions in AmiBroker Formula Language (AFL).

import pandas as pd

def exrem(series1, series2):
    """
    Mimics the ExRem function.
    After a True signal in series1, it ignores subsequent True signals in series2 until a new True signal in series1.
    """
    in_position = False
    clean_series1 = pd.Series(False, index=series1.index)

    for i in range(len(series1)):
        if series1.iloc[i] and not in_position:
            clean_series1.iloc[i] = True
            in_position = True
        elif series2.iloc[i] and in_position:
            in_position = False

    return clean_series1

def flip(series1, series2):
    """
    Mimics the Flip function.
    Toggles a state between True and False based on True signals in series1 and series2.
    """
    state = False
    flipped_state = pd.Series(False, index=series1.index)

    for i in range(len(series1)):
        if series1.iloc[i]:
            state = True
        elif series2.iloc[i]:
            state = False
        flipped_state.iloc[i] = state

    return flipped_state

# Example DataFrame
data = {'Buy': [False, True, False,True,False, False, True, True, False, False],
        'Sell': [False, False, False, False, True, True, False, False, True, True]}
df = pd.DataFrame(data)

# Apply the exrem function
df['ExremData'] = exrem(df['Buy'], df['Sell'])

# Apply the flip function
df['FlipData'] = flip(df['Buy'], df['Sell'])

print(df)

Output

    Buy   Sell  ExremData  FlipData
0  False  False      False     False
1   True  False       True      True
2  False  False      False      True
3   True  False      False      True
4  False   True      False     False
5  False   True      False     False
6   True  False       True      True
7   True  False      False      True
8  False   True      False     False
9  False   True      False     False
Rajandran R Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, USDINR and High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in)

Building a Google Gemini Digital Assistant Slack Bot :…

In an era where efficiency is key, integrating a digital assistant into Slack using Google Gemini's AI technology offers a transformative solution. This guide...
Rajandran R
10 min read

Leveraging Jupyter AI for Traders and Investors – Python…

Jupyter AI provides a state-of-the-art resource for data scientists, data analysts, and traders/investors, boosting their Python programming productivity and efficiency. This tool significantly enhances...
Rajandran R
2 min read

VectorBT Streamlit Backtesting App – Python Tutorial

This Streamlit application is designed for backtesting trading strategies using the VectorBT library in Python. It provides a user-friendly interface to input various parameters...
Rajandran R
4 min read

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More