Python 繪圖

圖表3D


程式碼

# -*- coding: utf-8 -*-

import sys
import matplotlib.pyplot as plt
from matplotlib.font_manager import fontManager
import numpy as np
import plotly
import plotly.plotly as py
from plotly.graph_objs import *
import csv
from datetime import datetime


class PlotSP500:

    plotData_X = None
    plotData_Y = None

    def __init__(self):
        pass

    def loadFile(self, csvFile):
        X = []
        Y = []

        csvF = open(csvFile, 'r')
        fieldHead = True
        for rowDB in csv.DictReader(csvF, ["日期", "開盤", "最高", "最低", "收盤", "成交量", "盤後"]):
            if fieldHead:
                fieldHead = False
            else:
                if (rowDB is not None):
                    stockDate = rowDB['日期'].strip()

                    X.append(
                            datetime(
                                int(stockDate[0:4]),
                                int(stockDate[4:6]),
                                int(stockDate[6:8])).strftime("%Y-%m-%d")
                            )
                    Y.append(
                        [
                           float(rowDB['開盤']),
                           float(rowDB['收盤']),
                           float(rowDB['最高']),
                           float(rowDB['最低'])
                    ])

        self.plotData_X = np.array(X)
        self.plotData_Y = np.array(Y, float)

    def printData(self):
        for i in range(0, len(self.plotData_X)):
            Y = self.plotData_Y[i, :]
            print "%s\t" % (self.plotData_X[i]),
            for j in range(0, 4):
                print "%.2f\t" % (Y[j]),

            print

    def plotCloud(self):
        plotly.tools.set_credentials_file(username='power.elinks',
            api_key='u3pzoya9ne',
            stream_ids=['cj1hw453qe', '70ntqzdgzq'])

        X = self.plotData_X

        plot_data = Data([
            Scatter(x=X, y=self.plotData_Y[:, 0], name="開盤"),
            Scatter(x=X, y=self.plotData_Y[:, 1], name="收盤"),
            Scatter(x=X, y=self.plotData_Y[:, 2], name="最高"),
            Scatter(x=X, y=self.plotData_Y[:, 3], name="最低")
            ])

        plot_url = py.plot(
            Figure(
                data=plot_data,
                layout=Layout(title=u"S&P500 指數線圖")),
            filename='S&P500')

        print plot_url

    def plotLocal(self):
        plt.rcParams["font.family"] = 'Microsoft MHei'
        plt.title(u"S&P500 指數線圖")
        plt.xlabel(u"日期")
        plt.ylabel(u"指數")

        plt.plot(range(0, self.plotData_X.size), self.plotData_Y[:, 0], label=u'開盤')
        plt.plot(range(0, self.plotData_X.size), self.plotData_Y[:, 1], label=u'收盤')
        plt.plot(range(0, self.plotData_X.size), self.plotData_Y[:, 2], label=u'最高')
        plt.plot(range(0, self.plotData_X.size), self.plotData_Y[:, 3], label=u'最低')

        plt.legend(loc='lower left')
        plt.show()

    def outputFont(self):
        for font in fontManager.ttflist:
            print font


if __name__ == "__main__":
    csvFile = 'SP500.csv'
    plotOnCloud = False

    if len(sys.argv) > 1:
        csvFile = sys.argv[1]

    if len(sys.argv) > 2:
        plotOnCloud = True

    plotSP500 = PlotSP500()

    if False:
        plotSP500.outputFont()

    plotSP500.loadFile(csvFile)

    if plotOnCloud:
        plotSP500.plotCloud()
    else:
        plotSP500.plotLocal()
ċ
SP500-1.py
(4k)
李智,
2015年4月14日 上午5:25
ċ
SP500.csv
(4k)
李智,
2015年4月14日 上午5:19