读取股票数据时出错:“DatetimeProperties”对象没有属性“weekday_name”,“NoneType”对象没有属性“to_csv”
Posted
技术标签:
【中文标题】读取股票数据时出错:“DatetimeProperties”对象没有属性“weekday_name”,“NoneType”对象没有属性“to_csv”【英文标题】:Error in reading stock data : 'DatetimeProperties' object has no attribute 'weekday_name' and 'NoneType' object has no attribute 'to_csv' 【发布时间】:2020-05-29 12:53:17 【问题描述】:我尝试运行代码来获取股票数据,但它失败了,显示以下错误:
'DatetimeProperties' 对象没有属性 'weekday_name' 'NoneType' 对象没有属性 'to_csv'
from pandas_datareader import data as web
import os
import pandas as pd
from pandas.testing import assert_frame_equal
def get_stock(ticker, start_date, end_date, s_window, l_window):
try:
df = web.get_data_yahoo(ticker, start=start_date, end=end_date)
df['Return'] = df['Adj Close'].pct_change()
df['Return'].fillna(0, inplace = True)
df['Date'] = df.index
df['Date'] = pd.to_datetime(df['Date'])
df['Month'] = df['Date'].dt.month
df['Year'] = df['Date'].dt.year
df['Day'] = df['Date'].dt.day
for col in ['Open', 'High', 'Low', 'Close', 'Adj Close']:
df[col] = df[col].round(2)
df['Weekday'] = df['Date'].dt.weekday_name
df['Week_Number'] = df['Date'].dt.strftime('%U')
df['Year_Week'] = df['Date'].dt.strftime('%Y-%U')
df['Short_MA'] = df['Adj Close'].rolling(window=s_window, min_periods=1).mean()
df['Long_MA'] = df['Adj Close'].rolling(window=l_window, min_periods=1).mean()
col_list = ['Date', 'Year', 'Month', 'Day', 'Weekday',
'Week_Number', 'Year_Week', 'Open',
'High', 'Low', 'Close', 'Volume', 'Adj Close',
'Return', 'Short_MA', 'Long_MA']
num_lines = len(df)
df = df[col_list]
print('read ', num_lines, ' lines of data for ticker: ' , ticker)
return df
except Exception as error:
print(error)
return None
try:
ticker='MSFT'
input_dir = r'/Users/sirishpulijala/Desktop'
output_file = os.path.join(input_dir, ticker + '.csv')
df = get_stock(ticker, start_date='2014-01-01', end_date='2019-12-31',
s_window=14, l_window=50)
df.to_csv(output_file, index=False)
print('wrote ' + str(len(df)) + ' lines to file: ' + output_file)
except Exception as e:
print(e)
print('failed to get Yahoo stock data for ticker: ', ticker)
【问题讨论】:
【参考方案1】:您的问题是以下行:
df['Weekday'] = df['Date'].dt.weekday_name
改成:
df['Weekday'] = df['Date'].dt.day_name()
你可以走了。
【讨论】:
【参考方案2】:我们可以使用
df['Weekday'] = df['Date'].dt.strftime("%A")
这将给出工作日名称
更多格式选项包括:
%A
- 完整的工作日名称,例如 MONDAY、TUESDAY 等%w
- 工作日为十进制数字,例如 1、2、3 等%a
- 缩写的工作日名称,例如 SUN、MON 等%Y
-year%m
-month%d
-day%H
-hours%M
-minutes%S
-seconds
【讨论】:
以上是关于读取股票数据时出错:“DatetimeProperties”对象没有属性“weekday_name”,“NoneType”对象没有属性“to_csv”的主要内容,如果未能解决你的问题,请参考以下文章