【问题标题】:manipulate Date from yfinance从 yfinance 操纵日期
【发布时间】:2021-03-24 12:17:06
【问题描述】:

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

例如,2020 年 10 月 26 日,我想创建包含以下数据的列:
day_of_week,星期一 = 1
年 = 2020
月 = 10
天 = 26
周 = 44
交易日 = 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

【问题讨论】:

    标签: python datetime yfinance


    【解决方案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')
    

    【讨论】:

    • 感谢 Samer!我收到以下错误消息:“weekofyear 和 week 已被弃用,请改用 DatetimeIndex.isocalendar().week,它返回一个系列。要准确重现 week 和weekofyear 并返回一个索引,您可以调用 pd.Int64Index(idx.isocalendar().week)"
    • 我确实通过更改以下内容使“贸易周”工作:new_df['Trade_week'] = df.index.isocalendar().week。此外,如果“trade_day”是从一年中的任何其他日子开始计算的,它也是不正确的。我希望“trade_day”在一年中的第一个实际交易日开始计算。
    • 更改开始日期:start_date = pd.to_datetime('2017-01-01')
    【解决方案2】:

    我确实发现了大部分问题。我不知道如何计算“交易日期”。

    #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
    

    【讨论】:

      猜你喜欢
      • 2023-02-03
      • 1970-01-01
      • 2011-09-30
      • 2022-10-02
      • 2020-09-13
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多