Skip to content

Instantly share code, notes, and snippets.

# Obtain the prediction feature with the above function
data['y'] = triple_barrier_method(data, holding_period=10, upper_lower_multipliers=[2, 1])
# Import the Apple dataframe
data ='AAPL', start='1990-01-01', end='2024-04-04', auto_adjust=True)
# Compute the daily volatility
data['vol'] = get_Daily_Volatility(data)
# Drop the rows that have NaN values
def triple_barrier_method(df, holding_period=10, upper_lower_multipliers=[2, 1]):
# Set the close price as a cupy array
close = cp.array(df['Close'].values, dtype=cp.float64)
# Set the high price as a cupy array
high = cp.array(df['High'].values, dtype=cp.float64)
# Set the low price as a cupy array
low = cp.array(df['Low'].values, dtype=cp.float64)
# Set the daily volatility as a cupy array
daily_volatility = cp.array(df['vol'].values, dtype=cp.float64)
# Set the barriers empty array as a cupy array
def triple_barrier_method_cuda(close, high, low, daily_volatility, upper_lower_multipliers, holding_period, out):
# Set the number days passed to zero
days_passed = 0
# Set the vertical barrier initial value to NaN
vert_barrier = math.nan
# Set the top barrier initial value to NaN
top_barrier = math.nan
# Set the bottom barrier initial value to NaN
def get_Daily_Volatility(df,span0=20):
# simple percentage returns
# 20 days, a month EWM's std as boundary
df0=df0.ewm(span = span0, adjust = False).std()
# Round the column values to six decimals
df0 = df0.round(6)
return df0
def dropLabels(events,minPct=.05):
# apply weights, drop labels with insufficient examples
while True:
# Count the number of observations the prediction feature has for each label
# If the label with minimum number of observations is lower than the minPct threshold
# or the number of labels in the prediction features is 2, then break the while loop
if (df0.min()>minPct) or (df0.shape[0]<3):break
# Drop the label with minimum number of observations
events = events[events['y']!=df0.index[df0.argmin()]]
import numpy as np
from numba import cuda
import math
import cupy as cp
import cudf
import yfinance as yf
# Set the figure size
# Plot both the benchmark and strategy returns
plt.plot(df_results.index, df_results['Benchmark'], label = "Benchmark Cumulative Returns")
plt.plot(df_results.index, df_results['Stra_cum_returns'], label = "Strategy Returns", color='g')
# Set the title of the graph
plt.title('Benchmark and Strategy Cumulative Returns using a 1-year span', fontsize=16)
# Create the signal
df_results['signal'] = np.where(df_results['forecast']>=0.0,1,-1)
# Create the Buy and Hold returns
df_results['returns'] = np.log(df_results['Close']/df_results['Close'].shift(1))
# Create the Buy and Hold cumulative returns
df_results['Benchmark'] = df_results['returns'].cumsum()
# Create the strategy returns