如何用适用于不同数据集的变量替换硬编码索引?

问题描述 投票:0回答:1

我希望获得一些关于如何遵守“我的代码必须适用于任何数据”的规则的建议。我尝试使用索引来查找以下问题的最大损失日期,但没有成功。我最终只是将日期硬编码到“losshigh”变量中,但我认为这还不够。我们也不能使用 for 循环。

我们正在使用的“股票”数据集是一个带有日期时间索引和浮点值的 pandas 系列。

“计算最坏的可能买入日期和卖出日期组合。找到 x 和 y 这两天,以便最大化 x 买入和 y 卖出(y 在 x 之后)造成的损失百分比。您的代码应该适用于任何数据. 返回交易日 x 和 y,以及买入 x 和卖出 y 造成的损失百分比。如果您的代码错误、您的代码无法处理不同的数据或您使用 for 循环,您将受到处罚。 ” 提示: 使用方法 cummax() 或方法 cummin()。

(P.S.我已经在这个问题上研究了七个小时了。我哭了两次。我真的在重新考虑我的人生决定。我尝试了很多事情,感觉自己一直在用头撞墙好几个小时都没有进展。我只编码了几个星期。请帮忙。)

这是我到目前为止所拥有的。

====

#Reproducing stock.

import pandas as pd
import numpy as np
data = pd.read_csv('NVDA.csv',index_col=0, parse_dates=True)
stock = data['Close']
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
pd.set_option('display.float_format', lambda x: '%.2f' % x)
pd.set_option('display.max_columns', None)

====

#Find the highest index of x that comes before the lowest index of y

#The worst ratio of high stock in the past to whatever stock price is now.
bigloss=stock.cummax()/stock
biggestloss=bigloss.nlargest(1)

#Defining y.
y=stock.loc[biggestloss.index]

#The highest stock up to the biggest loss date.
losshigh=stock.loc['1999-01-22':'2002-10-09'].max()

#Defining x.
x=stock[stock==losshigh]

#The worst percentage.
percentage=(x[0]-y[0]/x[0])*100
python pandas datetime series
1个回答
0
投票

好吧,首先是免责声明:我将其解释为您在某一天买入并在另一天卖出所造成的最大总损失是多少。导师可能会要求每天买卖的最大损失,或最大百分比损失,或每天最大百分比损失,但这些是不同的问题。

但无论如何:

# first, we import pandas
import pandas as pd

# second, create sample data
stock = pd.Series([100, 120, 90, 30, 70, 150, 110, 100, 80, 90], index=pd.date_range(start='2023-01-01', periods=10, freq='D'), name='Stock_Price')

# cummax() finds the minimum value in the data *so far*
>>> stock.cummax()
2023-01-01    100
2023-01-02    120
2023-01-03    120
2023-01-04    120
2023-01-05    120
2023-01-06    150
2023-01-07    150
2023-01-08    150
2023-01-09    150
2023-01-10    150

所以基本上,这个想法是这样的:如果在某一天,cummax 和当天的股票价格之间的差异很大,这意味着我们可以在过去以最低价格买入它,然后卖出它今天。如果今天的价格低于最高价格,那么我们就会亏损。这是我们数据集的结果:

>>> stock - stock.cummax() 
2023-01-01     0
2023-01-02     0
2023-01-03   -30
2023-01-04   -90
2023-01-05   -50
2023-01-06     0
2023-01-07   -40
2023-01-08   -50
2023-01-09   -70
2023-01-10   -60

现在,我们只要看看就知道,最糟糕的出售日期是 2023 年 1 月 4 日。我们可以使用 idxmin() 获取该值:

>>> sell_day = (stock - stock.cummax()).idxmin()
Timestamp('2023-01-04 00:00:00')

现在获取从开始到卖出日的数据点,然后找到这些天内的最高价格,这必须是我们的买入日:

>>> stock[:sell_day]
2023-01-01    100
2023-01-02    120
2023-01-03     90
2023-01-04     30

>>> buy_day = stock.loc[:sell_day].idxmax()
Timestamp('2023-01-02 00:00:00')

现在最后,为了得到损失,我们可以使用简单的算术来计算:

>>> 100 * (stock[sell_day] - stock[buy_day]) / stock[sell_day]
-300.0

在示例数据集中,如果您在 2023 年 1 月 2 日以 120 美元买入,并在 2023 年 1 月 4 日以 30 美元卖出,您将损失 300%。

© www.soinside.com 2019 - 2024. All rights reserved.