Python获取阿里百度股票数据并可视化

准备工作

  1. 先安装Python,然后配置环境变量等等(网上自行找教程)

  2. 安装Anaconda3并安装各种包(pip install “你需要的工具名”),如果版本过低请更新pip

  3. 本次需要的包numpy、pandas、sqlite3、matplotlib

  4. 打开Jupyter Notebook

从雅虎财经网站上提取阿里巴巴和百度的股票数据并保存为.csv文件

保存路径可以自己选择

1
2
3
4
5
6
7
8
import numpy as np
import pandas as pd
from pandas_datareader import data as web
import datetime
alibaba = web.DataReader('BABA','yahoo',start='2010-1-1')
print (alibaba)
alibaba.to_csv(r'C:\flash\Alibaba.csv',columns=alibaba.columns,index=True)

效果图
alibaba

1
2
3
4
baidu = web.DataReader('BIDU','yahoo',start='2009-12-31')
print (baidu)
baidu.to_csv(r'C:\flash\Baidu.csv',columns=df_csvsave.columns,index=True)

利用Sqlite3生成.db文件并用Navicat premium查看

1
2
3
4
5
6
7
8
9
import sqlite3 as sq3
import datetime as dt
Alibaba='create table alibaba (Date date,High real,Low real,Open real,Close real,Volume real,Adj Close real)'
con=sq3.connect(path+'.db')
con.execute(Alibaba)
for row in alibaba:
con.execute('INSERT INTO alibaba VALUES(?, ?, ?, ?, ?, ?, ?)'),(dt.datetime.now(), row[0], row[1],row[2],row[3],row[4],row[5],row[6])
con.commit()

Navicat premium的安装及其注册就不多讲了(用其他的软件也行)
Alibaba

读取本地.csv文件并可视化数据

1
2
3
path='C:/flash/Alibaba'
pd.read_csv(path+'.csv')['Close'].plot(figsize=(8, 5), grid=True,title="Alibaba")

效果图
Alibaba

读取本地Sqlite3数据库文件并可视化数据

1
2
3
4
5
import pandas.io.sql as pds
con = sqlite3.connect("C:/flash/Baidu.db")
data = pds.read_sql('select * from baidu',con)
data.head()

Baidu

1
2
3
4
5
6
7
8
plt.plot(data["Date"],data["Close"],label='Close',linewidth=3,color='r',)
plt.xlabel("Date")
plt.ylabel('Close')
plt.title("Alibaba Close")
plt.legend()
plt.grid()
plt.show()

Alibaba