用pandas读取MySQL数据库中,某只股票100天的日交易数据,将查询结果返回的dataframe里的数据,直接保存到Excel文件中,并绘制日收盘价格走势、5天移动均线、10天移动均线
时间: 2024-03-21 10:41:54 浏览: 22
好的,可以使用以下代码实现你的需求:
```python
import pandas as pd
import pymysql
import matplotlib.pyplot as plt
# 连接MySQL数据库
conn = pymysql.connect(host='localhost', port=3306, user='root', password='yourpassword', database='yourdatabase')
# 查询数据
sql = "SELECT * FROM stock WHERE code='000001' AND date>='2021-01-01' AND date<='2021-04-10'"
df = pd.read_sql(sql, conn)
# 保存数据到Excel文件
df.to_excel('stock_data.xlsx', index=False)
# 绘制走势图
plt.plot(df['date'], df['close'], label='Close')
ma5 = df['close'].rolling(window=5).mean()
plt.plot(df['date'], ma5, label='MA5')
ma10 = df['close'].rolling(window=10).mean()
plt.plot(df['date'], ma10, label='MA10')
plt.legend()
plt.show()
```
需要注意的是,上面的代码中需要替换以下参数:
- `yourpassword`:MySQL数据库的密码
- `yourdatabase`:MySQL数据库的名称
- `code`:需要查询的股票代码
- `2021-01-01`和`2021-04-10`:需要查询的时间范围
另外,需要安装`pandas`、`pymysql`和`matplotlib`这三个库。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)