【问题标题】:How to omit only weekends from my data frame?如何从我的数据框中只省略周末?
【发布时间】:2021-03-24 06:05:34
【问题描述】:

我正在开发一个创建算法交易者的项目。但是,我想从我的数据框中删除周末,因为它破坏了 中所示的数据那个技术。它也不是数据框中的列。我是 python 新手,所以我不太确定,但我认为这是一个索引,因为当我通过 .index 函数时,它会显示日期和时间。如果这些是愚蠢的问题,我很抱歉,但我是 python 和 pandas 的新手。

这是我的代码:

#import all the libraries
import nsetools as ns
import pandas as pd
import numpy
import matplotlib.pyplot as plt
from datetime import datetime
import yfinance as yf

plt.style.use('fivethirtyeight')
a = input("Enter the ticker name you wish to apply strategy to")
ticker = yf.Ticker(a)
hist = ticker.history(period="1mo", interval="15m")
print(hist)

plt.figure(figsize=(12.5, 4.5))
plt.plot(hist['Close'], label=a)
plt.title('close price history')
plt.xlabel("13 Nov 2020 too 13 Dec 2020")
plt.ylabel("Close price")
plt.legend(loc='upper left')
plt.show()

编辑:根据用户的建议,我尝试将我的代码修改为此

refinedlist = hist[hist.index.dayofweek<5]plt.style.use('fivethirtyeight')
a = input("Enter the ticker name you wish to apply strategy to")
ticker = yf.Ticker(a)
hist = ticker.history(period="1mo", interval="15m")
refinedlist = hist[hist.index.dayofweek<5]
print (refinedlist)

并绘制了图表,但图表仍包括 x 轴上的周末。

【问题讨论】:

标签: python pandas numpy dataframe matplotlib


【解决方案1】:

首先,股市数据不存在,因为市场在节假日和国定假日休市。原因是你的获取单位是时间,所以也没有从市场收盘到第二天开盘的数据。

例如,我绘制了前 50 个结果。 (x 轴似乎不正确。)

plt.plot(hist['Close'][:50], label=a)

举个例子,如果您将节假日和国定假日包括在内,并为市场不开放的时间绘制一个缺失值的图表,您会得到以下结果。

new_idx = pd.date_range(hist.index[0], hist.index[-1], freq='15min')
hist = hist.reindex(new_idx, fill_value=np.nan)

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
import yfinance as yf

# plt.style.use('fivethirtyeight')
# a = input("Enter the ticker name you wish to apply strategy to")
a = 'AAPL'
ticker = yf.Ticker(a)
hist = ticker.history(period="1mo", interval="15m")
new_idx = pd.date_range(hist.index[0], hist.index[-1], freq='15min')
hist = hist.reindex(new_idx, fill_value=np.nan)

plt.figure(figsize=(12.5, 4.5))
plt.plot(hist['Close'], label=a)
plt.title('close price history')
plt.xlabel("13 Nov 2020 too 13 Dec 2020")
plt.ylabel("Close price")
plt.legend(loc='upper left')
plt.show()

【讨论】:

  • 你说的很有道理,这是否意味着数据应该是这样的?因为图表当然不应该有这些差距
猜你喜欢
  • 1970-01-01
  • 2021-06-13
  • 1970-01-01
  • 2017-06-20
  • 2021-09-08
  • 1970-01-01
  • 1970-01-01
  • 2022-10-14
  • 1970-01-01
相关资源
最近更新 更多