<jupyter_start><jupyter_text>This is where I found the code for calculating the Average True Range (ATR)

https://www.learnpythonwithrune.org/calculate-the-average-true-range-atr-easy-with-pandas-dataframes/<jupyter_code># high_low = df['High'] - df['Low']
# high_close = np.abs(df['High'] - df['Close'].shift())
# low_close = np.abs(df['Low'] - df['Close'].shift())

# ranges = pd.concat([high_low, high_close, low_close], axis=1)
# true_range = np.max(ranges, axis=1)

# window = 14

# atr = true_range.rolling(window).sum() / window
# df['ATR'] = atr
# df.head(20)

pattern_function = getattr(talib, 'CDLDOJI')
symbol = 'MSFT'
result = pattern_function(df['Open'], df['High'], df['Low'], df['Close'])
df['DOJI'] = result
last = result.tail(1).values[0]
df

atr_function = getattr(talib, 'ATR')

atr_result = atr_function(df['High'], df['Low'], df['Close'], timeperiod=14)

atr_factor = 2.5

df['Trailing Stop'] = df['Close'] - (atr_result * atr_factor)
df['Long Entry'] = np.nan

for index, row in df.iterrows():
    if row['DOJI'] > 0:
        df.loc[index, 'Long Entry'] = 1
    else:
        df.loc[index, 'Long Entry'] = 0
df['Pct Change'] = df['Close'].pct_change()
df['Initialize Stop Loss'] = np.where(df['Long Entry']==1,df['Trailing Stop'],0.0)
df['Recalculate Stop Loss Once in Trade'] = np.nan

for index, row in df.iterrows():
    if row['Initialize Stop Loss'] > 0.0:
        df.loc[index, 'Recalculate Stop Loss Once in Trade'] = row['Initialize Stop Loss']

    elif row['Initialize Stop Loss'] > 0.0 or row['Pct Change'] > 0.0:
        if row['Trailing Stop'] > row['Recalculate Stop Loss Once in Trade'].shift(1):
            df.loc[index,'Recalculate Stop Loss Once in Trade'] = row['Trailing Stop']
        else:
            df.loc[index,'Recalculate Stop Loss Once in Trade'] = df.loc[index, 'Recalculate Stop Loss Once in Trade'].shift(1)
    
    else:
        df.loc[index,'Recalculate Stop Loss Once in Trade'] = row['Recalculate Stop Loss Once in Trade'].shift(1)
df.tail(40)




# df['Stop Loss'] =

# atr_multiplier = 2.5
# previous_close = 0
# previous_stop = 0

# for index, row in df.iterrows():
#     if row['DOJI'] > 0:
#         df.loc[index, 'Long'] = 1
#         df.loc[index, "Stop Loss"] = row['Close'] - (row['ATR'] * atr_multiplier) 
          
#     elif row['Close'] >= previous_close:
#         df.loc[index, 'Long'] = 1
#         df.loc[index, "Stop Loss"] = row['Close'] - (row['ATR'] * atr_multiplier) 
    
#     elif row['Close'] <= previous_close:
#         df.loc[index, 'Long'] = 1
#         df.loc[index, "Stop Loss"] = previous_stop

#     elif row['Low'] >= previous_stop:
#         df.loc[index, 'Long'] = -1
#         df.loc[index, "Stop Loss"] = row['Close'] - (row['ATR'] * atr_multiplier)

#     else:
#         df.loc[index, 'Long'] = 0

         

    
#     previous_stop = row['Close'] - (row['ATR'] * atr_multiplier)
#     previous_close = row['Close']

df.tail(40)
equity_balance = 20000
expected_return = 1.6
prob_win = 0.7
prob_loss = 1 - prob_win

pct_equity = (expected_return * prob_win - prob_loss) / expected_return
full_kelly = pct_equity * equity_balance
fractional_kelly = 0.33 * full_kelly

fractional_kelly

df['Exit'] = df['Close'] + df['Dynamic Stop Loss']
df.dropna()
df['Equity Balance'] = equity_balance

import hvplot.pandas

# Visualize entry position relative to close price
entry = signals_df[signals_df["Entry/Exit"] == 1.0]["Close"].hvplot.scatter(
    color='purple',
    marker='^',
    size=200,
    legend=False,
    ylabel='Price in $',
    width=1000,
    height=400
)

# Visualize exit position relative to close price
exit = signals_df[signals_df["Entry/Exit"] == -1.0]["Close"].hvplot.scatter(
    color='orange',
    marker='v',
    size=200,
    legend=False,
    ylabel='Price in $',
    width=1000,
    height=400
)

# Visualize close price for the investment
security_close = signals_df[["Close"]].hvplot(
    line_color='lightgray',
    ylabel='Price in $',
    width=1000,
    height=400
)

# Visualize moving averages
moving_avgs = signals_df[["SMA50", "SMA200"]].hvplot(
    ylabel='Price in $',
    width=1000,
    height=400
)

# Overlay plots
entry_exit_plot = security_close * moving_avgs * entry * exit
entry_exit_plot<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.16355353075170842, 'fraction_numerical': 0.022095671981776765, 'mean_word_length': 3.1978967495219885, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 13, 'https://': 1, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '288970', 'license': 'MIT', 'n_tokens_mistral': 1675, 'n_tokens_neox': 1584, 'n_words': 349, 'path': 'entry_exit/average_true_range.ipynb', 'repo_name': 'billybishop21/Algo_Signals_2.0', 'size': '4390'}