Advertisement
Guest User

Untitled

a guest
Feb 9th, 2024
570
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.01 KB | Software | 0 0
  1. import numpy as np
  2. import pandas as pd
  3.  
  4. def calculate_fractals(high, low):
  5.     """
  6.    Calculate up and down fractals. A simplistic approach.
  7.    """
  8.     up_fractal = (high.shift(1) < high) & (high.shift(-1) < high)
  9.     down_fractal = (low.shift(1) > low) & (low.shift(-1) > low)
  10.     return up_fractal, down_fractal
  11.  
  12. def calculate_atr(high, low, close, period=14):
  13.     """
  14.    Calculate Average True Range (ATR).
  15.    """
  16.     tr = pd.DataFrame({
  17.         'high-low': high - low,
  18.         'high-close_prev': abs(high - close.shift()),
  19.         'low-close_prev': abs(low - close.shift())
  20.     }).max(axis=1)
  21.     atr = tr.rolling(window=period).mean()
  22.     return atr
  23.  
  24. def calculate_stop_loss_and_take_profit(high, low, close, risk_reward_ratio, atr_multiplier_for_trailing_stop):
  25.     """
  26.    Calculate stop loss and take profit.
  27.    """
  28.     up_fractal, down_fractal = calculate_fractals(high, low)
  29.     # Example for a long position. For short positions, use down fractal and adjust logic accordingly.
  30.     recent_swing_high = high[up_fractal].max()  # This is a simplification
  31.     stop_loss = recent_swing_high + buffer_pips  # Adjust buffer_pips as needed
  32.  
  33.     # Assuming a risk_reward_ratio of 1:2 for example
  34.     risk_amount = stop_loss - entry_price  # Assuming a long position
  35.     target_profit = entry_price + (risk_amount * risk_reward_ratio)
  36.  
  37.     # Trailing stop and take profit logic to be implemented based on the strategy
  38.  
  39.     return stop_loss, target_profit
  40.  
  41. # Example usage
  42. # This assumes you have a DataFrame `df` with 'High', 'Low', and 'Close' columns
  43. # entry_price = df['Close'].iloc[-1]  # Just as an example, adjust based on your strategy
  44. # risk_reward_ratio = 2  # Example for a 1:2 risk/reward ratio
  45. # atr_multiplier_for_trailing_stop = 1.5  # Example multiplier for ATR in trailing stop
  46. # stop_loss, take_profit = calculate_stop_loss_and_take_profit(df['High'], df['Low'], df['Close'], risk_reward_ratio, atr_multiplier_for_trailing_stop)
  47. # print(f"Stop Loss: {stop_loss}, Take Profit: {take_profit}")
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement