怎么用python画出一只股票连续20日的k线图
时间: 2024-12-25 21:27:31 浏览: 5
在Python中,可以使用matplotlib和yfinance库来绘制股票K线图。以下是一个基本的例子,展示如何画出Apple Inc (AAPL)连续20天的K线图:
```python
import yfinance as yf
import matplotlib.pyplot as plt
# 下载AAPL的历史数据
ticker = 'AAPL'
df = yf.download(ticker, period='20d')
# 数据预处理 - 挑选日期和开盘价、收盘价、最高价、最低价
df['Date'] = pd.to_datetime(df.index)
df = df[['Date', 'Close', 'Open', 'High', 'Low']].dropna()
# 绘制K线图
plt.figure(figsize=(10,6))
plt.plot(df['Date'], df['Close'], label='Closing Price')
plt.plot(df['Date'], df['Open'], 'r', marker='o', linestyle='', ms=3, label='Opening Price')
plt.plot(df['Date'], df['High'], 'g', marker='^', linestyle='', ms=3, label='Highest Price')
plt.plot(df['Date'], df['Low'], 'b', marker='_', linestyle='', ms=3, label='Lowest Price')
plt.fill_between(df['Date'], df['Low'], df['High'], color='grey', alpha=0.3)
# 添加元素和标签
plt.title(f'{ticker} Stock - Last 20 Days K-line Chart')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.grid(True)
plt.show()
```
阅读全文