1

当我从 yfinance 提取股票数据时,我可以创建其他数据列来操纵“日期”列吗?我是 python 新手,仍然学到很多东西。我已经使用股票价格数据创建了其他列,但我不知道如何操作“日期”列。

例如,10/26/2020,我想用以下数据创建列:
day_of_week, Monday = 1
year = 2020
month = 10
day = 26
week = 44
trade_day = 207

import pandas as pd
import numpy as np
import yfinance as yf
import pandas_datareader as pdr
import datetime as dt
import matplotlib.pyplot as plt

##Get stock price data
ticker = 'NVDA'

#Data time period
now = dt.datetime.now()
startyear = 2017
startmonth=1
startday=1
start = dt.datetime(startyear, startmonth, startday)

#get data from YFinance
df = pdr.get_data_yahoo(ticker, start, now)

#create a column
df['% Change'] = (df['Adj Close'] / df['Adj Close'].shift(1))-1

df['Range'] = df['High'] - df['Low']

df
4

2 回答 2

1

您想使用数据帧的索引,它的类型为 pd.DatetimeIndex。要将日期拆分为新列:

new_df = df.copy()
new_df['year'], new_df['month'], new_df['day'] = df.index.year, df.index.month, df.index.day

从第一个交易日开始进行算术运算:

start_date = df.index.min()
new_df['trade_day'] = df.index.day - start_date.day
new_df['trade_week'] = df.index.week - start_date.week
new_df['trade_year'] = df.index.year - start_date.year
new_df['day_of_week'] =  df.index.weekday
new_df['days_in_month'] =  df.index.days_in_month
new_df['day_name'] =  df.index.day_name()
new_df['month_name'] =  df.index.month_name()

选择另一个开始日期

start_date = pd.to_datetime('2017-01-01')
于 2020-12-13T19:55:30.550 回答
0

我确实找出了大部分问题。我无法弄清楚如何计算“交易日期”。

#Convert the 'Date' Index to 'Date' Column
df.reset_index(inplace=True)

#Create columns manipulating 'Date'
df['Year'] = df['Date'].dt.year
df['Month'] = df['Date'].dt.month
df['Day'] = df['Date'].dt.day
df['Week of Year'] = df['Date'].dt.isocalendar().week
df['Day of Week'] = df['Date'].dt.dayofweek
于 2020-12-14T20:25:30.160 回答