Tushare
金融数据接口库
yfinance (Yahoo Finance 数据接口) 是一个 Python 库,用于从 Yahoo Finance 获取金融数据,包括股票、ETF、期权、加密货币等市场数据。它是 pandas-datareader 的替代方案,提供了更稳定、更灵活的接口,适用于量化交易、数据分析和金融研究。
pip install yfinance
建议使用anaconda或者miniconda安装,方便管理。
import yfinance as yf
import matplotlib.pyplot as plt
from datetime import datetime
# 获取TSLA数据
tsla = yf.Ticker("TSLA")
end_date = datetime.now().strftime('%Y-%m-%d')
tsla_hist = tsla.history(start='2024-06-01', end=end_date)
# 创建图表
plt.figure(figsize=(12, 6))
# 绘制收盘价
plt.plot(tsla_hist.index, tsla_hist['Close'], label='Close Price', color='blue', linewidth=2)
# 添加标题和标签
plt.title(f'TSLA Stock Price (June 2024 - {end_date})', fontsize=14)
plt.xlabel('Date', fontsize=12)
plt.ylabel('Price ($)', fontsize=12)
# 添加网格和图例
plt.grid(True, linestyle='--', alpha=0.7)
plt.legend(fontsize=12)
# 自动调整日期显示
plt.gcf().autofmt_xdate()
# 显示图表
plt.show()
import yfinance as yf
meta = yf.Ticker("META")
print("Meta 公司名称:", meta.info['longName'])
print("市值:", meta.info['marketCap'])
print("市盈率 (P/E):", meta.info['trailingPE'])
output:
Meta 公司名称: Meta Platforms, Inc.
市值: 1807828516864
市盈率 (P/E): 28.086329
更新API用法请参考
API Reference – https://ranaroussi.github.io/yfinance/reference/index.html
DataFrame,方便分析