Yahoo Finance API 使用教程
项目地址:https://gitcode.com/gh_mirrors/ya/yahoofinance-api
项目介绍
Yahoo Finance API 是一个开源项目,旨在通过 Yahoo Finance 的公开 API 下载市场数据。该项目适用于研究和教育目的,提供了线程化和 Pythonic 的方式来访问 Yahoo Finance 的数据。用户在使用时应注意遵守 Yahoo 的条款和条件,该 API 主要用于个人使用。
项目快速启动
安装
首先,使用 pip 安装 yfinance 库:
pip install yfinance --upgrade --no-cache-dir
快速示例
以下是一个简单的 Python 脚本,用于获取 Apple 公司的股票数据:
import yfinance as yf
# 获取 Apple 公司的股票数据
apple = yf.Ticker("AAPL")
# 获取最近 5 天的历史数据
hist = apple.history(period="5d")
# 打印数据
print(hist)
应用案例和最佳实践
案例一:股票数据分析
使用 Yahoo Finance API 可以轻松获取股票的历史数据,进行技术分析或基本面分析。例如,可以计算股票的移动平均线,分析其趋势。
import yfinance as yf
import matplotlib.pyplot as plt
# 获取 Apple 公司的股票数据
apple = yf.Ticker("AAPL")
# 获取最近 30 天的历史数据
hist = apple.history(period="30d")
# 计算 5 天和 20 天的移动平均线
hist['MA5'] = hist['Close'].rolling(window=5).mean()
hist['MA20'] = hist['Close'].rolling(window=20).mean()
# 绘制图表
plt.figure(figsize=(14, 7))
plt.plot(hist['Close'], label='Close Price')
plt.plot(hist['MA5'], label='5-Day MA')
plt.plot(hist['MA20'], label='20-Day MA')
plt.legend()
plt.show()
案例二:实时监控股票价格
可以编写一个脚本,实时监控特定股票的价格,并在价格达到某个阈值时发送通知。
import yfinance as yf
import time
def monitor_stock(ticker, threshold):
stock = yf.Ticker(ticker)
while True:
price = stock.history(period="1d")['Close'][0]
print(f"Current price of {ticker}: {price}")
if price > threshold:
print(f"Alert: {ticker} price exceeded {threshold}!")
# 发送通知的代码可以在这里添加
time.sleep(60) # 每分钟检查一次
monitor_stock("AAPL", 150)
典型生态项目
项目一:Pandas 数据处理
Yahoo Finance API 获取的数据可以直接与 Pandas 库结合使用,进行复杂的数据处理和分析。
import yfinance as yf
import pandas as pd
# 获取 Apple 公司的股票数据
apple = yf.Ticker("AAPL")
# 获取最近一年的历史数据
hist = apple.history(period="1y")
# 使用 Pandas 进行数据处理
hist['Daily_Return'] = hist['Close'].pct_change()
hist['Cumulative_Return'] = (1 + hist['Daily_Return']).cumprod()
print(hist)
项目二:Matplotlib 数据可视化
结合 Matplotlib 库,可以将股票数据可视化,更直观地展示数据趋势。
import yfinance as yf
import matplotlib.pyplot as plt
# 获取 Apple 公司的股票数据
apple = yf.Ticker("AAPL")
# 获取最近一年的历史数据
hist = apple.history(period="1y")
# 绘制收盘价图表
plt.figure(figsize=(14, 7))
plt.plot(hist['Close'], label='Close Price')
plt.legend()
plt.show()
通过以上教程,您可以快速上手使用 Yahoo Finance API,并结合其他开源库进行更深入的数据分析和可视化。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考