文章目录
一、简介
二、代码
三、资料样例的展示
四、效果展示
1、主档案
2、数据库使用档案
3、ui设计模块
4、资料处理模块
Python实作股票资料分析的可视化
一、简介
我们知道在购买股票的时候,可以使用历史资料来对当前的股票的走势进行预测,这就需要对股票的资料进行获取并且进行一定的分析,当然了,人们是比较喜欢图形化的界面的,因此,我们在这里采用一种可视化的方法来实作股票资料的分析,
二、代码
1、主档案
from work1 import get_datafrom work1 import read_datafrom work1 import plot_dataimport pymysqlfrom uitest import MyFrame1import wxfrom database1 import write_to_baseimport timeclass CalcFrame(MyFrame1): def __init__(self, parent): MyFrame1.__init__(self, parent) # Virtual event handlers, overide them in your derived class def get_data(self, event): """ 获取资料 :param event: 点击 :return: 空 """ get_data() time.sleep(2) dlg = wx.MessageDialog(None, '已经成功获取资料', '获取资料') result = dlg.ShowModal() dlg.Destroy() event.Skip() def store_data(self, event): """ 存盘资料 :param event: 点击 :return: 空 """ write_to_base() dlg = wx.MessageDialog(None, '已经成功存盘资料', '存盘资料') result = dlg.ShowModal() dlg.Destroy() event.Skip() def read_data(self, event): """ 读取资料 :param event: 点击 :return: 空 """ df0 = read_data() dlg = wx.MessageDialog(None, '已经成功读取资料', '读取资料') result = dlg.ShowModal() dlg.Destroy() event.Skip() def show_data(self, event): """ 展示资料 :param event: 点击 :return: 空 """ df0 = read_data() plot_data(df0) event.Skip()if __name__ == '__main__': """ 主函式 """ app = wx.App(False) frame = CalcFrame(None) frame.Show(True) # start the applications app.MainLoop()
2、数据库使用档案
import pymysqlimport pandas as pddef write_to_base(): # pass """ 写入数据库 :return:空 """ df0 = pd.read_csv('./data.csv') df0[['ts_code']] = df0[['ts_code']].astype(str) df0[['trade_date']] = df0[['trade_date']].astype(str) df0[['open']] = df0[['open']].astype(str) df0[['high']] = df0[['high']].astype(str) df0[['low']] = df0[['low']].astype(str) df0[['close']] = df0[['close']].astype(str) df0[['pre_close']] = df0[['pre_close']].astype(str) df0[['change']] = df0[['change']].astype(str) df0[['pct_chg']] = df0[['pct_chg']].astype(str) df0[['vol']] = df0[['vol']].astype(str) df0[['amount']] = df0[['amount']].astype(str) # df0[['pre_close']] = df0[['pre_close']].astype(str) # df0[['ts_code']] = df0[['ts_code']].astype(str) # 打开数据库连接 # print(data) # data = tuple(data) db = pymysql.connect(host="localhost", user="root", password="671513", db="base1") # 使用cursor()方法获取操作游标 cursor = db.cursor() # db.commit() # db.ping(reconnect=True) db.ping(reconnect=True) cursor.execute("use base1") db.commit() cursor.execute("truncate table tb") db.commit() sql = "INSERT INTO tb(ts_code,trdae_date,open,high,low,close,pre_close,changed,pct_chg,vol,amount) \ VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" # ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" # ('000001.SZ','20210716','21.41','21.82','21.3','21.34','21.62','-0.28','-1.2951','573002.61','1230180.813') # ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s') for i in range(220): db.ping(reconnect=True) # 执行sql陈述句 cursor.execute(sql %\ (df0.iloc[i, 1], df0.iloc[i, 2], df0.iloc[i, 3], df0.iloc[i, 4], df0.iloc[i, 5], df0.iloc[i, 6], df0.iloc[i, 7], df0.iloc[i, 8], df0.iloc[i, 9], df0.iloc[i, 10], df0.iloc[i, 11])) # 执行sql陈述句 db.commit() # 关闭数据库连接 db.close()
3、ui设计模块
# -*- coding: utf-8 -*-############################################################################# Python code generated with wxFormBuilder (version Jun 17 2015)## http://www.wxformbuilder.org/#### PLEASE DO "NOT" EDIT THIS FILE!###########################################################################import wximport wx.xrc############################################################################# Class MyFrame1###########################################################################class MyFrame1(wx.Frame): def __init__(self, parent): wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=u"股票资料分析", pos=wx.DefaultPosition, size=wx.Size(309, 300), style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL) self.SetSizeHintsSz(wx.DefaultSize, wx.DefaultSize) bSizer1 = wx.BoxSizer(wx.VERTICAL) self.m_button1 = wx.Button(self, wx.ID_ANY, u"获取资料", wx.DefaultPosition, wx.DefaultSize, 0) bSizer1.Add(self.m_button1, 1, wx.ALL | wx.EXPAND, 5) self.m_button2 = wx.Button(self, wx.ID_ANY, u"存盘资料", wx.DefaultPosition, wx.DefaultSize, 0) bSizer1.Add(self.m_button2, 1, wx.ALL | wx.EXPAND, 5) self.m_button3 = wx.Button(self, wx.ID_ANY, u"读取资料", wx.DefaultPosition, wx.DefaultSize, 0) bSizer1.Add(self.m_button3, 1, wx.ALL | wx.EXPAND, 5) self.m_button4 = wx.Button(self, wx.ID_ANY, u"展示曲线", wx.DefaultPosition, wx.DefaultSize, 0) bSizer1.Add(self.m_button4, 1, wx.ALL | wx.EXPAND, 5) self.SetSizer(bSizer1) self.Layout() self.Centre(wx.BOTH) # Connect Events self.m_button1.Bind(wx.EVT_BUTTON, self.get_data) self.m_button2.Bind(wx.EVT_BUTTON, self.store_data) self.m_button3.Bind(wx.EVT_BUTTON, self.read_data) self.m_button4.Bind(wx.EVT_BUTTON, self.show_data) def __del__(self): pass # Virtual event handlers, overide them in your derived class def get_data(self, event): event.Skip() def store_data(self, event): event.Skip() def read_data(self, event): event.Skip() def show_data(self, event): event.Skip()### class CalcFrame(MyFrame1):# def __init__(self, parent):# MyFrame1.__init__(self, parent)### app = wx.App(False)## frame = CalcFrame(None)## frame.Show(True)## # start the applications# app.MainLoop()
4、资料处理模块
import numpy as npimport tushare as tsimport matplotlib.pyplot as pltimport pandas as pddef get_data(): """ 获取资料 :return: 空 """ # 获取股票的资料 pro = ts.pro_api('c62ba9195fa8b54ff78a38cab1cec01b15def7f47c32f91fb273ee3a') df = pro.daily(ts_code='000001.SZ', start_date='20200101', end_date='20201130') # 存盘资料到一个档案中 df.to_csv('./data.csv') print(df)def read_data(): """ 读取资料 :return: 空 """ # 读取资料 df = pd.read_csv('./data.csv') # 洗掉不需要的行 df = df.drop(['Unnamed: 0'], axis=1) df = df.drop(['ts_code'], axis=1) # 反转行使得时间是从前到后的 df = df.iloc[::-1, :] # 将时间由数字转为字符串 for i in range(220): df.iloc[i, 0] = str(df.iloc[i, 0]) # 将字符串转为时间型别的资料 df['trade_date'] = pd.to_datetime(df['trade_date']) # 将时间设定为索引 df = df.set_index(['trade_date']) df = df.iloc[:, :] print(df) return dfdef plot_data(df): """ 展示资料 :param df: 一个DataFrame :return: 空 """ ma5 = (df['close'].rolling(5).mean()).iloc[30:] ma10 = (df['close'].rolling(10).mean()).iloc[30:] ma20 = (df['close'].rolling(20).mean()).iloc[30:] plt.figure(figsize=(16, 9)) l1, = plt.plot(ma5, label="ma5") l2, = plt.plot(ma10, label="ma10") l3, = plt.plot(ma20, label="ma20") l4, = plt.plot(df['close'].iloc[30:], label="close") plt.legend(handles=[l1, l2, l3, l4], labels=["ma5", "ma10", "ma20", "close"]) plt.show()
0 评论