13.08.2022 Views

advanced-algorithmic-trading

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

314

alldays = DayLocator()

weekFormatter = DateFormatter("")

fig, ax = plt.subplots(figsize=(16,4))

ax.xaxis.set_major_locator(mondays)

ax.xaxis.set_minor_locator(alldays)

ax.xaxis.set_major_formatter(weekFormatter)

# Sort the data by the cluster values and obtain

# a separate DataFrame listing the index values at

# which the cluster boundaries change

df = copy.deepcopy(data)

df.sort_values(by="Cluster", inplace=True)

df.reset_index(inplace=True)

df["clust_index"] = df.index

df["clust_change"] = df["Cluster"].diff()

change_indices = df[df["clust_change"] != 0]

# Plot the OHLC chart with cluster-ordered "candles"

csticks = candlestick_ohlc(

ax, df[

["clust_index", ’Open’, ’High’, ’Low’, ’Close’]

].values, width=0.6,

colorup=’#000000’, colordown=’#ff0000’

)

ax.set_axis_bgcolor((1,1,0.9))

# Add each of the cluster boundaries as a blue dotted line

for row in change_indices.iterrows():

plt.axvline(

row[1]["clust_index"],

linestyle="dashed", c="blue"

)

plt.xlim(0, len(df))

plt.setp(

plt.gca().get_xticklabels(),

rotation=45, horizontalalignment=’right’

)

plt.show()

The final function is create_follow_cluster_matrix. Its job is to produce a K×K matrix,

where K is the number of selected clusters in the K-Means Clustering process. Each element of

the matrix represents the percentage frequency of cluster j being the daily follow-on cluster to

cluster i. This is useful in a quantitative trading setting as it allows determination of the sample

distribution of cluster changes.

The matrix is constructed using the Pandas shift method, which allows a new column

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!