如何使用 python 中的 yfinance 库调整变量建议以达成共识建议,例如指定的月份数、间隔和时间段?
例如,下面的脚本将提供从当前日期算起的 4 个月、1 个月的间隔。
import pandas as pd # Import the missing "pd" module
import yfinance as yf
# Define the stock ticker
stock = yf.Ticker("AAPL")
# Get stock info
info = stock.info
# Access analyst recommendations if available
recommendations = stock.recommendations
print(recommendations) # Print the full DataFrame
输出
period strongBuy buy hold sell strongSell
0 0m 11 21 6 0 0
1 -1m 10 17 12 2 0
2 -2m 10 17 12 2 0
3 -3m 10 24 7 1 0
但是尝试使用脚本来指定日期、月份或间隔,然后提供更多时间段
例如,periods=12,interval = 2 个月,end=mm/dd/yyyy 将提供 12 个周期,总共可追溯到 24 个月。
我的尝试遇到了一系列错误
import pandas as pd
import yfinance as yf
from datetime import datetime, timedelta
def get_analyst_recommendations(stock_ticker, num_months, interval_months, end_date=None):
if end_date is None:
end_date = datetime.now().strftime("%Y-%m-%d")
else:
end_date = datetime.strptime(end_date, "%m/%d/%Y").strftime("%Y-%m-%d")
start_date = (datetime.strptime(end_date, "%Y-%m-%d") - timedelta(days=num_months*30)).strftime("%Y-%m-%d")
stock = yf.Ticker(stock_ticker)
if hasattr(stock, 'recommendations'):
recommendations = stock.recommendations
if recommendations is None or recommendations.empty:
print(f"No analyst recommendations found for {stock_ticker}")
return None
else:
print(f"Recommendations data not available for {stock_ticker}")
return None
recommendations = recommendations.loc[start_date:end_date]
# Convert the index to a DatetimeIndex
recommendations.index = pd.to_datetime(recommendations.index)
# Resample the recommendations based on the specified interval
resampled_recommendations = recommendations.resample(f'{interval_months}ME', label='right').agg('last')
# Count the number of each recommendation grade
grade_counts = resampled_recommendations.value_counts().unstack(fill_value=0)
# Reset the index
grade_counts = grade_counts.reset_index()
# Convert the relevant column to datetime and format it as a string
grade_counts['your_datetime_column'] = pd.to_datetime(grade_counts['your_datetime_column']).dt.strftime('-%mME')
# Set the formatted column as the index
grade_counts = grade_counts.set_index('your_datetime_column')
grade_counts.index = grade_counts.index.strftime('-%mME')
# Rename the columns to match the desired output format
grade_counts.columns = grade_counts.columns.str.replace(' ', '')
grade_counts = grade_counts.reindex(columns=['strongBuy', 'Buy', 'Hold', 'Sell', 'strongSell']).fillna(0).astype(int)
# Add the '0m' row at the beginning
grade_counts.loc['0m'] = 0
grade_counts = grade_counts.sort_index(ascending=False)
return grade_counts
# Example usage
stock_ticker = "AAPL"
num_months = 24
interval_months = 2
end_date = "05/06/2024"
recommendations = get_analyst_recommendations(stock_ticker, num_months, interval_months, end_date)
print(recommendations)
你把事情搞得太复杂了一点。我建议采用这种方法:
import pandas as pd
import yfinance as yf
from datetime import datetime, timedelta
def get_analyst_recommendations(stock_ticker, num_periods, interval_months, end_date=None):
if end_date is None:
end_date = datetime.now()
else:
end_date = datetime.strptime(end_date, "%m/%d/%Y")
start_date = end_date - timedelta(days=interval_months * 30 * num_periods)
stock = yf.Ticker(stock_ticker)
recommendations = stock.recommendations
current_date = end_date
recommendations['Date'] = [current_date - pd.DateOffset(months=i) for i in range(len(recommendations))]
recommendations.set_index('Date', inplace=True)
recommendations = recommendations[(recommendations.index >= start_date) & (recommendations.index <= end_date)]
if recommendations.empty:
print("No data in the specified date range:", start_date, "to", end_date)
return None
resampled_recommendations = recommendations.resample(f'{interval_months}M').last()
return resampled_recommendations
stock = yf.Ticker("AAPL")
recommendations = stock.recommendations
print("Current Analyst Recommendations:")
print(recommendations)
custom_recommendations = get_analyst_recommendations('AAPL', num_periods=12, interval_months=2, end_date='05/07/2024')
print("Custom Time-based Analyst Recommendations:")
print(custom_recommendations)
这会给你(结合普通推荐)
Current Analyst Recommendations:
period strongBuy buy hold sell strongSell
0 0m 11 21 6 0 0
1 -1m 10 17 12 2 0
2 -2m 10 17 12 2 0
3 -3m 10 24 7 1 0
Custom Time-based Analyst Recommendations:
period strongBuy buy hold sell strongSell
Date
2024-02-29 -3m 10 24 7 1 0
2024-04-30 -1m 10 17 12 2 0
2024-06-30 0m 11 21 6 0 0