【问题标题】:Making decisions based on the times of datetime in a dataframe根据数据框中的日期时间做出决策
【发布时间】:2022-01-18 21:06:56
【问题描述】:

我是编程和 python 的新手。经过数小时的研究,我想向社区寻求帮助。我想使用数据来回测基于伦敦时段开始的交易策略。

我有一个数据框:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 28766 entries, 0 to 28765
Data columns (total 6 columns):
| #  | Column | Non-Null Count  |Dtype   |      
|--- |------ |--------------  |----- |        
| 0  |Time   |28766 non-null  |datetime64[ns]|
| 1  |Open   |28766 non-null  |float64 |
| 2 |...|

|    |Time                  |Open    | High   | Low    |Close   |Volume  |
|--- |--------------------- |------- |------- |------- |------- | ------|
|8   |2017-05-23 08:00:00   |2180.7  |2187.2  |2139.2  | 2170.2 | 97.0  |

现在我想定义一个函数,它可以识别其中包含 08:00 GMT 的每一行:

def LondonSession(df):
df = df.copy()
for t in df['Time']:
    if df[df['Time'].dt.hour == (8)]:
        df['StopLoss'] = technicals(df)['atr'] * (-1)
        df['TakeProfit'] = technicals(df)['atr'] * (2)
    else: 
        df['StopLoss'] = technicals(df)['atr'] * (0)
        df['TakeProfit'] = technicals(df)['atr'] * (0)
return df

print(LondonSession(df)[0:10])

很遗憾,我对如何解决错误消息一无所知:

ValueError                                Traceback (most recent call last) Input In [204], in <module>
      9             df['TakeProfit'] = technicals(df)['atr'] * (0)
     10     return df
---> 11 print(LondonSession(df)[0:10])

Input In [204], in LondonSession(df)
      2 df = df.copy()
      3 for t in df['Time']:
----> 4     if df[df['Time'].dt.hour == (8)]:
      5         df['StopLoss'] = technicals(df)['atr'] * (-1)
      6         df['TakeProfit'] = technicals(df)['atr'] * (2)

File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\generic.py:1537, in NDFrame.__nonzero__(self)    1535 @final    1536 def
__nonzero__(self):
-> 1537     raise ValueError(    1538         f"The truth value of a {type(self).__name__} is ambiguous. "    1539         "Use a.empty, a.bool(), a.item(), a.any() or a.all()."    1540     )

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

建议使用任何输入。 提前致谢!

【问题讨论】:

    标签: python pandas dataframe datetime finance


    【解决方案1】:

    这里的问题是你在第一个 if 条件中写的:df[df['Time'].dt.hour == (8)]。此代码不返回布尔值,而是返回一个数据框,其中选定的行是属性 Time 等于 8 的行。

    如果你想保持你的 for 循环结构,你应该用if t.hour == 8 改变条件。但请记住,对于 pandas,您应该避免使用 for 循环并使用行过滤(您可以在 pandas official tutorial 上阅读更多关于此问题的信息)。

    【讨论】:

    • 根据您的回答,我尝试了以下操作:test2 = technicals(test) test2[test2['Time'].dt.hour == (8)]['StopLoss'] = test2['atr'] * (-1) 但我收到另一个错误:“试图在 DataFrame 的切片副本上设置值。尝试使用 .loc[row_indexer ,col_indexer] = value instead 请参阅文档中的注意事项:pandas.pydata.org/pandas-docs/stable/user_guide/… ..." for-loop 不是强制性的...您还有其他想法如何决定逐行执行的操作吗?
    • 您还必须在右侧的 DataFrame 上使用相同的过滤器:test2[test2['Time'].dt.hour == (8)]['StopLoss'] = test2[test2['Time'].dt.hour == (8)]['atr'] * (-1)。使用此过滤器,您只需选择小时 = 8 的行并进行正确的计算。
    【解决方案2】:

    我的解决方案是:

    test2.loc[test2['Time'].dt.hour == (8), 'TakeProfit'] = (test2['atr'] * (1.5)) test2.loc[test2['Time'].dt.hour == (8), 'StopLoss'] = (test2['atr'] * (-1)) test2.loc[test2['Time'].dt.hour != (8), 'TakeProfit'] = (0) test2.loc[test2['Time'].dt.hour != (8), 'StopLoss'] = (0)

    我在这篇文章中读到:enter link description here

    这篇文章描述了我的问题的更多选项。但我第一个成功了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-07
      • 2019-01-15
      • 2021-03-16
      • 1970-01-01
      • 2022-11-23
      • 1970-01-01
      • 1970-01-01
      • 2019-07-14
      相关资源
      最近更新 更多