xxxxxxxxxx
使用说明,修改stocks股票代码,这个地址查看价格:https://au.finance.yahoo.com/
修改投入金额:investment_amount
修改开始和结束时间:investment_date 、end_date
获取雅虎数据接口需要vpn。
xxxxxxxxxx
pip install yfinance
pip install pandas
ximport yfinance as yf
import pandas as pd
from datetime import datetime
input_money= 200000
# 股票代码和投资信息
stocks = {
"贵州茅台": "600519.SS", # 贵州茅台
"中国平安": "601318.SS", # 中国平安
"格力电器": "000651.SZ",# 格力电器
"招商银行": "600036.SS", # 招商银行
"万科A": "000002.SZ" # 万科A
}
investment_amount = 200000 # 投资金额(人民币)
investment_date = "2013-11-11"
end_date = "2023-11-11"
problem="如果我在{} 买入 {}这些股票 每只股票买入{},那么截止到{},我的收益是怎样的".format(investment_date,stocks,investment_amount,end_date)
def calculate_dividends(stock_ticker,investment, investment_date, end_date,):
# 创建股票对象
stock = yf.Ticker(stock_ticker)
stock_data = yf.download(symbol, start=investment_date, end=end_date)
initial_price = stock_data['Close'].iloc[0]
shares_purchased = investment / initial_price
# 获取股票的历史分红数据
dividends = stock.dividends
# 筛选出指定时间段内的分红
filtered_dividends = dividends[(dividends.index >= investment_date) & (dividends.index <= end_date)]
# 计算总分红
total_dividends = filtered_dividends.sum() * shares_purchased
return total_dividends
# 计算投资回报的函数
def calculate_return(symbol, investment, start_date, end_date):
stock_data = yf.download(symbol, start=start_date, end=end_date)
# print("历年价格:\n{}".format(stock_data))
# print("股票代码:{}".format(symbol))
initial_price = stock_data['Close'].iloc[0]
# print("{}价格:{}".format(investment_date,initial_price))
final_price = stock_data['Close'].iloc[-1]
# print("{}价格:{}".format(end_date,final_price))
shares_purchased = investment / initial_price
# print("购买金额:{}/{}当年价格{},得到持仓数量:{}".format(investment,investment_date,initial_price,shares_purchased))
final_value = shares_purchased * final_price
# print("现在时间{},现在价格{},持仓数量:{},持仓市值{}".format(end_date, final_price, shares_purchased, final_value))
profit = final_value - investment
# print("当前收益{},减去买入金额{},得到利润{}".format(final_value,investment,profit))
return profit
# 为每只股票计算并输出收益
results = {}
total_dividends = {}
for stock, symbol in stocks.items():
profit = calculate_return(symbol, investment_amount, investment_date, end_date)
dividends = calculate_dividends(symbol,investment_amount ,investment_date, end_date)
results[stock] = profit
total_dividends[stock] = dividends
# 将结果输出为 DataFrame
# results_df = pd.DataFrame.from_dict(results, orient='index', columns=['Profit'])
# print(results_df)
print("--------")
print(problem)
print("--------")
print("股票差价净利润如下:")
total_sum = 0
for k,v in results.items():
print(k,v)
total_sum += v
print("--------")
print("股票分红如下:")
total_dividends_sum = 0
for k,v in total_dividends.items():
print(k,v)
total_dividends_sum += v
#计算总投入
total_sum_input = (len(results)) * int(input_money)
# 将字符串格式的日期转换为 datetime 对象
investment_date_dt = datetime.strptime(investment_date, "%Y-%m-%d")
end_date_dt = datetime.strptime(end_date, "%Y-%m-%d")
# 计算两个日期之间的年数差异
difference_in_years = end_date_dt.year - investment_date_dt.year
# print(difference_in_years)
#计算每年收益
all_sum = total_sum + total_dividends_sum
annual_return_rate = (all_sum / total_sum_input) / difference_in_years
annual_return_rate_percentage = annual_return_rate * 100 # 转换为百分比
print("--------")
print("投入总金额:{}".format(total_sum_input))
print("--------")
print("股票差价总收益:{}".format(total_sum))
print("--------")
print("总分红:{}".format(total_dividends_sum))
print("--------")
print("股票收益+分红:{}".format(all_sum))
print("--------")
print("投资{}年,股票差价+分红,平均每年收益率:{}".format(difference_in_years,annual_return_rate_percentage))