计算熵时的运行时警告



我的脚本中的熵函数有一个运行时警告。我不明白为什么会出现这个错误。

我想我忘记导入numpy库了。但是,当我运行该脚本时,它说问题与以2为基数的日志有关。我真不知道该怎么解决。任何建议吗?

import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
# Retrieve the stock data
ticker = yf.Ticker("ES=F")
df = ticker.history(interval="2m", period="60d")
# Calculate the order flow imbalance
df["order_flow_imbalance"] = df["Volume"]
df.loc[df["Close"] > df["Open"], "order_flow_imbalance"] *= -1
# Calculate the entropy
total_orders = df["order_flow_imbalance"].sum()
p_buy = df.loc[df["order_flow_imbalance"] > 0, 
"order_flow_imbalance"].sum() / total_orders
p_sell = df.loc[df["order_flow_imbalance"] < 0, 
"order_flow_imbalance"].sum() / total_orders
entropy = -p_buy * np.log2(p_buy) - p_sell * np.log2(p_sell)
df["entropy"] = entropy
# Calculate the returns
df["returns"] = (df["Close"] - df["Open"]) / df["Open"]
# Filter the data
df = df[df["order_flow_imbalance"] > 100000]
# Plot the data
sns.scatterplot(x="returns", y="entropy", data=df)
sns.regplot(x="returns", y="entropy", data=df)
plt.show()
RuntimeWarning: invalid value encountered in log2 entropy = -p_buy * np.log2(p_buy) - p_sell * np.log2(p_sell)

你得到这个错误,因为传递给对数刻度的值是负的。P_buy = -552.6374.

在将值传递给日志刻度之前,放置一个检查以修改值为大于0。

相关内容