Skip to content

Instantly share code, notes, and snippets.

@yongghongg
Created November 7, 2021 09:15
Show Gist options
  • Save yongghongg/6512ffad3be8c0c90948815e19c40de1 to your computer and use it in GitHub Desktop.
Save yongghongg/6512ffad3be8c0c90948815e19c40de1 to your computer and use it in GitHub Desktop.
final_result_df = pd.DataFrame()
# read from local data
for symbol in os.listdir('price_data/'):
df = pd.read_csv(f'price_data/{symbol}')
if df.empty:
continue
df.replace('', np.nan, inplace=True)
df.dropna(inplace=True)
df.ta.cdl_pattern(name="all", append=True)
result_df = pd.DataFrame(columns = ['Trade', 'Win', 'Loss'])
# for each candlestick pattern
for pattern in df.columns[7:]:
hold = False
trades = 0
success_trades = 0
fail_trades = 0
for i in range(len(df.index)-1):
try:
# if value is 100 -> pattern is detected
if not hold and df[pattern][i] == 100.0:
# enter at open price the next day
entry = df['Open'][i+1]
hold = True
# set Stop Loss (SL) = 5%, Profit Target (PT) = 10%
stop_loss = entry * 0.95
profit_target = entry * 1.1
# see which one is hit first
elif hold and df['Close'][i] > profit_target:
hold = False
trades += 1
success_trades += 1
elif hold and df['Close'][i] < stop_loss:
hold = False
trades += 1
fail_trades += 1
except:
continue
result_df.loc[pattern] = [trades, success_trades, fail_trades]
# append to final_result_df
if final_result_df.empty:
final_result_df = result_df
else:
final_result_df = final_result_df.add(result_df)
@fredthedead
Copy link

Hi, great post, and thanks for providing the code!

Shouldn't line 31 be df['High'] rather than close? The stock might have reached the profit target before close and then dropped...

(similarly, in line 35 - 'Low' instead of 'Close')

Curious how that would impact the results 🤔

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment