请用python与金融相关的第三方库写计算股票收益率的代码,简洁
时间: 2024-09-12 18:13:33 浏览: 142
在Python中,我们可以使用pandas库来处理金融数据,以及matplotlib库来进行可视化,结合其他第三方库如yfinance来获取实时股票价格。下面是一个简单的示例,演示如何计算股票收益率:
```python
# 导入所需库
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
# 获取股票数据
def get_stock_data(ticker):
stock_info = yf.download(ticker, period='1d', start='2020-01-01') # 可自定义开始日期
return stock_info['Close']
# 计算每日收益率
def calculate_daily_return(data):
daily_returns = data.pct_change() # 使用pct_change计算百分比变化
daily_returns.iloc[0] = 0 # 设置第一个值为0,因为第一天没有前一天的价格作为基础
return daily_returns
# 示例:计算AAPL(苹果公司)的收益率
ticker = 'AAPL'
stock_prices = get_stock_data(ticker)
returns = calculate_daily_return(stock_prices)
# 绘制收益率图表
plt.figure(figsize=(10,6))
returns.plot()
plt.title('Apple Inc. (AAPL) Daily Returns')
plt.xlabel('Date')
plt.ylabel('Return')
plt.show()
# 相对总收益率
total_return = returns.sum()
print(f"Total relative return over the period: {total_return*100}%")
# 年化收益率(假设每年交易日252天)
annualized_return = (1 + total_return)**(252/len(returns)) - 1
print(f"Annualized return: {annualized_return * 100}%")
阅读全文
相关推荐


















