首页 > 解决方案 > 减少我的代码在 python 中计算股票指标的时间

问题描述

我想减少我的函数计算我的股票指标的时间。有没有办法做到这一点?该函数以股票的时间序列为例并计算“之字形”。此外,该功能需要像 0.03 这样的反转

import pandas as pd
import yfinance as yf


def zigzag(dataframe=None, prices_column=None):
    reversal = 0.03
    dataframe = dataframe.copy()
    empty_dataframe = pd.DataFrame()
    start = 0
    for i, row in dataframe.iterrows():
        if start == i:
            endLine = False
            lastIndex = None
            trend = None
            while endLine is False:
                start += 1
                database = dataframe.loc[i:start]
                firstPrice = database.iloc[0][prices_column]
                lastPrice = database.iloc[-1][prices_column]
                change = lastPrice / firstPrice - 1
                if not lastIndex:
                    if abs(change) >= reversal:
                        lastIndex = database.iloc[-1].name
                        trend = 1 if firstPrice < lastPrice else -1
                    else:
                        pass
                else:
                    if lastPrice / database.loc[lastIndex][prices_column] - 1 < 0 and trend == -1:
                        lastIndex = database.iloc[-1].name
                    elif lastPrice / database.loc[lastIndex][prices_column] - 1 > 0 and trend == 1:
                        lastIndex = database.iloc[-1].name
                    elif (
                        lastPrice / database.loc[lastIndex][prices_column] - 1 > 0 and
                        abs(lastPrice / database.loc[lastIndex][prices_column] - 1) >= reversal and
                        trend == -1
                    ):
                        endLine = True
                        start = lastIndex
                    elif (
                        lastPrice / database.loc[lastIndex][prices_column] - 1 < 0 and
                        abs(lastPrice / database.loc[lastIndex][prices_column] - 1) >= reversal and
                        trend == 1
                    ):
                        endLine = True
                        start = lastIndex
                if dataframe.shape[0] < start:
                    endLine = True
            empty_dataframe = empty_dataframe.append(dataframe.loc[i])
            empty_dataframe = empty_dataframe.append(dataframe.loc[lastIndex])
    empty_dataframe = empty_dataframe[~empty_dataframe.index.duplicated(keep='first')]
    empty_dataframe = empty_dataframe.set_index('Date')
    return empty_dataframe

dataframe = yf.download("AAPL", start="2010-01-01", end="2017-04-30")
dataframe.reset_index(drop=False, inplace=True)
result = zigzag(dataframe=dataframe, prices_column='Close')

标签: python

解决方案


推荐阅读