Example #1
0
    def __init__(self,PLOTSEC=600,outfname='stripchartTemp',PDio=4):
        self.PLOTSEC = PLOTSEC #PLOTSEC #720 # 12 minute sessions for x axis
        self.QUITS = ("q","Q")
        self.STARTIN = ('I','i')
        self.ENDIN = ('E','e')
        self.PDio = PDio
        # Uncomment one of the blocks of code below to configure your Pi or BBB to use
        # software or hardware SPI.
        # Raspberry Pi software SPI configuration.
        #CLK = 25
        #CS  = 24
        #DO  = 18
        #sensor = MAX31855.MAX31855(CLK, CS, DO)
        # Raspberry Pi hardware SPI configuration.
        self.SPI_PORT   = 0
        self.SPI_DEVICE = 0
        self.sensor = MAX31855.MAX31855(spi=SPI.SpiDev(self.SPI_PORT, self.SPI_DEVICE))
        # BeagleBone Black software SPI configuration.
        #CLK = 'P9_12'
        #CS  = 'P9_15'
        #DO  = 'P9_23'
        #sensor = MAX31855.MAX31855(CLK, CS, DO)
        # BeagleBone Black hardware SPI configuration.
        #SPI_PORT   = 1
        #SPI_DEVICE = 0
        #sensor = MAX31855.MAX31855(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
        self.blinkYlevel = 20 # where blink off will appear
        self.blinkYactive = 25
        self.blinkThresh = 2500
        # this works for me and my blu-tac. Your mileage may vary. Try raising it and seeing where
        # the hi and low readings tend to cluster - then choose a sensible threshold to reliably distinguish
        # them
        self.maxPhotoDetReads = self.blinkThresh + 1 # about 0.06 sec sampling truncating at 5k cycles
        # self.maxPhotoDetReads = 100000 # about 0.23 sec sampling at 30k cycles      
        self.ts = self.getTempStream()
        self.bs = self.photoDet()
        self.outf = open('%s.xls' % outfname,'w')
        self.savepng = '%s.png' % outfname
        self.outf.write('Second\tTemperature\n')
        # set up a generator for PLOTSEC seconds of sampling
        style.use('ggplot')
        # prepopulate arrays to make updates quicker
        self.t = range(self.PLOTSEC+2)
        self.y = [None for i in self.t]
        self.blinky = [None for i in self.t]
        self.blinkx = [None for i in self.t]
        self.fig, self.ax = plt.subplots()
        #self.ax.set_xlim(auto=True)
        #self.ax.set_ylim(auto=True)

        # fig.canvas.mpl_connect('key_press_event', press)
        self.line, = self.ax.plot(0,0,lw=1)
        self.blinkLine, = self.ax.plot(0,0,lw=1)
        self.text_template = 'Last temperature = %3.2f'
        self.title_template = 'Temperature strip chart at %d seconds'
        self.t_temp = self.ax.text(0.15,0.15,self.text_template%(0),
                                   transform=self.ax.transAxes, family='monospace',fontsize=10)
        #self.t_title = self.ax.text(0.5,1.0,self.title_template%(0),
        #                            transform=self.ax.transAxes, family='monospace',fontsize=20)
        self.started = time.time()
Example #2
0
    def __init__(self, csv_file, image_path=None):
        # TODO Re-enable plotfile
        plt.subplots_adjust(left=0.13, bottom=0.33, right=0.95, top=0.89)
        style.use('seaborn-darkgrid')
        for label in self.ax1.xaxis.get_ticklabels():
            label.set_rotation(45)

        self.image_path = image_path

        self.creader = self.generate_reader(csv_file)

        self.points_generator = self.yield_points()

        self.x = []
        self.y = []

        for a, b in self.points_generator:
            self.x.append(a)
            self.y.append(b)

        self.ax1.plot_date(self.x, self.y, 'r-')

        plt.xlabel('Timestamps')
        plt.ylabel('Return Time (in milliseconds)')
        plt.title('Ping Over Time')
 def __init__(self, parent=None):
     super(OptionViewerPlotDlg, self).__init__(parent)
     
     self.setWindowTitle('Plot')
     self.resize(600,450)
     
     # a figure instance to plot on
     self.figure = plt.figure()
     
     # this is the Canvas Widget that displays the 'figure'
     # it takes the 'figure' instance as a parameter to __init__
     self.canvas = FigureCanvas(self.figure)
     
     # this is the Navigation widget
     # it takes the Canvas widget and a parent
     self.toolbar = NavigationToolbar(self.canvas, self)
     
     # Just some button connected to 'plot' method
     self.button = QtGui.QPushButton('Plot')
     self.button.clicked.connect(self.plot)
     
     # set the layout
     layout = QtGui.QVBoxLayout()
     layout.addWidget(self.toolbar)
     layout.addWidget(self.canvas)
     layout.addWidget(self.button)
     self.setLayout(layout)
     
     style.use('ggplot')
     rcParams['font.size'] = 12
     
     # create an axis
     self.ax = self.figure.add_subplot(111)
     self.xdata = []
     self.ydata = []
Example #4
0
def plot_wue_time(df):

    plt.rcParams['lines.linewidth'] = 1.25
    plt.rcParams.update({'mathtext.default': 'regular'})
    style.use('ggplot')
    ncols = plt.rcParams['axes.color_cycle']

    fig, ax1 = plt.subplots()
    ax2 = ax1.twinx()

    ax1.bar(df.index, df["WUE"], color=ncols[0], width=300, \
            edgecolor=ncols[0], alpha=0.7)
    ax1.xaxis_date()
    ax2.plot_date(df.index, df["dWUE_dt"], '-', c=ncols[1], lw=3)

    ax1.set_ylabel(r'WUE (mol H$_{2}$O mol$^{-1}$ CO$_{2}$)')
    ax2.set_ylabel(r'$\partial$WUE/$\partial$t (mol H$_{2}$O mol$^{-1}$ CO$_{2}$)')

    ax1.set_ylim([0, 3.2])
    ax2.set_ylim([-1, 1])

    ax2.grid(False)

    plt.show()

    return 1
Example #5
0
def plot_wue_ppt(df):

    plt.rcParams['lines.linewidth'] = 1.25
    plt.rcParams.update({'mathtext.default': 'regular'})
    style.use('ggplot')
    ncols = plt.rcParams['axes.color_cycle']

    fig, ax1 = plt.subplots()
    ax2 = ax1.twinx()

    ax1.plot(df['Rainfall'], df["WUE"], 'o', c=ncols[0], alpha=0.7)
    ax2.plot(df['Rainfall'], df["dWUE_dt"], 'o', c=ncols[1], lw=3)

    ax1.set_xlabel(r'Rainfall (mm)')
    ax1.set_ylabel(r'WUE (mol H$_{2}$O mol$^{-1}$ CO$_{2}$)')
    ax2.set_ylabel(r'$\partial$WUE/$\partial$t (mol H$_{2}$O mol$^{-1}$ CO$_{2}$)')

    ax1.set_ylim([0, 3.2])
    ax2.set_ylim([-1, 1])

    ax2.grid(False)

    plt.show()

    return 1
Example #6
0
    def plot_trajectories(self):
        # """uses matplotlib to plot the trajectory
        # of each individual stock stored in earlier
        # trajectory array"""
        print("Creating Plot...")
        #use numpy to plot 
        self.np_price_trajectories = np.array(self.price_trajectories, dtype=float)
        self.times = np.linspace(0, self.T, self.N-1)

        #style/plot/barrier line
        style.use('dark_background')

        self.fig = plt.figure()
        self.ax1 = plt.subplot2grid((1,1),(0,0))
        for sublist in self.np_price_trajectories:
            if max(sublist) > self.B:
                self.ax1.plot(self.times,sublist,color = 'cyan')
            else:
                self.ax1.plot(self.times,sublist,color = '#e2fb86')
        plt.axhline(y=8,xmin=0,xmax=self.T,linewidth=2, color = 'red', label = 'Barrier')

        #rotate and add grid
        for label in self.ax1.xaxis.get_ticklabels():
            label.set_rotation(45)
        self.ax1.grid(True)

        #plotting stuff
        plt.xticks(np.arange(0, self.T+self.delta_t, .1))
        plt.suptitle('Stock Price Trajectory', fontsize=40)
        plt.legend()
        self.leg = plt.legend(loc= 2)
        self.leg.get_frame().set_alpha(0.4)
        plt.xlabel('Time (in years)', fontsize = 30)
        plt.ylabel('Price', fontsize= 30)
        plt.show()
def plot_dists(outpath, dists, controlsamples):
    from matplotlib import style

    style.use('ggplot')

    samplecolors = colormap_lch(len(controlsamples))
    samplessorted = sorted(controlsamples, key=lambda x: (x[1], x[0]))

    xticks = np.arange(0, dists.index[-1] + 0.1)
    xticks_disp = [format(v, 'g') for v in xtransform_rev(xticks)]

    fig, ax = plt.subplots(1, 1, figsize=(4, 3.2))
    ax.patch.set_facecolor('#f7f7f7')

    for (samplename, explength), color in zip(samplessorted, samplecolors):
        ax.plot(dists[samplename], color=color, label=samplename, zorder=3)
        ax.axvline(xtransform(explength), color=color, linewidth=2, alpha=0.3)

    leg = ax.legend(loc='center left', fontsize=10)
    plt.setp([leg.get_frame()], facecolor='white', edgecolor='#e8e8e8')

    ax.set_xlabel('Poly(A) length (nt)')
    ax.set_ylabel('Cumulative fraction')
    ax.set_title('Poly(A) length distribution', fontsize=12)

    ax.set_xticks(xticks)
    ax.set_xticklabels(xticks_disp)

    plt.setp(ax.get_xgridlines() + ax.get_ygridlines(), color='#e0e0e0')

    plt.tight_layout()

    plt.savefig(outpath)

    plt.close(fig)
Example #8
0
    def __init__(self, root, *args, **kwargs):
        """ Validates `self.title_str` and rotates plot labels. """
        super(_Plot, self).__init__(root)
        self.ptable = _PlotTable()

        # table_length validation
        try:
            table_length = kwargs['table_length']
        except KeyError:
            table_length = None
        if table_length is not None and type(table_length) is not int:
            raise TypeError('table_length is not None or int')
        if table_length is not None:
            self.ptable.length = table_length

        # title_str validation
        if type(self.title_str) is not str:
            raise TypeError('Plot title_str requires a string object')
        if self.title_str.count('\x00'):
            raise(ValueError('Title String must not have null bytes'))

        style.use('seaborn-darkgrid')

        for label in self.ax1.xaxis.get_ticklabels():
            label.set_rotation(45)

        self.canvas = FigureCanvasTkAgg(self.fig, self)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=BOTTOM, fill=BOTH, expand=True)
Example #9
0
def test_imshow_pil(fig_test, fig_ref):
    style.use("default")
    PIL = pytest.importorskip("PIL")
    png_path = Path(__file__).parent / "baseline_images/pngsuite/basn3p04.png"
    tiff_path = Path(__file__).parent / "baseline_images/test_image/uint16.tif"
    axs = fig_test.subplots(2)
    axs[0].imshow(PIL.Image.open(png_path))
    axs[1].imshow(PIL.Image.open(tiff_path))
    axs = fig_ref.subplots(2)
    axs[0].imshow(plt.imread(str(png_path)))
    axs[1].imshow(plt.imread(tiff_path))
Example #10
0
    def __init__(self, args):

        #: input argument Namespace
        self.args = args

        #: verbosity
        self.verbose = 0 if args.silent else args.verbose

        # NB: finalizing may want to log if we're being verbose
        self._finalize_arguments(args)  # post-process args

        if args.style:  # apply custom styling
            try:
                from matplotlib import style
            except ImportError:
                from matplotlib import __version__ as mpl_version
                warnings.warn('--style can only be used with matplotlib >= '
                              '1.4.0, you have {0}'.format(mpl_version))
            else:
                style.use(args.style)

        #: the current figure object
        self.plot = None

        #: figure number
        self.plot_num = 0

        #: start times for data sets
        self.start_list = unique(
            map(int, (gps for gpsl in args.start for gps in gpsl)))

        #: duration of each time segment
        self.duration = args.duration

        #: channels to load
        self.chan_list = unique(c for clist in args.chan for c in clist)

        # total number of datasets that _should_ be acquired
        self.n_datasets = len(self.chan_list) * len(self.start_list)

        #: list of input data series (populated by get_data())
        self.timeseries = []

        #: dots-per-inch for figure
        self.dpi = args.dpi
        #: width and height in pixels
        self.width, self.height = map(float, self.args.geometry.split('x', 1))
        #: figure size in inches
        self.figsize = (self.width / self.dpi, self.height / self.dpi)
        #: Flag for data validation (like all zeroes)
        self.got_error = False

        # please leave this last
        self._validate_arguments()
def graphWords(wordLst, comments):
    """
    Assumes WORDLIST is a list of words to graph and
    comments is a numpy array containing all the comments
    in the reddit post.
    """
    style.use('dark_background')
    for word in wordLst:
        counts = np.char.count(comments, word)
        plt.plot(np.cumsum(counts), label=word)
    plt.legend(loc=2)
    plt.show()
def main():
    style.use("ggplot")
    data = pd.io.stata.read_stata(DTA_FILE)
    plt.figure(1)

    draw_1(plt, data)
    draw_2(plt)
    draw_3(plt, data)
    draw_4(plt)

    plt.tight_layout()

    plt.show()
Example #13
0
def use_style(style=pb_style):
    """Shortcut for `matplotlib.style.use()`

    Parameters
    ----------
    style : dict
        The default value is the preferred pybinding figure style.
    """
    mpl_style.use(style)

    # the style shouldn't override inline backend settings
    if _is_notebook_inline_backend():
        _reset_notebook_inline_backend()
Example #14
0
    def __init__(self, frame, loss, losskeys):
        self.frame = frame
        self.loss = loss
        self.losskeys = losskeys

        self.ylim = (100, 0)

        style.use('ggplot')

        self.fig = plt.figure(figsize=(4, 4), dpi=75)
        self.ax1 = self.fig.add_subplot(1, 1, 1)
        self.losslines = list()
        self.trndlines = list()
def plotWell(time_series, edges, channels, calls, outputFig, outputFile):
	'''plotting routine'''
	MAX_CHANS = 6
	FIG_COLS = 2
	FIG_ROWS = 3
#	INCHES_PER_SUBPLOT = 10
	CORRECT_CAL = [0.0, 0.8, 0.4]
	NO_CAL = [0.0, 0.4, 0.8]
	MISS_CAL = [0.7, 0.0, 0.7]
	CHANNEL_TAG = 'CH_'
	COLORS = [[0, 0.4, 0.8],
			  [0, 0.8, 0.4],
			  [0.7, 1.0, 0.1],
			  [1.0, 0.7, 0.2],
			  [1.0, 0.2, 0.3],
			  [0.7, 0, 0.9]]

#	fig1 = plt.figure(figsize=(FIG_ROWS*INCHES_PER_SUBPLOT, FIG_COLS*INCHES_PER_SUBPLOT))
	style.use('ggplot')
	outputFig.clf()

	for i in range(len(channels)):
		ax = outputFig.add_subplot(FIG_ROWS, FIG_COLS, i + 1)
		marker_shape = '.'
		#if it is a correct call
		if calls[i] == CORRECT_CAL:
			marker_shape = 'o'
		#if it is a no call
		elif calls[i] == NO_CAL:
			marker_shape = '^'
		#if it is a miss call
		if calls[i] == MISS_CAL:
			marker_shape = 's'

		if edges[i] != -1:
			ax.plot(time_series[i], color = calls[i], linewidth = 2.0)
			ax.plot(edges[i], time_series[i][edges[i]], marker = marker_shape, linewidth = 3.0, color = calls[i])
			ax.set_title(CHANNEL_TAG + str(channels[i] + 1), fontsize = 10.0)
			ax.set_xlabel('cycles', color = [0.4, 0.4, 0.4], fontsize = 12.0)
			ax.set_ylabel('intensity', color = COLORS[channels[i]], fontsize = 12.0)
			for tl in ax.get_yticklabels():
				tl.set_color(COLORS[channels[i]])

			for tl in ax.get_xticklabels():
				tl.set_color(COLORS[channels[i]])

	outputFig.savefig(outputFile, format = 'png', dpi = 150)
	outputFig.clf()
	plt.cla()
Example #16
0
    def __init__(self,PLOTSEC=600,outfname='stripchartTemp'):
        self.PLOTSEC = 10 #PLOTSEC #720 # 12 minute sessions for x axis
        self.QUITS = ("q","Q")
        self.STARTIN = ('I','i')
        self.ENDIN = ('E','e')
        # Uncomment one of the blocks of code below to configure your Pi or BBB to use
        # software or hardware SPI.
        # Raspberry Pi software SPI configuration.
        #CLK = 25
        #CS  = 24
        #DO  = 18
        #sensor = MAX31855.MAX31855(CLK, CS, DO)
        # Raspberry Pi hardware SPI configuration.
        self.SPI_PORT   = 0
        self.SPI_DEVICE = 0
        self.sensor = MAX31855.MAX31855(spi=SPI.SpiDev(self.SPI_PORT, self.SPI_DEVICE))
        # BeagleBone Black software SPI configuration.
        #CLK = 'P9_12'
        #CS  = 'P9_15'
        #DO  = 'P9_23'
        #sensor = MAX31855.MAX31855(CLK, CS, DO)
        # BeagleBone Black hardware SPI configuration.
        #SPI_PORT   = 1
        #SPI_DEVICE = 0
        #sensor = MAX31855.MAX31855(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
            
        self.ts = self.getTempStream()
        self.outf = open('%s.xls' % outfname,'w')
        self.savepng = '%s.png' % outfname
        self.outf.write('Second\tTemperature\n')
        # set up a generator for PLOTSEC seconds of sampling
        style.use('ggplot')
        # prepopulate arrays to make updates quicker
        self.t = range(self.PLOTSEC+2)
        self.y = [None for i in self.t]
        self.fig, self.ax = plt.subplots()
        #self.ax.set_xlim(auto=True)
        #self.ax.set_ylim(auto=True)

        # fig.canvas.mpl_connect('key_press_event', press)
        self.line, = self.ax.plot(0,0,lw=1)
        self.text_template = 'Last temperature = %3.2f'
        self.title_template = 'Temperature strip chart at %d seconds'
        self.t_temp = self.ax.text(0.15,0.15,self.text_template%(0),
                                   transform=self.ax.transAxes, family='monospace',fontsize=10)
        #self.t_title = self.ax.text(0.5,1.0,self.title_template%(0),
        #                            transform=self.ax.transAxes, family='monospace',fontsize=20)
        self.started = time.time()
Example #17
0
    def __init__(self, parent, controller):
     
        ## tk.Frame 초기화
        tk.Frame.__init__(self, parent)
        
        style.use("ggplot")

        self.figure = pl.figure(1)
        self.a = self.figure.add_subplot(111)

        self.canvas = FigureCanvasTkAgg(self.figure, self)
        self.canvas.get_tk_widget().grid(sticky="news")
        self.canvas._tkcanvas.grid(sticky="news")
        
        ## Initialization
        self.som = MiniSom(10,10,136,sigma=1.0,learning_rate=0.5)
Example #18
0
def findhash():
    a=[]
    b=[]
    
    statistics=db.Tweets.aggregate([ {"$unwind": "$entities.hashtags"}, { "$group": { "_id": "$entities.hashtags.text", "tagCount": {"$sum": 1} }},{ "$sort": {"tagCount": -1 }}, { "$limit": 20 }])
    for s in statistics:
        a.append(s['_id'])
        b.append(s['tagCount'])


    style.use('ggplot')

    web_stats={'hashtag':a,'nombre':b}
    df=pd.DataFrame(web_stats)

    return df
Example #19
0
    def __init__(self, parent, data, ylabel):
        ttk.Frame.__init__(self, parent)
        style.use("ggplot")

        self.calcs = data
        self.ylabel = ylabel
        self.colourmaps = ["Reds", "Blues", "Greens",
                           "Purples", "Oranges", "Greys",
                           "copper", "summer", "bone"]
        self.lines = list()
        self.toolbar = None
        self.fig = plt.figure(figsize=(4, 4), dpi=75)
        self.ax1 = self.fig.add_subplot(1, 1, 1)
        self.plotcanvas = FigureCanvasTkAgg(self.fig, self)

        self.initiate_graph()
        self.update_plot(initiate=True)
Example #20
0
def test13():
    style.use('fivethirtyeight')
    fig = plt.figure()
    ax1 = fig.add_subplot(1,1,1)
    def animate(i):
        x = []
        y = []
        with open('data/example.csv', 'r') as file:
            for line in file:
                if line.strip():
                    t = line.split(';')
                    x.append(int(t[0]))
                    y.append(int(t[1]))
        ax1.clear()
        ax1.plot(x,y)
    ani = animation.FuncAnimation(fig, animate, interval=1000)
    plt.show()
Example #21
0
def plotter(x, y, x_fine, fit, fit_fine, lowerbound, upperbound,
            xlog=True, ylog=True, xlim=None, ylim=None,
            xlabel="Set your X-label!", ylabel="Set your y label!",
            title="Set your title!", file="temp.pdf", save=False):
    """Make plots pretty."""
    style.use('ggplot')

    plt.rcParams['font.size'] = 12
    plt.rcParams['axes.labelsize'] = 12
    plt.rcParams['xtick.labelsize'] = 12
    plt.rcParams['ytick.labelsize'] = 12

    plt.figure()

    # Only plot datapoints if I gave you datapoints
    if y is not None:
        plt.plot(x, y, marker='o', markersize=10, linestyle='None')

    # Plot a nice error shadow
    if lowerbound is not None:
        plt.fill_between(x.value, lowerbound.value, upperbound.value,
                         facecolor='gray', alpha=0.5)

    plt.plot(x, fit)
    plt.plot(x_fine, fit_fine, linestyle='--')

    # Fiddle with axes, etc.
    ax = plt.gca()

    if xlog:
        ax.set_xscale('log')
    if ylog:
        ax.set_yscale('log')

    if xlim is not None:
        ax.set_xlim(xlim)
    if ylim is not None:
        ax.set_ylim(ylim)

    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.title(title)

    # Show and save plots
    plt.draw()
def main():
    style.use('dark_background')

    config_file = sys.argv[1]
    with open(config_file) as conf:
        config = json.load(conf, object_hook=as_config)

    ser = serial.Serial()

    with open('/var/arduino_device', 'r') as device:
        ser.port = device.read().rstrip('\n')
    
    ser.baudrate = 9600
    
    ser.bytesize = serial.EIGHTBITS #number of bits per bytes
    
    ser.parity = serial.PARITY_NONE #set parity check: no parity
    
    ser.stopbits = serial.STOPBITS_ONE #number of stop bits
    
    #ser.timeout = None             #block read
    
    ser.timeout = 0                 #non-block read
    
    #ser.timeout = 2                  #timeout block read
    
    ser.xonxoff = False      #disable software flow control
    
    ser.rtscts = False      #disable hardware (RTS/CTS) flow control
    
    ser.dsrdtr = False         #disable hardware (DSR/DTR) flow control
    
    ser.writeTimeout = 2      #timeout for write
    
    print "serial port: "

    try: 
    
        ser.open()
    
    except Exception, e:
    
        print "error open serial port: " + str(e)
    
        exit()
def weatherforecast(city, country):

    apikey = '2ddda8352fab17f0c1b43254bc161dc6'
    #url_base = 'http://api.openweathermap.org/data/2.5/forecast/city?q=' + city.replace(' ', '%20') + ',' + country + '&APPID='
    url_base = 'http://api.openweathermap.org/data/2.5/forecast/daily?q=' + city.replace(' ', '%20') + ',' + country + '&cnt=16&APPID='
    url = url_base + apikey

    print url

    json_obj = urllib2.urlopen(url)
    data = json.load(json_obj)
    weather_data = data['list']
    t = []
    tmin = []
    tmax = []
    hum = []
    time = []

    for i in weather_data:
        t.append(float(i['temp']['day']) - 273.18)
        tmin.append(float(i['temp']['min']) - 273.18)
        tmax.append(float(i['temp']['max']) - 273.18)
        hum.append(float(i['humidity']))
        time.append(int(i['dt']))
    
    dateconv = np.vectorize(dt.datetime.fromtimestamp)
    time = dateconv(time)
    print time[:]
    style.use('ggplot')
    
    print t[0::9]
    
    ax1 = plt.subplot(1, 1, 1)
    ax1.plot_date(time, t, marker='*', color='k', linestyle='-')
    #ax1.plot_date(time, tmax, marker='^', color='r', linestyle='-')
    #ax1.plot_date(time, tmin, marker='o', color='b', linestyle='-')
    for label in ax1.xaxis.get_ticklabels():
        label.set_rotation(45)
    myFmt = mdates.DateFormatter('%d.%m.')
    ax1.xaxis.set_major_formatter(myFmt)
    
    plt.subplots_adjust(left=0.09, bottom=0.20, right=0.94, top=0.90, wspace=0.2, hspace=0)
    plt.title('Weatherforecast ' + data['city']['name'])
    plt.show()
Example #24
0
    def __init__(self):
        super(MainWindow, self).__init__()
        uic.loadUi("PeakInspector_layout.ui", self)
        self.setWindowTitle("PeakInspector (beta) (c) A.Salykin - Masaryk University - CC-BY-SA 4.0")

        # main variable:
        self.multiple_data_sets = pd.DataFrame()  # Initialise the final dataframe to export to Excel

        self.coordinates = []
        self.area = []
        self.amplitudes = []
        self.amplitude_line_coordinates = []
        self.left_peak_border = []
        self.right_peak_border = []
        self.pickable_artists_pts_AX2 = []
        self.pickable_artists_pts_AX3 = []
        self.pickable_artists_lns_AX3 = []
        self.pickable_artists_fill_AX3 = []
        self.pickable_artists_plb_AX3 = []
        self.pickable_artists_prb_AX3 = []
        self.pickable_artists_lnsP_AX3 = []

        self.left_border = []
        self.right_border = []

        # Connect buttons to class methods:
        self.BtnLoadFile.clicked.connect(self.load_file)
        self.BtnReplot.clicked.connect(self.replot_graph)
        self.chbxDotPickEnable.stateChanged.connect(self.dot_pick_enable)
        self.BtnSaveCurrent.clicked.connect(self.coordinates_analysis)
        self.BtnSaveFullDataset.clicked.connect(self.save_data)
        self.BoxMplPlotStyle.currentIndexChanged.connect(self.mpl_style_change)

        style.use(self.BoxMplPlotStyle.currentText())

        self.BtnLoadFile.setStyleSheet("background-color: #7CF2BD")
        self.BtnReplot.setStyleSheet("background-color: #FAF6F2")
        self.BtnSaveCurrent.setStyleSheet("background-color: #FAF6F2")
        self.BtnSaveFullDataset.setStyleSheet("background-color: #FAF6F2")

        # Initialise figure instance
        self.fig = plt.figure()
        self.show()
Example #25
0
def post_rc_actions(show_warning=True):
    try:
        from matplotlib import style

        if u"viscid-default" not in use_styles:
            use_styles.insert(0, u"viscid-default")

        for s in use_styles:
            try:
                style.use(s)
            except ValueError as e:
                logger.warn(str(e))
    except ImportError:
        if show_warning and use_styles:
            logger.warn("Upgrade to matplotlib >= 1.5.0 to use style sheets")

    matplotlib.rcParams.update(rc_params)
    for group, params in rc.items():
        matplotlib.rc(group, **params)
 def plotbutton(self, event):
     ## Standard Realtime data visualization
     style.use('ggplot')
     fig = plt.figure()
     ax1 = fig.add_subplot(1,1,1)
     fig.canvas.set_window_title('Realtime Data Plot')
     directory = self.txtDic.GetValue()
     filename = self.txtFil.GetValue()
     filedic = directory+'\\'+filename 
     ## Create a animate method for updating realtime data in the plot
     def animate(i):
         fid = open(filedic,'r')
         graph_data = fid.read()
         fid.close()
         lines = graph_data.split('\n')
         ## Initialize data reading in 2D-list, get the X-axis and Y-axis input from users
         xs = self.plotdict[self.XplotChoices[self.Xplot.GetCurrentSelection()]]
         ys = self.plotdict[self.YplotChoices[self.Yplot.GetCurrentSelection()]]
         dataread = [[],[],[],[],[],[],[],[],[],[]]
         ## Read data
         for line in lines:
             if len(line) > 1 and line[0:2] != "##":
                 Time,T_in,R,Rstd,Tstd_in,T_out,Tstd_out,Vsr850,T_set, T_stable= line.split(',')#,T_stable 
                 dataread[0].append(Time)
                 dataread[1].append(T_in)
                 dataread[2].append(R)
                 dataread[3].append(Rstd)
                 dataread[4].append(Tstd_in)
                 dataread[5].append(T_out)
                 dataread[6].append(Tstd_out)
                 dataread[7].append(Vsr850)
                 dataread[8].append(T_set)
                 dataread[9].append(T_stable)
         ## clear previous graph
         ax1.clear()
         ## plot data
         ax1.plot(dataread[xs], dataread[ys],'--o', lw = 0.5, ms = 5, mew =0 , c = [0.5,0.5,0.5],mfc = [0,0,1])
     ## Set graph title
     ax1.set_title(filedic.split('\\')[-1]) 
     ## animation
     ani = animation.FuncAnimation(fig, animate, interval=1000)  
     plt.show()
Example #27
0
def mathplot(clusters):
	""" Plot a graph with amount of tweets on the Y-axis and time on the X-axis """
	style.use('ggplot')

	x = []
	y = []
	for times, tweets in sorted(clusters.items()):
		oldtime = times
		minute, second = times.split('.')		
		second = float(second) / 60 * 100
		newtime = float(minute) + second / 100
		x.append(newtime)
		y.append(len(tweets))

	plt.plot(x,y)

	plt.title('Aantal tweets x Tijd')
	plt.ylabel('Aantal tweets')
	plt.xlabel('Tijd')

	plt.show()
Example #28
0
def visualise_by_race(data):
    """Visualise the stop and search by officer-reported race.

    Parameters
    ----------
    data : list
        The parsed data in JSON-like format.
    """
    counter = Counter(row.get('Officer-defined ethnicity') for row in data)
    race_to_search = OrderedDict(sorted(counter.items(), key=lambda t: t[1]))

    races = tuple('Unspecified' if not key else key
                  for key in race_to_search.keys())
    num_of_searches = tuple(race_to_search.values())

    style.use('ggplot')
    pos = np.arange(len(num_of_searches))
    plt.bar(pos, num_of_searches, align='center', color='#231F20')
    plt.xticks(pos, races)
    plt.title('Stop and Search by Race')
    plt.ylabel('Number of stop and searches')
    plt.xlabel('Officer-defined Race')
    plt.show()
Example #29
0
#-*-encoding:utf8-*-
#  annotation last price in edge of matplolib
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
from mpl_finance import candlestick_ochl
from matplotlib import style

style.use('classic')


def bytespdate2num(fmt, encoding='utf-8'):
    strconverter = mdates.strpdate2num(fmt)

    def bytesconverter(b):
        s = b.decode(encoding)
        return strconverter(s)

    return bytesconverter


with open('tsla.csv', 'r') as csvfile:
    fig = plt.figure('figure one')
    ax1 = plt.subplot2grid((1, 1), (0, 0))
    ax1.grid(True, color='g', linestyle='-', linewidth=0.1)

    source_code = csvfile.read()
    stock_data = []
    split_source = source_code.split('\n')
# %%
# %load_ext autoreload
# %autoreload 2

import os, sys
import re
import pprint
import pandas as pd

from sys import platform as sys_pf
import matplotlib
matplotlib.use("TkAgg")
from matplotlib import pyplot as plt
from matplotlib import style as styl
styl.use('default')

from core.fileop import DirCheck, ListFiles, GetPendingList, GetGrpFLs


# Functions Section Begins ----------------------------------------------------- #

# Functions Section Ends ----------------------------------------------------- #

# %%
# parameter
'''
path = '/Volumes/LaCie_DataStorage/xiaochao_wei_STORM imaging/STORM_imaging'
analysis_dir = 'analysis_20190419'
analysis_subdir = 'spacial_test'
ip_dir = 'spacialdata'
nchannel = 2
"""
Created on Sat Apr 04 13:49:38 2015

@author: CHANDRA DEO MAHTO
"""

import pandas as pd
import os
import time
from datetime import datetime

from time import mktime
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import style
style.use("dark_background")

import re


path = "D:/intraQuarter/intraQuarter"

def Key_Stats(gather=["Total Debt/Equity",
                      'Trailing P/E',
                      'Price/Sales',
                      'Price/Book',
                      'Profit Margin',
                      'Operating Margin',
                      'Return on Assets',
                      'Return on Equity',
                      'Revenue Per Share',
import pandas as pd
import datetime
import pandas_datareader.data as web
from pandas import Series, DataFrame
import sys

import matplotlib.pyplot as plt  #importing matplotlib
import matplotlib as mpl
from matplotlib import style

pd.set_option('display.max_rows', None)  #show all the rows "None" is no limit
plt.rcParams["figure.figsize"] = (8, 7)  #adjusting size of matblotlib
style.use('ggplot')  #adjusting the style, possible to use different styles

start = datetime.datetime(2019, 1, 1)
end = datetime.datetime(2021, 1, 31)

stock_data = web.DataReader(
    'AAPL', 'yahoo', start,
    end)  #possible to use google etc and other e.g. eurostat
stock_data.tail()

close_px = stock_data['Adj Close']  #get the close_px
moving_avarage = close_px.rolling(window=100).mean()  #rolling the close_px
moving_avarage

#plotting using matplotlib
close_px.plot(label='AAPL')
moving_avarage.plot(label='Moving avg')
plt.legend()
#https://m.blog.naver.com/samsjang/220967436415
#only for irisi example

from sklearn import datasets
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score
from sklearn.svm import SVC
import numpy as np
from matplotlib import style
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.colors import ListedColormap


style.use('seaborn-talk')


krfont={'family': 'NanumGothic', 'weight':'bold', 'size':10}
matplotlib.rc('font', **krfont)
matplotlib.rcParams['axes.unicode_minus'] = False

def plot_decision_region(x,y,classifier, test_idx=None, resolution=0.2, title=''):
    markers = ('s', 'x', 'o', '^', 'v') #shape of dots
    colors = ('r', 'b', 'lightgreen', 'gray', 'cyan')
    cmap = ListedColormap(colors[:len(np.unique(y))])
     # x = np.array([10, 10, 20, 20, 30, 30])
     #(np.unique(x))
     #[10 20 30] 
     
     #draw decision surface
Example #34
0
import ttk
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import matplotlib.animation as animation
from matplotlib import style
import matplotlib.pyplot as plt
import time
import random
from collections import deque
import numpy as np
import serial

LARGE_FONT= ("Verdana", 40)
style.use("seaborn-bright")
f = Figure(figsize=(10,6), dpi=100)
a = f.add_subplot(111)
xList1 = deque([0] * 15, maxlen=15)
yList1 = deque([0] * 15, maxlen=15)
xList2 = deque([0] * 15, maxlen=15)
yList2 = deque([0] * 15, maxlen=15)
xList3 = deque([0] * 15, maxlen=15)
yList3 = deque([0] * 15, maxlen=15)
start_time=time.time()
ser = serial.Serial('/dev/tty.usbmodem1562971', 115200)  # open serial port

'Main function to refresh the graph with new points'
def animate(i):

    d=0
Example #35
0
    def view(self, *args, backend='matplotlib', fig_title='Print Path',
             color_in_time=True, cmap='jet', give=False, plot_style='default',**kwargs):
        
        '''
        Parameters:
        

        > BACKEND: str (default: 'matplotlib')
            The plotting backend to use, one of 'matplotlib' or 'mayavi'.
            
        > *args,**kwargs : are passed to matplotlib's pyplot.plot function
        
        > FIG_TITLE: the title given to the figure. Only used is a figure is not given to plot on
        
        > GIVE : this command makes the method return the figure after the path data is
                plotted. This has no effect when mayavi is the backend.
        '''

        # checking backend input and force matplotlib if there is a mistake
        if backend != 'matplotlib' and backend != 'mayavi':

            # create warning message
            warn = 'Incorrect backend ({}) given \nMust be either matplotlib or mayavi \nDefaulting to matplotlib'.format(backend)

            # reassinging backend
            backend = 'matplotlib'

            # raising warning and continuing
            raise Warning(warn)
        
        
        if backend == 'matplotlib':

            # using time to color the line representing printer motion
            # help from https://matplotlib.org/gallery/lines_bars_and_markers/multicolored_line.html
            if color_in_time:
                from mpl_toolkits.mplot3d import Axes3D
                import matplotlib.pyplot as plt
                from matplotlib import style

                # setting matplotlib plot style
                style.use(plot_style)
                
                # creating figure
                fig = plt.figure()
                ax = fig.gca(projection='3d')
                ax.set_aspect('equal')

                # getting motion history
                X = self.history[:, 0]
                Y = self.history[:, 1]
                Z = self.history[:, 2]

                # creating the color scheme to parametricise this plot in time
                # Create a continuous norm to map from data points to colors
                norm = plt.Normalize(0,self.t[-1])
                

                # creating CM object that contains the method to get colors in the map
                color_map = plt.cm.ScalarMappable(norm, cmap)

                # creating array of RGBA colors to pass when plotting
                colors = color_map.to_rgba(self.t.data())

                # adding colorbar to figure
                color_map.set_array(self.t.data()) # trick to make this work from:
                # https://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots

                # actually adding color bar with 3 tick marks
                colorbar = fig.colorbar(color_map, pad=0.09,
                                        ticks=[0,self.t[-1]/2,self.t[-1]])

                # adding tick labels to color bar
                colorbar.ax.set_yticklabels(['0','{:0.2f}'.format(self.t[-1]/2),
                                             '{:0.2f}'.format(self.t[-1])])
                

                # setting label of color bar
                colorbar.set_label('Time (min)')
                
                # Plots the 3 past printer positions on figure parameterized by time
                for i in range(1,len(X)):
                    ax.plot(X[i-1:i+1], Y[i-1:i+1], Z[i-1:i+1], *args,
                            color=colors[i,:], **kwargs)
                
                
                # Keeps aspect ratio square
                # http://stackoverflow.com/questions/13685386
                max_range = np.array([X.max()-X.min(),
                                      Y.max()-Y.min(),
                                      Z.max()-Z.min()]).max() / 2.0

                mean_x = X.mean()
                mean_y = Y.mean()
                mean_z = Z.mean()
                ax.set_xlim(mean_x - max_range, mean_x + max_range)
                ax.set_ylim(mean_y - max_range, mean_y + max_range)
                ax.set_zlim(mean_z - max_range, mean_z + max_range)

                # labeling figure axes and title
                ax.set_xlabel('X ({})'.format(self.unit_sys))
                ax.set_ylabel('Y ({})'.format(self.unit_sys))
                ax.set_zlabel('Z ({})'.format(self.unit_sys))
                plt.title(fig_title)


                # determines whether to show the figure or to return it
                if give:
                    return ax
                else:
                    # showing figure
                    plt.show()

                # end of view
                return


            else:
                from mpl_toolkits.mplot3d import Axes3D
                import matplotlib.pyplot as plt

                # creating figure
                fig = plt.figure()
                ax = fig.gca(projection='3d')
                ax.set_aspect('equal')

                # getting motion history
                X = self.history[:, 0]
                Y = self.history[:, 1]
                Z = self.history[:, 2]

                # To Do add optional label to the first point
                # Plots the 3 past printer positions on figure
                ax.plot(X, Y, Z, *args, **kwargs)

                # Keeps aspect ratio square
                # http://stackoverflow.com/questions/13685386
                max_range = np.array([X.max()-X.min(),
                                      Y.max()-Y.min(),
                                      Z.max()-Z.min()]).max() / 2.0

                mean_x = X.mean()
                mean_y = Y.mean()
                mean_z = Z.mean()
                ax.set_xlim(mean_x - max_range, mean_x + max_range)
                ax.set_ylim(mean_y - max_range, mean_y + max_range)
                ax.set_zlim(mean_z - max_range, mean_z + max_range)

                # labeling figure axes and title
                ax.set_xlabel('X ({})'.format(self.unit_sys))
                ax.set_ylabel('Y ({})'.format(self.unit_sys))
                ax.set_zlabel('Z ({})'.format(self.unit_sys))
                plt.title(fig_title)


                # determines whether to show the figure or to return it
                if give:
                    return ax
                else:
                    # showing figure
                    plt.show()

                # end of view
                return
            
        # mayavi 
        elif backend == 'mayavi':
            from mayavi import mlab

            # plotting the time series
            mlab.plot3d(self.history[:, 0],
                        self.history[:, 1],
                        self.history[:, 2],
                        *args, **kwargs)

            # labeling axes and title
            mlab.xlabel('X ({})'.format(self.unit_sys))
            mlab.ylabel('Y ({})'.format(self.unit_sys))
            mlab.zlabel('Z ({})'.format(self.unit_sys))
            mlab.title(title)

            # end of view
            return
Example #36
0
    def live_view(self, *args, save_file=None, writer='pillow',refresh=100,
                  plot_style='default',show=True,**kwargs):

        '''
        Parameters:

        > SAVE_FILE:
        > ANIMATE:
        > COLOR:
        > REFRESH:
        > PLOT_STYLE:
        '''

        # need imports
        import matplotlib.animation as animation
        from mpl_toolkits.mplot3d import Axes3D
        import matplotlib.pyplot as plt
        from matplotlib import style
        
        # maplotlib style to use
        style.use(plot_style)

        # creating new figure to plot on
        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')
        ax.set_aspect('equal')

        
        # getting motion history
        X = self.history[:, 0]
        Y = self.history[:, 1]
        Z = self.history[:, 2]

        # Keeps aspect ratio square
        # http://stackoverflow.com/questions/13685386
        max_range = np.array([X.max()-X.min(),
                              Y.max()-Y.min(),
                              Z.max()-Z.min()]).max() / 2.0

        mean_x = X.mean()
        mean_y = Y.mean()
        mean_z = Z.mean()
        xlim = (mean_x - max_range, mean_x + max_range)
        ylim = (mean_y - max_range, mean_y + max_range)
        zlim = (mean_z - max_range, mean_z + max_range)

        # labeling figure axes and title
        xlab = 'X ({})'.format(self.unit_sys)
        ylab = 'Y ({})'.format(self.unit_sys)
        zlab = 'Z ({})'.format(self.unit_sys)

        # creates the animation
        def animate_loop(i):

            # Makes loop cycle so that it restarts after it's full length is reached
            i = i % (self.count - 1)

            # calls the animate function
            x = self.history[0:i,0]
            y = self.history[0:i,1]
            z = self.history[0:i,2]
            
            # cleans old drawing off screen. computationally light
            ax.clear()
            
            # redraws stuff on to plot
            ax.plot(x,y,z, *args,**kwargs)

            # setting axis sizes
            ax.set_xlim(xlim[0], xlim[1])
            ax.set_ylim(ylim[0], ylim[1])
            ax.set_zlim(zlim[0], zlim[1])

            # labeling axes
            ax.set_xlabel(xlab)
            ax.set_ylabel(ylab)
            ax.set_zlabel(zlab)
            

        # animation function from matplotlib
        # arguments are where to draw, which drawing function to use, and how often to redraw
        ani = animation.FuncAnimation(fig, animate_loop, interval=refresh)

        # if a save file is passed, the animation is saved to the file
        if save_file:
            ani.save(save_file, writer=writer) # saves to an mp4 file
            

        # calling figure to screen
        if show:
            plt.show()

        # end of the live_view method
        return
Example #37
0

# In[11]:

plt.plot(lista, listb, linewidth=2, color ='r', label='actual' )
plt.plot(listc, listd, linewidth=2, color ='g', label = 'expected' )
plt.legend()
plt.show()


# In[12]:

from matplotlib import pyplot as plt
from matplotlib import style

style.use('ggplot')

lista = [6, 9, 11]
listb = [11, 15, 7]

listc = [6, 10, 13]
listd = [6, 16, 8]
plt.plot(lista, listb, linewidth=2, color ='r', label='actual' )
plt.plot(listc, listd, linewidth=2, color ='g', label = 'expected' )
plt.legend()
plt.show()


# In[15]:

from matplotlib import pyplot as plt
Example #38
0
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib import style
style.use('Solarize_Light2')
from math import sqrt
import random
import copy

# Project source files
import plotah
import calc
import hage

GRID_X = 18
GRID_Y = 16

GRID_X_POINTS = 10
GRID_Y_POINTS = 10

def random_walk(ah, buildings, random_walks):

	bad_yield = 50000
	scores = []
	top_scores = []
	bad_scores = []
	top_yield = 0
	top_buildings = {}
	top_free_distance = {}
   
	# Random statespace eploration
	for run in range(0, random_walks):
from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
import random

style.use('fivethirtyeight')

#xs = [1, 2, 3, 4, 5, 6]
#ys = [5, 4, 6, 4, 5, 7]

# plt.plot(xs, ys)
# plt.scatter(xs, ys)
# plt.show()

#xs = np.array([1, 2, 3, 4, 5, 6], dtype = np.float64)
#ys = np.array([5, 4, 6, 5, 6, 7], dtype = np.float64)


def create_dataset(number_of_datapoint, variance, step=2, correlation=False):
    val = 1
    ys = []
    for i in range(number_of_datapoint):
        y = val + random.randrange(-variance, variance)
        ys.append(y)
        if correlation and correlation == 'pos':
            val += step
        elif correlation and correlation == 'neg':
            val -= step
    xs = [i
          for i in range(len(ys))]  # we can give the len(number_of_datapoint)
import matplotlib as mpl
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import string
from matplotlib import colors
import time
from scipy.integrate import odeint
from scipy.interpolate import spline
import pandas as pd
import csv
from matplotlib import style
#style.use('ggplot')
style.use('seaborn')


df = pd.read_csv('"add the directory and the name of the csv file".csv')
df.replace('DEAD', 1e-04, inplace=True)
#df['%foram'].values[df['%foram'].values > 1e+00] = 1e+00
df['%foram'].values[df['%foram'].values < 1e-04] = 1e-04
df['%foram'] = df['%foram'].astype(float)
# setup the plot
#fig, ax = plt.subplots(3,3, figsize=(6,6))
## sharex='col', sharey='row' are used to premoved inner labels on the grid to make the plot cleaner.
x =np.zeros((3,3)) 
fig, x = plt.subplots(3,3, sharex='col', sharey='row', figsize=(12,12))

### adjust the space between the plots
fig.subplots_adjust(hspace=0.2, wspace=0.2)
tree_leaf_50.fit(X_train, y_train)

print('Training Score', tree_leaf_50.score(X_train, y_train).round(4))
print('Testing Score:', tree_leaf_50.score(X_test, y_test).round(4))


# Defining a function to visualize feature importance
def plot_feature_importances(model, train=X_train, export=False):
    fig, ax = plt.subplots(figsize=(12, 9))
    n_features = X_train.shape[1]
    plt.barh(range(n_features), model.feature_importances_, align='center')
    plt.yticks(pd.np.arange(n_features), train.columns)
    plt.xlabel("Feature importance")
    plt.ylabel("Feature")


plot_feature_importances(tree_leaf_50, train=X_train, export=True)
plt.show()

plot_feature_importances(tree_full, train=X_train, export=False)
plt.show()

# Residual Plot

style.use('bmh')
plt.scatter(lr_bw_pred, y_test - lr_bw_pred)
plt.show()

############################################################################
import math, datetime
import pandas as pd
import quandl as q
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
from sklearn import preprocessing, cross_validation, svm
from sklearn.linear_model import LinearRegression

style.use("ggplot")
q.ApiConfig.api_key = "u7U8X8jZ_QfZfVv7HZBx"

df = q.get('NSE/TCS')

df = df[['Open', 'High', 'Low', 'Close', 'Total Trade Quantity']]
df['HL_PCT'] = (df['High'] - df['Close']) / df['Close'] * 100
df['PCT_change'] = (df['Close'] - df['Open']) / df['Open'] * 100

df = df[['Close', 'HL_PCT', 'PCT_change', 'Total Trade Quantity']]

forecast_col = 'Close'
df.fillna(-99999, inplace=True)

forecast_out = int(math.ceil(0.01 * len(df)))
print(forecast_out)

df['label'] = df[forecast_col].shift(-forecast_out)

X = np.array(df.drop(['label'], 1))
X = preprocessing.scale(X)
X = X[:-forecast_out]
Example #43
0
import pandas as pd
import os
import time
from datetime import datetime

from time import mktime
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import style
style.use("dark_background")
import re

path = "C:/Users/Aashish/Documents/Work/Pepr/Machine Learning Tut/Sentdex SciKit Tut/intraQuarter (1)/intraQuarter"


def key_stats(gather=[
    "Total Debt/Equity", 'Trailing P/E', 'Price/Sales', 'Price/Book',
    'Profit Margin', 'Operating Margin', 'Return on Assets',
    'Return on Equity', 'Revenue Per Share', 'Market Cap', 'Enterprise Value',
    'Forward P/E', 'PEG Ratio', 'Enterprise Value/Revenue',
    'Enterprise Value/EBITDA', 'Revenue', 'Gross Profit', 'EBITDA',
    'Net Income Avl to Common ', 'Diluted EPS', 'Earnings Growth',
    'Revenue Growth', 'Total Cash', 'Total Cash Per Share', 'Total Debt',
    'Current Ratio', 'Book Value Per Share', 'Cash Flow', 'Beta',
    'Held by Insiders', 'Held by Institutions', 'Shares Short (as of',
    'Short Ratio', 'Short % of Float', 'Shares Short (prior month)'
]):

    statspath = path + '/_KeyStats'
    stock_list = [X[0] for X in os.walk(statspath)]
Example #44
0
import pandas as pd
from matplotlib import style
import datetime
import pandas.io.data as web
import matplotlib.pyplot as plt



style.use('fivethirtyeight')


#function to use in rolling_apply
def mine(data):
    return max(data)
    
    

#setting dates
start=datetime.datetime(2015,1,1)
end=datetime.datetime(2015,12,31)

#connecting to yahoo api
att=web.DataReader('gmc','yahoo',start,end)

#manipulations
att['Open']=att['Open']/100
att['Check']=att['Close']>att['Open']
att['bool']=att['Check']
#print(att[(att['Close']>att['Open'])])

#print(att.head())
Example #45
0
# Logistic Regression from scratch. Building model as Object instead of separate functions

# Importing core libraries
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use('seaborn-whitegrid')

np.random.seed(42)

# Features and Labels
class0_vals = np.hstack( (20 + np.random.randn(100,1), 22 + np.random.rand(100,1)) )
class1_vals = np.hstack( (20.5 + np.random.randn(100,1), 20.63 + np.random.rand(100,1)) )

X = np.vstack( (class0_vals, class1_vals) )
X = np.c_[ np.ones(X.shape[0]), X ]

y = np.array([0.0 if X[i, 1:] in class0_vals else 1.0 for i in range(X.shape[0])])

'''
class0_xvals = (8 + np.random.rand(50)).reshape(-1,1)
class1_xvals = (9 + np.random.rand(50)).reshape(-1,1)

class0_yvals = (8.9 + np.random.randn(50)).reshape(-1,1)
class1_yvals = (3.92 + np.random.randn(50)).reshape(-1,1)

X = np.c_[ np.vstack((class0_xvals, class1_xvals)), np.vstack((class0_yvals, class1_yvals)) ]
X = np.c_[ np.ones(X.shape[0]), X ]

y = np.array([0.0 if val in class0_xvals else 1.0 for val in X])
'''