python k线分型
时间: 2024-12-26 20:27:16 浏览: 1
### K线分型算法的Python实现
为了实现K线分型,在处理过程中需要考虑两个主要方面:一是识别并消除相邻K线之间的包含关系;二是基于调整后的K线条目来判断顶分型和底分型。
#### 处理包含关系
当遇到一个K线的价格区间完全被另一个所覆盖的情况时,这被称为包含关系。对于这种情况,如果趋势是上升,则取两者之中较高的最高价作为新K线的高价,并选取其中较高的最低价作为低价;如果是下降趋势,则相反操作——即采用更低的最低价以及相对应的更高一点的最高价格形成新的K线数据条目[^4]。
```python
def remove_inclusion(klines):
adjusted_klines = []
i = 0
while i < len(klines) - 1:
current_high, current_low = klines[i]['high'], klines[i]['low']
next_high, next_low = klines[i + 1]['high'], klines[i + 1]['low']
if (current_high >= next_high and current_low <= next_low): # 当前K线包含下一个K线
combined_high = max(current_high, next_high)
combined_low = min(current_low, next_low)
new_kline = {
'open': klines[i]['open'],
'close': klines[i + 1]['close'],
'high': combined_high,
'low': combined_low
}
adjusted_klines.append(new_kline)
i += 2
elif (next_high >= current_high and next_low <= current_low): # 下一个K线包含当前K线
combined_high = max(next_high, current_high)
combined_low = min(next_low, current_low)
new_kline = {
'open': klines[i]['open'],
'close': klines[i + 1]['close'],
'high': combined_high,
'low': combined_low
}
adjusted_klines[-1] = new_kline
i += 2
else:
adjusted_klines.append({
'open': klines[i]['open'],
'close': klines[i]['close'],
'high': klines[i]['high'],
'low': klines[i]['low']
})
i += 1
return adjusted_klines
```
#### 判断顶分型与底分型
一旦完成了上述步骤,就可以进一步分析这些不含有任何包含关系的连续三个K线组合是否构成有效的顶分型或底分型模式。具体来说:
- **顶分型**发生在中间那根K线具有最高的高点且两侧各有一根较低的低点;
- **底分型**则正好相反,指的是位于中央位置的那个K线拥有最低的低点并且其两边分别存在更高的高点[^3]。
```python
def find_divergences(adjusted_klines):
divergences = []
for i in range(1, len(adjusted_klines)-1):
mid_price = adjusted_klines[i]['close']
prev_higher = adjusted_klines[i-1]['high'] < adjusted_klines[i]['high']
post_lower = adjusted_klines[i+1]['low'] > adjusted_klines[i]['low']
is_top_divergence = all([prev_higher, post_lower])
prev_lower = adjusted_klines[i-1]['low'] > adjusted_klines[i]['low']
post_higher = adjusted_klines[i+1]['high'] < adjusted_klines[i]['high']
is_bottom_divergence = all([prev_lower, post_higher])
if is_top_divergence or is_bottom_divergence:
divergence_type = "Top Divergence" if is_top_divergence else "Bottom Divergence"
divergences.append({
'index': i,
'type': divergence_type,
'price': mid_price
})
return divergences
```
通过以上函数`remove_inclusion()`可以先移除所有的包含关系,之后再利用`find_divergences()`去寻找可能存在的顶分型或是底分型特征。最终返回的结果将是那些满足条件的位置索引及其对应类型的列表对象。
阅读全文