Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Python查找数据集中的最大百分比下降?(股市)_Python_Statistics_Google Play_Stock - Fatal编程技术网

如何使用Python查找数据集中的最大百分比下降?(股市)

如何使用Python查找数据集中的最大百分比下降?(股市),python,statistics,google-play,stock,Python,Statistics,Google Play,Stock,我目前正在处理股票市场分析,并试图找到一种快速算法,使我能够计算给定数据集中的最大价格下跌,我认为这是一个值得思考的好算法问题。因此,输入将是特定时间间隔内的股票价格,输出将是所有价格下跌的最大值 这里是一个视觉例子,请看图片;(百分比由眼睛决定) 我大致描述了一些价格下跌及其百分比。即使最后一次降价是其价值的最大值,但降价60%的那一次是我想要找到的 提前感谢解决方案: 您可以在线性时间内通过向后迭代股票值来实现这一点 您可以跟踪到迄今为止所看到的最小元素,因为最大的落差总是落在前面的最小值

我目前正在处理股票市场分析,并试图找到一种快速算法,使我能够计算给定数据集中的最大价格下跌,我认为这是一个值得思考的好算法问题。因此,输入将是特定时间间隔内的股票价格,输出将是所有价格下跌的最大值

这里是一个视觉例子,请看图片;(百分比由眼睛决定)

我大致描述了一些价格下跌及其百分比。即使最后一次降价是其价值的最大值,但降价60%的那一次是我想要找到的

提前感谢

解决方案: 您可以在线性时间内通过向后迭代股票值来实现这一点

您可以跟踪到迄今为止所看到的最小元素,因为最大的落差总是落在前面的最小值上。然后你可以计算出从每个点到前面最小元素的相对落差,只需跟踪你通过这种方式发现的最大落差

下面是它在Python中的一个实现。确保你了解我在做什么以及它为什么起作用,确保它符合你心中的问题

def getGreatestDrop(stock):
    """Calculates the greatest relative drop of a stock.
    @param stock: 1-D list contianing the values of that stock
    Returns a tuple with the relative drop size, the index of the start and the
    index of the end of that drop.
    """

    min = None # The smallest absolute value seen so far
    minIndex = None  # The index of the smallest absolute value smallest value
    greatestDrop = None # The biggest relative drop seen so far
    greatestDropStart = None # The index of the drop start
    greatestDropEnd = None # The index of the drop end

    # Iterating backwards through the array, starting from the last element
    for index in range(len(stock)-1,-1,-1):
        # Update min
        if min is None or stock[index] < min:
            min = stock[index]
            minIndex = index

        # Calculate relative drop
        drop = 1-min/stock[index]

        # Update greatest drop
        if greatestDrop is None or drop > greatestDrop:
            greatestDrop = drop
            greatestDropStart = index
            greatestDropEnd = minIndex

    # Return values
    return greatestDrop, greatestDropStart, greatestDropEnd

def getGreatestDrop(股票):
“”“计算股票的最大相对跌幅。
@参数库存:包含该库存值的一维列表
返回一个元组,该元组包含相对放置大小、开始和结束的索引
下降结束时的指数。
"""
min=无#迄今为止所见的最小绝对值
minIndex=无#最小绝对值最小值的索引
greatestDrop=无#迄今为止最大的相对跌幅
greatestDropStart=None#拖放开始的索引
greatestDropEnd=None#下拉端的索引
#从最后一个元素开始向后迭代数组
对于范围内的指数(len(股票)-1,-1,-1):
#更新最小值
如果最小值为无或股票[指数]greatestDrop:
最大下降=下降
greatestDropStart=索引
greatestDropEnd=minIndex
#返回值
返回greatestDrop、greatestDropStart、greatestDropEnd

例子: 下面是一个示例程序,我在6只随机生成的股票上使用此函数:

#!/usr/bin/env python3

import random
import numpy as np
from matplotlib import pyplot as plt

def generateRandomStock(length, volatility=1, trend=0, scale=100, lowest=500):
    """Generat
    @param stock: 1-D list contianing the values of that stock
    Returns a tuple with the relative drop size, the index of the start and the
    index of the end of that drop.
    """
    out = np.ndarray(length)
    value = 0
    for i in range(length):
        value += volatility*(random.random()-0.5) + trend
        out[i] = value
    out *= scale
    out -= out.min()
    out += lowest
    return out

def getGreatestDrop(stock):
    """Calculates the greatest relative drop of a stock.
    @param stock: 1-D list contianing the values of that stock
    Returns a tuple with the relative drop size, the index of the start and the
    index of the end of that drop.
    """

    min = None # The smallest absolute value seen so far
    minIndex = None  # The index of the smallest absolute value smallest value
    greatestDrop = None # The biggest relative drop seen so far
    greatestDropStart = None # The index of the drop start
    greatestDropEnd = None # The index of the drop end

    # Iterating backwards through the array, starting from the last element
    for index in range(len(stock)-1,-1,-1):
        # Update min
        if min is None or stock[index] < min:
            min = stock[index]
            minIndex = index

        # Calculate relative drop
        drop = 1-min/stock[index]

        # Update greatest drop
        if greatestDrop is None or drop > greatestDrop:
            greatestDrop = drop
            greatestDropStart = index
            greatestDropEnd = minIndex

    # Return values
    return greatestDrop, greatestDropStart, greatestDropEnd

if __name__ == "__main__":

    # Create subplots
    width = 3
    height = 2
    fig, axs = plt.subplots(width, height)

    # Fix random seed to get the same results every time
    random.seed(42)

    # Draw all plots
    for w in range(width):
        for h in range(height):
            # Generate stocks randomly
            stocks = generateRandomStock(1000)
            axs[w][h].plot(stocks)

            # Calculate greatest drop
            drop, dropStart, dropEnd = getGreatestDrop(stocks)
            axs[w][h].plot([dropStart, dropEnd],[stocks[dropStart],stocks[dropEnd]], color="red")

            # Set title
            axs[w][h].set_title("Greatest Drop is {:.1f}% from {} to {}".format(100*drop, dropStart, dropEnd))

    # Show all results
    plt.show()
#/usr/bin/env蟒蛇3
随机输入
将numpy作为np导入
从matplotlib导入pyplot作为plt
def GeneratorDomainStock(长度、波动率=1、趋势=0、标度=100、最低值=500):
“生成
@参数库存:包含该库存值的一维列表
返回一个元组,该元组包含相对放置大小、开始和结束的索引
下降结束时的指数。
"""
out=np.ndarray(长度)
值=0
对于范围内的i(长度):
价值+=波动率*(随机.random()-0.5)+趋势
out[i]=值
out*=刻度
out-=out.min()
out+=最低
返回
def getGreatestDrop(库存):
“”“计算股票的最大相对跌幅。
@参数库存:包含该库存值的一维列表
返回一个元组,该元组包含相对放置大小、开始和结束的索引
下降结束时的指数。
"""
min=无#迄今为止所见的最小绝对值
minIndex=无#最小绝对值最小值的索引
greatestDrop=无#迄今为止最大的相对跌幅
greatestDropStart=None#拖放开始的索引
greatestDropEnd=None#下拉端的索引
#从最后一个元素开始向后迭代数组
对于范围内的指数(len(股票)-1,-1,-1):
#更新最小值
如果最小值为无或股票[指数]greatestDrop:
最大下降=下降
greatestDropStart=索引
greatestDropEnd=minIndex
#返回值
返回greatestDrop、greatestDropStart、greatestDropEnd
如果名称=“\uuuuu main\uuuuuuuu”:
#创建子地块
宽度=3
高度=2
图,axs=plt.子批次(宽度、高度)
#固定随机种子以每次获得相同的结果
随机种子(42)
#画出所有的图
对于范围内的w(宽度):
对于范围内的h(高度):
#随机生成股票
库存=发电机库存(1000)
axs[w][h]。绘图(库存)
#计算最大落差
drop,dropStart,dropEnd=getGreatestDrop(股票)
axs[w][h]。绘图([dropStart,dropEnd],[stocks[dropStart],stocks[dropEnd]],color=“红色”)
#定名
axs[w][h]。设置标题(“从{}到{}的最大跌幅为{:.1f}%。格式(100*Drop,dropStart,dropEnd))
#显示所有结果
plt.show()
输出:

最大的落差不应该从左边开始(当前30%的落差开始),从60%的落差结束吗?这大概是90%的降幅。谢谢你的努力。这是一个可以理解且简单明了的解决方案。我刚刚意识到,没有必要回顾清单。你还可以继续追踪到目前为止你所看到的最高点,并将其与当前价格进行比较。我不知道为什么我认为它必须是向后的。。。