Shapely找不到肯定存在的交点

问题描述 投票:0回答:1

在我的代码中,我有两条线(line1、line2),它们在视觉上肯定是彼此相交的。它们只是从 yfinance 中抓取数据的库存线,但运行 line1.intersect(line2) 时,它返回没有交点。为了清晰起见,我附上了一些照片(请注意图表图例中的 line1=SMA-50,line2=SMA-200)

The visual intersection

这是代码的当前部分:

        new50 = sma50.to_frame().reset_index() #set series to dataframe & preserve date as column
        new200 = sma200.to_frame().reset_index()

        new50.Date = pd.to_numeric(pd.to_datetime(new50.Date.dt.date)) #removing time from datetime, converting to numeric
        new200.Date = pd.to_numeric(pd.to_datetime(new200.Date.dt.date))
        new50.Close = round(new50.Close,1) #round to see if I can obtain intersections...
        new200.Close= round(new200.Close,1)

        line1 = LineString(np.column_stack([new50.Close, new50.Date]))
        line2 = LineString(np.column_stack([new200.Close, new200.Date]))

        print(line1.intersection(line2))

这就是其中一个数据帧(new200)的样子,以及我在打印时得到的响应

line1.intersection(line2)

                    Date  Close
0    1644796800000000000    NaN
1    1644883200000000000    NaN
2    1644969600000000000    NaN
3    1645056000000000000    NaN
4    1645142400000000000    NaN
..                   ...    ...
495  1707091200000000000  442.7
496  1707177600000000000  444.7
497  1707264000000000000  446.9
498  1707350400000000000  449.0
499  1707436800000000000  451.3

[500 rows x 2 columns]
LINESTRING Z EMPTY

我尝试对数字进行四舍五入,看看是否可以通过这种方式获得交叉点。不幸的是这个方法并没有奏效。我还从日期时间中删除了时间,以查看没有交集的原因是否是由于我的数据太精确。我也在互联网上查看是否可以找到解决方案,但这种方法没有太多运气。

我已经看到了使用 numpy np.diff() 的潜在解决方案,我现在将对其进行测试 - 但是,我认为了解为什么 Shapely 无法识别这个交叉点或者这是我自己的错误会很有趣。

我在网上查了很多,但没有运气——希望得到任何帮助。谢谢大家!

python intersection stock shapely stockquotes
1个回答
0
投票

作为可能打印状态的警告,

LineString()
的输入包含无效值:

RuntimeWarning: invalid value encountered in linestrings

在无效的几何图形上调用像

intersection
这样的函数会导致未定义的行为,这就是您所看到的。

如果您在创建线串之前使用

dropna()
删除具有无效
NaN
坐标值的行,您应该会得到预期的结果:

import numpy as np
import pandas as pd
from shapely import LineString

dates = [
    1644796800000000000,
    1644883200000000000,
    1644969600000000000,
    1645056000000000000,
]
new50 = pd.DataFrame({"Date": dates, "Close": [np.nan, 410.0, 420.0, 500.0]})
new200 = pd.DataFrame({"Date": dates, "Close": [np.nan, 550.0, 500.0, 420.0]})

line1 = LineString(np.column_stack([new50.Close, new50.Date]))
line2 = LineString(np.column_stack([new200.Close, new200.Date]))
print(f"original: {line1.intersection(line2)}")

new50 = new50.dropna()
new200 = new200.dropna()

line1 = LineString(np.column_stack([new50.Close, new50.Date]))
line2 = LineString(np.column_stack([new200.Close, new200.Date]))
print(f"after dropna: {line1.intersection(line2)}")

结果:

original: LINESTRING EMPTY
after dropna: POINT (460 1645012800000000000)
© www.soinside.com 2019 - 2024. All rights reserved.