#python #pandas #data-analysis
#python #pandas #анализ данных
Вопрос:
Я хочу получить цену закрытия акций Apple за последнюю пятницу каждого месяца. Как я могу это сделать? Спасибо
import pandas as pd
import numpy as np
import yfinance as yf
apple=yf.Ticker("AAPL")
apple=apple.history(period="5y")
Комментарии:
1. как выглядят ваши данные о ценах?
2. я обновил код. Точно так же, как обычный фрейм данных. СПАСИБО
Ответ №1:
Вот способ сделать это:
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()]
Ответ №2:
Пример решения:
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)]