python - 减少我的代码在 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')
解决方案
推荐阅读
- html - 更改特定页面上 ion-menu 的“max-edge-start”值
- sql - 比较可用性和预订活动以计算一天中可用的分钟数
- reactjs - 我在 withTracker mongo 查找功能中遇到参考错误?
- jasper-reports - textField 和 staticText 的“合理”属性在 jaspersoft 报告中不起作用
- python - IO 错误:[Errno 13] 权限被拒绝 - networkX
- c - 我的文件中有奇怪的字符。我在 C 语言中使用无缓冲 I/O 流
- android - 多部分请求的响应解码没有发生
- angular - Angular 2 模板驱动的表单和 statusChanges
- c - GetPhysicallyInstalledMemory 函数 - C 中未定义的引用
- kotlin - 如何修复 kotlin 中的数据绑定错误?