python对股票分析有啥作用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python对股票分析有啥作用相关的知识,希望对你有一定的参考价值。

参考技术A 你好,Python对于股票分析来说,用处是很大的
Python,用数据软件分析可以做股票的量化程序,因为股票量化是未来的一种趋势,能够解决人为心理波动和冲动下单等不良行为,所以学好python量化的话,那么对股票来说有很大很大帮助

Python实现股票数据分析的可视化

Python实现股票数据分析的可视化

一、简介

我们知道在购买股票的时候,可以使用历史数据来对当前的股票的走势进行预测,这就需要对股票的数据进行获取并且进行一定的分析,当然了,人们是比较喜欢图形化的界面的,因此,我们在这里采用一种可视化的方法来实现股票数据的分析。

二、代码

1、主文件

from work1 import get_data
from work1 import read_data
from work1 import plot_data
import pymysql
from uitest import MyFrame1
import wx
from database1 import write_to_base
import time


class 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 pymysql
import pandas as pd


def 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 wx
import 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 np
import tushare as ts
import matplotlib.pyplot as plt
import pandas as pd


def 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 df


def 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()






三、数据样例的展示

,ts_code,trade_date,open,high,low,close,pre_close,change,pct_chg,vol,amount
0,000001.SZ,20201130,19.9,20.88,19.59,19.74,19.7,0.04,0.203,1581441.28,3213680.47
1,000001.SZ,20201127,20.0,20.0,19.38,19.7,19.5,0.2,1.0256,753773.74,1479430.635
2,000001.SZ,20201126,19.05,19.61,19.03,19.5,19.06,0.44,2.3085,639657.89,1240074.378
3,000001.SZ,20201125,19.48,19.7,19.05,19.06,19.36,-0.3,-1.5496,552585.01,1068352.014
4,000001.SZ,20201124,19.62,19.68,19.17,19.36,19.62,-0.26,-1.3252,678543.23,1313496.136
5,000001.SZ,20201123,18.85,19.62,18.8,19.62,18.86,0.76,4.0297,1165858.26,2252290.578
6,000001.SZ,20201120,18.83,18.99,18.52,18.86,18.85,0.01,0.0531,673919.22,1265262.915
7,000001.SZ,20201119,18.59,18.98,18.3,18.85,18.46,0.39,2.1127,1211740.62,2270476.474
8,000001.SZ,20201118,17.78,18.5,17.75,18.46,17.83,0.63,3.5334,1373400.72,2508632.642
9,000001.SZ,20201117,17.38,17.93,17.25,17.83,17.37,0.46,2.6482,852930.51,1509511.577
10,000001.SZ,20201116,17.08,17.43,16.9,17.37,17.18,0.19,1.1059,759856.93,1308190.459
11,000001.SZ,20201113,17.42,17.47,16.69,17.18,17.66,-0.48,-2.718,1289189.23,2191492.021
12,000001.SZ,20201112,17.81,17.94,17.45,17.66,17.81,-0.15,-0.8422,677258.48,1197284.181
13,000001.SZ,20201111,18.2,18.3,17.6,17.81,18.11,-0.3,-1.6565,940130.07,1677811.478
14,000001.SZ,20201110,18.0,18.5,17.93,18.11,17.84,0.27day32 Python与金融量化分析

% 对 Python 中的字符串有啥作用?

Cython 对进口有啥作用?

Python中的“ @”(@)符号有啥作用?

Python在信息工程学院有啥作用?

python的“re.compile”有啥作用?