import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
# 设置要分析的股票代码
stock_symbols = ["SHOP", "AMZN", "BABA", "SQ", "PYPL"]
# 获取历史股价数据并按季度计算平均股价
stock_data = {}
for symbol in stock_symbols:
stock = yf.Ticker(symbol)
history = stock.history(start="2015-01-01", end="2022-12-31")
history["quarter"] = pd.PeriodIndex(history.index, freq='Q')
average_prices = history.groupby("quarter")["Close"].mean()
stock_data[symbol] = average_prices
# 转换 Period 类型为 datetime 类型
for symbol, data in stock_data.items():
data.index = data.index.to_timestamp()
# 绘制每个股票的季度平均股价折线图
plt.figure(figsize=(10, 6))
for symbol, data in stock_data.items():
plt.plot(data.index, data.values, label=symbol)
plt.title("Quarterly Average Stock Price Comparison")
plt.xlabel("Quarter")
plt.ylabel("Stock Price (USD)")
plt.legend()
plt.show()
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
# 设置要分析的股票代码
stock_symbols = ["SHOP", "AMZN", "BABA", "SQ", "PYPL"]
# 获取历史股价数据并按月计算平均股价
stock_data = {}
for symbol in stock_symbols:
stock = yf.Ticker(symbol)
history = stock.history(start="2015-01-01", end="2022-12-31")
history["month"] = pd.PeriodIndex(history.index, freq='M')
average_prices = history.groupby("month")["Close"].mean()
stock_data[symbol] = average_prices
# 转换 Period 类型为 DatetimeIndex 类型
for symbol, data in stock_data.items():
data.index = pd.to_datetime(data.index.to_timestamp())
# 绘制每个股票的月度平均股价折线图
plt.figure(figsize=(10, 6))
for symbol, data in stock_data.items():
plt.plot(data.index, data.values, label=symbol)
plt.title("Monthly Average Stock Price Comparison")
plt.xlabel("Month")
plt.ylabel("Stock Price (USD)")
plt.legend()
plt.show()
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
# 设置要分析的股票代码
stock_symbols = ["SHOP", "AMZN", "BABA", "SQ", "PYPL"]
# 获取历史股价数据并按日计算平均股价
stock_data = {}
for symbol in stock_symbols:
stock = yf.Ticker(symbol)
history = stock.history(start="2015-01-01", end="2022-12-31")
average_prices = history["Close"].resample("D").mean()
stock_data[symbol] = average_prices
# 绘制每个股票的日度平均股价折线图
plt.figure(figsize=(10, 6))
for symbol, data in stock_data.items():
plt.plot(data.index, data.values, label=symbol)
plt.title("Daily Average Stock Price Comparison")
plt.xlabel("Date")
plt.ylabel("Stock Price (USD)")
plt.legend()
plt.show()