我想获取每个月的最后一个星期五苹果股票的收盘价。我该怎么做 ?谢谢
import pandas as pd
import numpy as np
import yfinance as yf
apple=yf.Ticker("AAPL")
apple=apple.history(period="5y")
答案 0 :(得分:2)
这是一种方法:
import pandas as pd
import numpy as np
import yfinance as yf
apple=yf.Ticker("AAPL")
apple=apple.history(period="5y")
apple['weekday'] = apple.index.weekday
apple['month_year'] = apple.index.to_period('M')
apple['date'] = apple.index
friday_groupy = apple[apple['weekday'] == 4].groupby(['month_year'])
apple.loc[friday_groupy['date'].idxmax()]
答案 1 :(得分:1)
解决方案示例:
import pandas as pd
import yfinance as yf
import calendar
# create dataframe
df = yf.Ticker("AAPL")
df = df.history(period="5y")
df.head()
# define helper function for retrieving last fridays for a given year
def last_fridays(year):
result = []
for month in range(1, 13):
last_friday = max(week[calendar.FRIDAY] for week in calendar.monthcalendar(year, month))
result.append('{:4d}-{:02d}-{:02d}'.format(year, month, last_friday))
return result
last_fridays = [frd for y in pd.DatetimeIndex(df.index).year for frd in last_fridays(y)]
# filter dataframe
df.loc[df.index.strftime('%Y-%m-%d').isin(last_fridays)]