- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想为股票创建一个锯齿形指标。我正在使用 python,我的英语不好,所以我对此表示歉意。我的部分代码来自:Pandas: Zigzag segmentation of data based on local minima-maxima
问题是我想要的曲折是这样的(Metastock 曲折指标): 我的曲折代码看起来像(注意你可以用过滤器改变百分比):
from pandas_datareader import data
import pandas as pd
from datetime import date
from pandas_datareader.nasdaq_trader import get_nasdaq_symbols
from scipy import signal
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
np.random.seed(0)
def filter(values, percentage):
previous = values[0]
mask = [True]
for value in values[1:]:
relative_difference = np.abs(value - previous)/previous
if relative_difference > percentage:
previous = value
mask.append(True)
else:
mask.append(False)
return mask
def main(stock=None, start_date=None, end_date=None):
df = data.DataReader(
stock,
start=start_date, end=end_date,
data_source='yahoo'
)
return df
if __name__ == '__main__':
today = '{}'.format(date.today())
stocks = ['BLL']
cont = 0
for stock in stocks:
cont += 1
try:
serie = main(stock=stock, start_date='2018-1-1', end_date=today)
serie.insert(loc=0, column='Date', value=serie.index)
serie = serie.reset_index(drop=True)
# Create zigzag trendline.
########################################
# Find peaks(max).
data_x = serie.index.values
data_y = serie['Close'].values
peak_indexes = signal.argrelextrema(data_y, np.greater)
peak_indexes = peak_indexes[0]
# Find valleys(min).
valley_indexes = signal.argrelextrema(data_y, np.less)
valley_indexes = valley_indexes[0]
# Merge peaks and valleys data points using pandas.
df_peaks = pd.DataFrame({'date': data_x[peak_indexes], 'zigzag_y': data_y[peak_indexes]})
df_valleys = pd.DataFrame({'date': data_x[valley_indexes], 'zigzag_y': data_y[valley_indexes]})
df_peaks_valleys = pd.concat([df_peaks, df_valleys], axis=0, ignore_index=True, sort=True)
# Sort peak and valley datapoints by date.
df_peaks_valleys = df_peaks_valleys.sort_values(by=['date'])
p = 0.1 # 20%
filter_mask = filter(df_peaks_valleys.zigzag_y, p)
filtered = df_peaks_valleys[filter_mask]
# Instantiate axes.
(fig, ax) = plt.subplots(figsize=(10,10))
# Plot zigzag trendline.
ax.plot(df_peaks_valleys['date'].values, df_peaks_valleys['zigzag_y'].values,
color='red', label="Extrema")
# Plot zigzag trendline.
ax.plot(filtered['date'].values, filtered['zigzag_y'].values,
color='blue', label="ZigZag")
# Plot original line.
ax.plot(data_x, data_y, linestyle='dashed', color='black', label="Org. line", linewidth=1)
plt.show()
print('{} - {}| success'.format(cont, stock))
except Exception:
print('{} - {}| ERROR'.format(cont, stock))
最佳答案
这是github上的一个例子:zigzag
cimport cython
import numpy as np
from numpy cimport ndarray, int_t
DEF PEAK = 1
DEF VALLEY = -1
@cython.boundscheck(False)
@cython.wraparound(False)
cpdef int_t identify_initial_pivot(double [:] X,
double up_thresh,
double down_thresh):
cdef:
double x_0 = X[0]
double x_t = x_0
double max_x = x_0
double min_x = x_0
int_t max_t = 0
int_t min_t = 0
up_thresh += 1
down_thresh += 1
for t in range(1, len(X)):
x_t = X[t]
if x_t / min_x >= up_thresh:
return VALLEY if min_t == 0 else PEAK
if x_t / max_x <= down_thresh:
return PEAK if max_t == 0 else VALLEY
if x_t > max_x:
max_x = x_t
max_t = t
if x_t < min_x:
min_x = x_t
min_t = t
t_n = len(X)-1
return VALLEY if x_0 < X[t_n] else PEAK
@cython.boundscheck(False)
@cython.wraparound(False)
cpdef peak_valley_pivots(double [:] X,
double up_thresh,
double down_thresh):
"""
Find the peaks and valleys of a series.
:param X: the series to analyze
:param up_thresh: minimum relative change necessary to define a peak
:param down_thesh: minimum relative change necessary to define a valley
:return: an array with 0 indicating no pivot and -1 and 1 indicating
valley and peak
The First and Last Elements
---------------------------
The first and last elements are guaranteed to be annotated as peak or
valley even if the segments formed do not have the necessary relative
changes. This is a tradeoff between technical correctness and the
propensity to make mistakes in data analysis. The possible mistake is
ignoring data outside the fully realized segments, which may bias
analysis.
"""
if down_thresh > 0:
raise ValueError('The down_thresh must be negative.')
cdef:
int_t initial_pivot = identify_initial_pivot(X,
up_thresh,
down_thresh)
int_t t_n = len(X)
ndarray[int_t, ndim=1] pivots = np.zeros(t_n, dtype=np.int_)
int_t trend = -initial_pivot
int_t last_pivot_t = 0
double last_pivot_x = X[0]
double x, r
pivots[0] = initial_pivot
# Adding one to the relative change thresholds saves operations. Instead
# of computing relative change at each point as x_j / x_i - 1, it is
# computed as x_j / x_1. Then, this value is compared to the threshold + 1.
# This saves (t_n - 1) subtractions.
up_thresh += 1
down_thresh += 1
for t in range(1, t_n):
x = X[t]
r = x / last_pivot_x
if trend == -1:
if r >= up_thresh:
pivots[last_pivot_t] = trend
trend = PEAK
last_pivot_x = x
last_pivot_t = t
elif x < last_pivot_x:
last_pivot_x = x
last_pivot_t = t
else:
if r <= down_thresh:
pivots[last_pivot_t] = trend
trend = VALLEY
last_pivot_x = x
last_pivot_t = t
elif x > last_pivot_x:
last_pivot_x = x
last_pivot_t = t
if last_pivot_t == t_n-1:
pivots[last_pivot_t] = trend
elif pivots[t_n-1] == 0:
pivots[t_n-1] = -trend
return pivots
@cython.boundscheck(False)
@cython.wraparound(False)
cpdef double max_drawdown(ndarray[double, ndim=1] X):
"""
Compute the maximum drawdown of some sequence.
:return: 0 if the sequence is strictly increasing.
otherwise the abs value of the maximum drawdown
of sequence X
"""
cdef:
double mdd = 0
double peak = X[0]
double x, dd
for x in X:
if x > peak:
peak = x
dd = (peak - x) / peak
if dd > mdd:
mdd = dd
return mdd if mdd != 0.0 else 0.0
@cython.boundscheck(False)
@cython.wraparound(False)
def pivots_to_modes(int_t [:] pivots):
"""
Translate pivots into trend modes.
:param pivots: the result of calling ``peak_valley_pivots``
:return: numpy array of trend modes. That is, between (VALLEY, PEAK] it
is 1 and between (PEAK, VALLEY] it is -1.
"""
cdef:
int_t x, t
ndarray[int_t, ndim=1] modes = np.zeros(len(pivots),
dtype=np.int_)
int_t mode = -pivots[0]
modes[0] = pivots[0]
for t in range(1, len(pivots)):
x = pivots[t]
if x != 0:
modes[t] = mode
mode = -x
else:
modes[t] = mode
return modes
def compute_segment_returns(X, pivots):
"""
:return: numpy array of the pivot-to-pivot returns for each segment."""
pivot_points = X[pivots != 0]
return pivot_points[1:] / pivot_points[:-1] - 1.0
关于python - Python 中的之字折线指标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62454181/
有没有办法将多个线段视为 1 条线? IE:我将鼠标悬停在其中一个上,两者都会突出显示,并且切换图例中的可见性将隐藏这两个部分。 http://jsfiddle.net/rayholland/HSvB
我正在使用 geojson 创建折线。我的geojson的格式如下: var myLines = [{ "type": "LineString", "coordinates": [[-
我对 matlab 和图像处理很陌生 我想要实现的是检测图像中的不规则线条。例如,在下图中,有 4 条折线: 我的目标是得到一组代表这 4 条不规则线/折线的像素点。像这样。 我已经通读了一些主题,例
本章响应小伙伴的反馈,除了算法自动画连接线(仍需优化完善),实现了可以手动绘制直线、折线连接线功能。 请大家动动小手,给我一个免费的 Star 吧~ 大家如果发现了 Bug,欢迎来提 Is
这一章把直线连接改为折线连接,沿用原来连接点的关系信息。关于折线的计算,使用的是开源的 AStar 算法进行路径规划,启发方式为 曼哈顿距离,且不允许对角线移动。 请大家动动小手,给我一个免费
话接上回《前端使用 Konva 实现可视化设计器(13)- 折线 - 最优路径应用【思路篇】》,这一章继续说说相关的代码如何构思的,如何一步步构建数据模型可供 AStar 算法进行路径规划,最终画出节
是否可以使用水平线性渐变描边 SVG 多段线,其中渐变的角度在每个多段线顶点发生变化?它看起来像这样: 最佳答案 看看tubefy以色列艾森伯格。目前 svg 中没有任何内容可以准确地以声明方式提供您
我已经实现了一些代码,可以在单击 ListView 项时从 URL 加载图像;这已经用“虚拟”图像进行了测试,并且在 ImageView 对象中显示的图像没有任何问题。 但是,我真正想做的是通过 UR
我正在编写一个函数,用于在 mouseover 和 mouseout 上添加和删除 Mapbox polyline。我的 mouseover 可以正常工作,但我似乎不知道如何在 mouseout 上访
我使用此代码在 OSM 上有一些自定义折线 var polyline1 = [ [44.772142, 17.208980], [44.774753, 17.20764
我的应用程序是实时跟踪器,多个用户登录并通过将他们的坐标发送到我们的网络服务来更新他们的位置,然后每 2 分钟回调一次,让我们在我的 MapView 上显示所有用户。 每次我在 connectionD
我想知道是否有一种方法可以通过单击来突出折线。像这样: Before click After click 最佳答案 您可以使用折线两次。第一次折线更宽并且笔划不透明度为“0”。当您将鼠标悬停在该组上时
我需要显示从 A 到 B 的不同折线。因此,这些线应该彼此区分。我曾尝试使用带有高度参数的推点函数来设置折线。然而它仍然在地面上。我插入的最后一条折线会覆盖前一条折线。高度值适用于标记,但我想将其应用
我正在尝试向 svg 多段线添加类似叠加的效果。基本目标是使单击该线变得容易,并且由于该线太细,我想添加一个背景叠加层,当鼠标悬停在上面时会亮起。 我使用多边形尝试了以下方法,但这看起来很乏味。 (线
如何在 Google map 中绘制圆弧折线? 我已经用过this创建曲线折线的代码。 下面是绘制曲线折线的方法: private void showCurvedPolyline (LatLng p1
背景: 开发使用 Android Google Map v2 的原生 Android 应用,使用 android.support.v4.app.FragmentActivity。在 Android v
如何使用 JavaScript 将坐标添加到现有的 SVG 折线? 我正在使用 IE 9(在 .hta 文件中)并且需要能够动态地将新点附加到折线。目标是能够创建折线图。我提前道歉,我完
如何在 JavaScript 中拆分数据数组 {x:30, y:45, x:36, y:49} 进入表格 [30, 45, 36, 49] ? 我需要此表单才能将坐标传递给 SVG 折线。我找到了一个
在角度 6 中。我正在为 agm-polyline 使用流动代码。 我想在 agm-polyline 中添加箭头符号(折线)( https://developers.google.com/maps/d
我在 map 上做了路线。使用一些坐标生成的路线,这些坐标完成了附加信息(速度)。我希望当路线悬停时,将出现一个工具提示并显示这些坐标处的信息(速度)。我很困惑如何显示速度的工具提示。 Po
我是一名优秀的程序员,十分优秀!