Files
strategy-lab/to_explore/pyquantnews/109_Expectancy.ipynb
David Brazda e3da60c647 daily update
2024-10-21 20:57:56 +02:00

4.6 KiB

No description has been provided for this image

This code calculates the expectancy ratio of a series of trades. The expectancy ratio measures the average expected return per trade by considering the win rate, loss rate, and average profit/loss of trades. It is useful in financial trading to evaluate the performance of a trading strategy. The input is a DataFrame of trades with profit or loss values. The output is a single expectancy ratio value.

In [ ]:
import pandas as pd
import numpy as np

Define a function to calculate the expectancy ratio of trades.

In [ ]:
def calculate_expectancy_ratio(trades):
    """Calculate the expectancy ratio of trades.
    
    This function computes the average expected return for a series of trades 
    by considering their win rate, loss rate, and average profit/loss.
    
    Parameters
    ----------
    trades : pd.DataFrame
        DataFrame containing trade information with a 'Profit' column.
    
    Returns
    -------
    expectancy_ratio : float
        The calculated expectancy ratio.
    """
    
    # Calculate the number of trades
    num_trades = len(trades)
    
    # Separate winning and losing trades
    winners = trades[trades['Profit'] > 0]
    losers = trades[trades['Profit'] <= 0]
    
    # Calculate win rate and loss rate
    win_rate = len(winners) / num_trades
    loss_rate = len(losers) / num_trades
    
    # Calculate average profit for winning trades and average loss for losing trades
    avg_win = winners['Profit'].mean()
    avg_loss = losers['Profit'].mean()
    
    # Compute the expectancy ratio
    expectancy_ratio = (win_rate * avg_win) + (loss_rate * avg_loss)
    
    return expectancy_ratio

Create a dictionary with trade data including trade numbers and corresponding profits/losses.

In [ ]:
trade_data = {
    'Trade': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    'Profit': [100, -50, 200, -100, 300, -150, 400, -200, 500, -250]
}

Convert the trade data dictionary into a pandas DataFrame.

In [ ]:
trades = pd.DataFrame(trade_data)

Calculate the expectancy ratio using the defined function and print the result.

In [ ]:
expectancy_ratio = calculate_expectancy_ratio(trades)
print(f"Expectancy Ratio: {expectancy_ratio}")

PyQuant News is where finance practitioners level up with Python for quant finance, algorithmic trading, and market data analysis. Looking to get started? Check out the fastest growing, top-selling course to get started with Python for quant finance. For educational purposes. Not investment advise. Use at your own risk.