fastdtw计算两个股票序列之间的相似性(最小距离)

fastdtw计算两个股票序列之间的相似性(最小距离)

1.动态时间扭曲 (DTW)

Dynamic time warping:动态时间扭曲 (DTW) 是一种在两个时间序列之间找到最佳对齐的技术,其中一个时间序列可以通过拉伸或收缩其时间轴来非线性地“扭曲”。 这种比对可用于找到对应的区域或确定两个时间序列之间的相似性。
DTW 经常用于语音识别,以确定两个波形是否代表相同的口语短语。 在语音波形中,每个语音的持续时间和声音之间的间隔是允许变化的,但整体语音波形必须相似。
既然是时间序列的数据对比,分析相似度,那么当然也可以用于分析两个股票走势的相似度。

2. 随机序列验证测试

用随机数测试:

import numpy as np
import fastdtw

# 定义两个时间序列
series1 = np.random.rand(20)  # 使用 rand 生成 [0, 1) 内的随机数  
series2 = np.random.rand(20)  # 同样生成 [0, 1) 内的随机数  

# 使用fastdtw计算这两个序列之间的最小距离
distance, path = fastdtw.fastdtw(series1, series2)
 
print('FastDTW distance:', distance)

FastDTW distance: 4.126319461445138

数据范围,变化不大,距离很小,相似度高。

3.时间序列验证测试

通过两个曲线验证一下距离,理解fastdtw函数:

# 数据标准化函数
def standardize_data(df):
    return (df - df.mean()) / df.std()

def show_plot(amplitude_a,amplitude_b):
    # 使用fastdtw计算这两个序列之间的最小距离
    distance, path = fastdtw.fastdtw(standardize_data(amplitude_a), standardize_data(amplitude_b))
     
    print('FastDTW distance:', distance)
    
    # 计算相似度
    distance = m._dtw_distance(standardize_data(amplitude_a), standardize_data(amplitude_b))
    print('FastDTW distance:', distance)
    
    
    # 创建一个大图,包含两个子图  
    fig, axs = plt.subplots(2, 1, figsize=(12, 8))  
      
    # 第一个子图:展示标准化后的数据  
    axs[0].plot(time, standardize_data(amplitude_a), label='amplitude_a_stand')  
    axs[0].plot<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值