コード例 #1
0
ファイル: sentdebot.py プロジェクト: NikhilOO7/sentdebot
async def user_metrics_background_task():
    await client.wait_until_ready()
    global sentdex_guild
    sentdex_guild = client.get_guild(405403391410438165)

    while not client.is_closed():
        try:
            online, idle, offline = community_report(sentdex_guild)
            with open(f"{path}/usermetrics.csv", "a") as f:
                f.write(f"{int(time.time())},{online},{idle},{offline}\n")

            df_msgs = pd.read_csv(f'{path}/msgs.csv',
                                  names=['time', 'uid', 'channel'])
            df_msgs = df_msgs[(df_msgs['time'] > time.time() -
                               (86400 * DAYS_BACK))]
            df_msgs['count'] = 1
            df_msgs['date'] = pd.to_datetime(df_msgs['time'], unit='s')
            df_msgs.drop("time", 1, inplace=True)
            df_msgs.set_index("date", inplace=True)

            df_no_dup = df_msgs.copy()
            df_no_dup['uid2'] = df_no_dup['uid'].shift(-1)
            df_no_dup['uid_rm_dups'] = list(
                map(df_match, df_no_dup['uid'], df_no_dup['uid2']))

            df_no_dup.dropna(inplace=True)

            message_volume = df_msgs["count"].resample(RESAMPLE).sum()

            user_id_counts_overall = Counter(
                df_no_dup[df_no_dup['channel'].isin(COMMUNITY_BASED_CHANNELS)]
                ['uid'].values).most_common(MOST_COMMON_INT)
            #print(user_id_counts_overall)

            uids_in_help = Counter(df_no_dup[df_no_dup['channel'].isin(
                HELP_CHANNELS)]['uid'].values).most_common(MOST_COMMON_INT)
            #print(uids_in_help)

            df = pd.read_csv(f"{path}/usermetrics.csv",
                             names=['time', 'online', 'idle', 'offline'])
            df = df[(df['time'] > time.time() - (86400 * DAYS_BACK))]
            df['date'] = pd.to_datetime(df['time'], unit='s')
            df['total'] = df['online'] + df['offline'] + df['idle']
            df.drop("time", 1, inplace=True)
            df.set_index("date", inplace=True)

            df = df.resample(RESAMPLE).mean()
            df = df.join(message_volume)

            df.dropna(inplace=True)
            #print(df.head())

            fig = plt.figure(facecolor=DISCORD_BG_COLOR)
            ax1 = plt.subplot2grid((2, 1), (0, 0))
            plt.ylabel("Active Users")
            plt.title("Community Report")
            ax1.set_facecolor(DISCORD_BG_COLOR)
            ax1v = ax1.twinx()
            plt.ylabel("Message Volume")
            #ax1v.set_facecolor(DISCORD_BG_COLOR)
            ax2 = plt.subplot2grid((2, 1), (1, 0))
            plt.ylabel("Total Users")
            ax2.set_facecolor(DISCORD_BG_COLOR)

            ax1.plot(df.index, df.online, label="Active Users\n(Not Idle)")
            #ax1v.bar(df.index, df["count"], width=0.01)

            ax1v.fill_between(df.index,
                              0,
                              df["count"],
                              facecolor="w",
                              alpha=0.2,
                              label="Message Volume")
            ax1.legend(loc=2)
            ax1v.legend(loc=9)

            ax2.plot(df.index, df.total, label="Total Users")
            ax2.xaxis.set_major_formatter(
                mdates.DateFormatter('%Y-%m-%d\n%H:%M'))

            #for label in ax2.xaxis.get_ticklabels():
            #        label.set_rotation(45)
            ax2.xaxis.set_major_locator(
                mticker.MaxNLocator(nbins=5, prune='lower'))
            ax2.legend()

            plt.subplots_adjust(left=0.11,
                                bottom=0.10,
                                right=0.89,
                                top=0.95,
                                wspace=0.2,
                                hspace=0)
            ax1.get_xaxis().set_visible(False)

            ax1v.set_ylim(0, 3 * df["count"].values.max())

            #plt.show()
            plt.savefig(f"{path}/online.png", facecolor=fig.get_facecolor())
            plt.clf()

            fig = plt.figure(facecolor=DISCORD_BG_COLOR)
            ax1 = plt.subplot2grid((2, 1), (0, 0))

            plt.xlabel("Message Volume")
            plt.title(f"General User Activity (past {DAYS_BACK} days)")
            ax1.set_facecolor(DISCORD_BG_COLOR)

            users = []
            msgs = []
            for pair in user_id_counts_overall[::-1]:
                try:
                    users.append(sentdex_guild.get_member(
                        pair[0]).name)  # get member name from here

                    # Example for trolling people who spam messages for rank. Not the cleanest, but it works :)
                    if "Dhanos" in sentdex_guild.get_member(pair[0]).name:
                        msgs.append(pair[1] / 1.0)
                    else:
                        msgs.append(pair[1])
                except Exception as e:
                    print(str(e))
            y_pos = np.arange(len(users))
            ax1.barh(y_pos, msgs, align='center', alpha=0.5)
            plt.yticks(y_pos, users)

            ax2 = plt.subplot2grid((2, 1), (1, 0))
            plt.title(f"Help Channel Activity (past {DAYS_BACK} days)")
            plt.xlabel("Help Channel\nMsg Volume")
            ax2.set_facecolor(DISCORD_BG_COLOR)

            users = []
            msgs = []
            for pair in uids_in_help[::-1]:
                try:
                    users.append(sentdex_guild.get_member(
                        pair[0]).name)  # get member name from here

                    if "Dhanos" in sentdex_guild.get_member(pair[0]).name:
                        msgs.append(pair[1] / 1.0)
                    else:
                        msgs.append(pair[1])
                    #users.append(pair[0])
                except Exception as e:
                    print(str(e))

            y_pos = np.arange(len(users))
            ax2.barh(y_pos, msgs, align='center', alpha=0.5)
            plt.yticks(y_pos, users)

            plt.subplots_adjust(left=0.30,
                                bottom=0.15,
                                right=0.99,
                                top=0.95,
                                wspace=0.2,
                                hspace=0.55)
            plt.savefig(f"{path}/activity.png", facecolor=fig.get_facecolor())
            plt.clf()

            await asyncio.sleep(300)

        except Exception as e:
            print(str(e))
            await asyncio.sleep(300)
コード例 #2
0
                                   and side == 'long'):
        earnings = close / trade_price if side == 'long' else trade_price / close
        btc_amount *= earnings * (1 - market_rate)
        side = row['signal']
        trade_price = row['close']
        btc_amount *= (1 - market_rate)
    elif (row['signal'] == 'close_long'
          and side == 'long') or (row['signal'] == 'close_short'
                                  and side == 'short'):
        earnings = close / trade_price if side == 'long' else trade_price / close
        btc_amount *= earnings * (1 - market_rate)
        side = 'wait'
        trade_price = 0

df['assets'] = np.array(btc_amounts)
ax = df[['close', 'assets']].plot(figsize=(20, 10),
                                  grid=True,
                                  xticks=df.index,
                                  rot=90,
                                  subplots=True,
                                  style='b')
interval = int(len(df) / (40 - 1))
# 设置x轴刻度数量
ax[0].xaxis.set_major_locator(ticker.MaxNLocator(40))
# 以date为x轴刻度
ax[0].set_xticklabels(df.index[::interval])
# 美观x轴刻度
plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
ax[0].set_title(filename + ' BOLL策略回测')
plt.show()
コード例 #3
0
    def __init__(self,
                 wavelength,
                 n_radial,
                 z0=None,
                 callback=None,
                 pars={},
                 parent=None):
        super().__init__(parent=parent)
        self.log = logging.getLogger(self.__class__.__name__)

        self.pars = {**deepcopy(self.def_pars), **deepcopy(pars)}
        self.units = 'rad'
        self.status = None
        self.mul = 1.0
        self.figphi = None
        self.ax = None
        self.im = None
        self.cb = None
        self.shape = (128, 128)
        self.P = 1

        self.rzern = RZern(n_radial)
        dd = np.linspace(-1, 1, self.shape[0])
        xv, yv = np.meshgrid(dd, dd)
        self.rzern.make_cart_grid(xv, yv)
        self.rad_to_nm = wavelength / (2 * np.pi)
        self.callback = callback
        self.zernike_rows = []

        if z0 is None:
            self.z = np.zeros(self.rzern.nk)
        else:
            self.z = z0.copy()
        assert (self.rzern.nk == self.z.size)

        group_phase = QGroupBox('phase')
        lay_phase = QGridLayout()
        group_phase.setLayout(lay_phase)
        self.figphi = FigureCanvas(Figure(figsize=(2, 2)))
        self.ax = self.figphi.figure.add_subplot(1, 1, 1)
        phi = self.rzern.matrix(self.rzern.eval_grid(np.dot(self.P, self.z)))
        self.im = self.ax.imshow(phi, origin='lower')
        self.cb = self.figphi.figure.colorbar(self.im)
        self.cb.locator = ticker.MaxNLocator(nbins=5)
        self.cb.update_ticks()
        self.ax.axis('off')
        self.status = QLabel('')
        lay_phase.addWidget(self.figphi, 0, 0)
        lay_phase.addWidget(self.status, 1, 0)

        def nmodes():
            return min(self.pars['shown_modes'], self.rzern.nk)

        bot = QGroupBox('Zernike')
        lay_zern = QGridLayout()
        bot.setLayout(lay_zern)
        labzm = QLabel('shown modes')
        lezm = QLineEdit(str(nmodes()))
        lezm.setMaximumWidth(50)
        lezmval = MyQIntValidator(1, self.rzern.nk)
        lezmval.setFixup(nmodes())
        lezm.setValidator(lezmval)

        brad = QCheckBox('rad')
        brad.setChecked(True)
        breset = QPushButton('reset')
        lay_zern.addWidget(labzm, 0, 0)
        lay_zern.addWidget(lezm, 0, 1)
        lay_zern.addWidget(brad, 0, 2)
        lay_zern.addWidget(breset, 0, 3)

        scroll = QScrollArea()
        lay_zern.addWidget(scroll, 1, 0, 1, 5)
        scroll.setWidget(QWidget())
        scrollLayout = QGridLayout(scroll.widget())
        scroll.setWidgetResizable(True)

        def make_hand_slider(ind):
            def f(r):
                self.z[ind] = r
                self.update_phi_plot()

            return f

        def make_hand_lab(le, i):
            def f():
                self.pars['zernike_labels'][str(i)] = le.text()

            return f

        def default_zernike_name(i, n, m):
            if i == 1:
                return 'piston'
            elif i == 2:
                return 'tip'
            elif i == 3:
                return 'tilt'
            elif i == 4:
                return 'defocus'
            elif m == 0:
                return 'spherical'
            elif abs(m) == 1:
                return 'coma'
            elif abs(m) == 2:
                return 'astigmatism'
            elif abs(m) == 3:
                return 'trefoil'
            elif abs(m) == 4:
                return 'quadrafoil'
            elif abs(m) == 5:
                return 'pentafoil'
            else:
                return ''

        def make_update_zernike_rows():
            def f(mynk=None):
                if mynk is None:
                    mynk = len(self.zernike_rows)
                ntab = self.rzern.ntab
                mtab = self.rzern.mtab
                if len(self.zernike_rows) < mynk:
                    for i in range(len(self.zernike_rows), mynk):
                        lab = QLabel(
                            f'Z<sub>{i + 1}</sub> ' +
                            f'Z<sub>{ntab[i]}</sub><sup>{mtab[i]}</sup>')
                        slider = RelSlider(self.z[i], make_hand_slider(i))

                        if str(i) in self.pars['zernike_labels'].keys():
                            zname = self.pars['zernike_labels'][str(i)]
                        else:
                            zname = default_zernike_name(
                                i + 1, ntab[i], mtab[i])
                            self.pars['zernike_labels'][str(i)] = zname
                        lbn = QLineEdit(zname)
                        lbn.setMaximumWidth(120)
                        hand_lab = make_hand_lab(lbn, i)
                        lbn.editingFinished.connect(hand_lab)

                        scrollLayout.addWidget(lab, i, 0)
                        scrollLayout.addWidget(lbn, i, 1)
                        slider.add_to_layout(scrollLayout, i, 2)

                        self.zernike_rows.append((lab, slider, lbn, hand_lab))

                    assert (len(self.zernike_rows) == mynk)

                elif len(self.zernike_rows) > mynk:
                    for i in range(len(self.zernike_rows) - 1, mynk - 1, -1):
                        lab, slider, lbn, hand_lab = self.zernike_rows.pop()

                        scrollLayout.removeWidget(lab)
                        slider.remove_from_layout(scrollLayout)
                        scrollLayout.removeWidget(lbn)

                        lbn.editingFinished.disconnect(hand_lab)
                        lab.setParent(None)
                        lbn.setParent(None)

                    assert (len(self.zernike_rows) == mynk)

            return f

        self.update_zernike_rows = make_update_zernike_rows()

        def reset_fun():
            self.z *= 0.
            self.update_gui_controls()
            self.update_phi_plot()

        def change_nmodes():
            try:
                ival = int(lezm.text())
                assert (ival > 0)
                assert (ival <= self.rzern.nk)
            except Exception:
                lezm.setText(str(len(self.zernike_rows)))
                return

            if ival != len(self.zernike_rows):
                self.update_zernike_rows(ival)
                self.update_phi_plot()
                lezm.setText(str(len(self.zernike_rows)))

        def f2():
            def f(b):
                if b:
                    self.units = 'rad'
                    self.mul = 1.0
                else:
                    self.units = 'nm'
                    self.mul = self.rad_to_nm
                self.update_phi_plot()

            return f

        self.update_zernike_rows(nmodes())

        brad.stateChanged.connect(f2())
        breset.clicked.connect(reset_fun)
        lezm.editingFinished.connect(change_nmodes)

        splitv = QSplitter(Qt.Vertical)
        top = QSplitter(Qt.Horizontal)
        top.addWidget(group_phase)
        splitv.addWidget(top)
        splitv.addWidget(bot)
        self.top = top
        self.bot = bot
        l1 = QGridLayout()
        l1.addWidget(splitv)
        self.setLayout(l1)
        self.lezm = lezm
コード例 #4
0
def animate(i):
    global refreshRate
    global counter

    if chartLoad:
        if paneCount == 1:
            if dataPace == "tick":
                try:
                    if exchange == "BTC-e":
                        a = plt.subplot2grid((6, 4), (0, 0),
                                             rowspan=5,
                                             colspan=4)
                        a2 = plt.subplot2grid((6, 4), (5, 0),
                                              rowspan=1,
                                              colspan=4,
                                              sharex=a)

                        dataLink = 'https://wex.nz/api/3/trades/btc_usd?limit=2000'
                        data = urllib.request.urlopen(dataLink)
                        data = data.read().decode("utf-8")
                        data = json.loads(data)

                        #Takes all the data under 'btc_usd' in the api
                        data = data["btc_usd"]

                        #Makes data a panda dataset
                        data = pd.DataFrame(data)

                        data["datestamp"] = np.array(
                            data["timestamp"]).astype("datetime64[s]")
                        allDates = data["datestamp"].tolist()

                        buys = data[(data['type'] == 'bid')]
                        #buys["datestamp"] = np.array(buys["timestamp"]).astype("datetime64[s]")
                        buyDates = (buys["datestamp"]).tolist()

                        sells = data[(data['type'] == 'ask')]
                        #sells["datestamp"] = np.array(sells["timestamp"]).astype("datetime64[s]")
                        sellDates = (sells["datestamp"]).tolist()

                        volume = data["amount"]

                        a.clear()

                        a.plot_date(buyDates,
                                    buys["price"],
                                    lightColour,
                                    label="buys")
                        a.plot_date(sellDates,
                                    sells["price"],
                                    darkColour,
                                    label="sells")

                        a2.fill_between(allDates,
                                        0,
                                        volume,
                                        facecolor=darkColour)

                        #Makes it easier to see dates on the graph
                        a.xaxis.set_major_locator(mticker.MaxNLocator(5))
                        a.xaxis.set_major_formatter(
                            mdates.DateFormatter("%Y-%m-%d %H:%M:%S"))

                        plt.setp(a.get_xticklabels(), visible=False)
                        #Creates legend
                        a.legend(bbox_to_anchor=(0, 1.02, 1, .102),
                                 loc=3,
                                 ncol=2,
                                 borderaxespad=0)
                        a.set_title("BTC Prices (USD) \nLast Price: " +
                                    str(data["price"][1999]))
                        priceData = data['price'].apply(float).tolist()

                    if exchange == "Bitstamp":
                        a = plt.subplot2grid((6, 4), (0, 0),
                                             rowspan=5,
                                             colspan=4)
                        a2 = plt.subplot2grid((6, 4), (5, 0),
                                              rowspan=1,
                                              colspan=4,
                                              sharex=a)

                        dataLink = 'https://www.bitstamp.net/api/transactions/'
                        data = urllib.request.urlopen(dataLink)
                        data = data.read().decode("utf-8")
                        data = json.loads(data)

                        # Makes data a panda dataset
                        data = pd.DataFrame(data)

                        data["datestamp"] = np.array(
                            data["date"].apply(int)).astype("datetime64[s]")
                        dateStamps = data["datestamp"].tolist()
                        #allDates = data["datestamp"].tolist()

                        # buys = data[(data['type'] == 'bid')]
                        # # buys["datestamp"] = np.array(buys["timestamp"]).astype("datetime64[s]")
                        # buyDates = (buys["datestamp"]).tolist()
                        #
                        # sells = data[(data['type'] == 'ask')]
                        # # sells["datestamp"] = np.array(sells["timestamp"]).astype("datetime64[s]")
                        # sellDates = (sells["datestamp"]).tolist()

                        volume = data["amount"].apply(float).tolist()

                        a.clear()

                        a.plot_date(dateStamps,
                                    data["price"],
                                    lightColour,
                                    label="buys")

                        a2.fill_between(dateStamps,
                                        0,
                                        volume,
                                        facecolor=darkColour)

                        # Makes it easier to see dates on the graph
                        a.xaxis.set_major_locator(mticker.MaxNLocator(5))
                        a.xaxis.set_major_formatter(
                            mdates.DateFormatter("%Y-%m-%d %H:%M:%S"))
                        plt.setp(a.get_xticklabels(), visible=False)
                        # Creates legend
                        a.legend(bbox_to_anchor=(0, 1.02, 1, .102),
                                 loc=3,
                                 ncol=2,
                                 borderaxespad=0)
                        a.set_title(
                            "Bitstamp BTC Prices (USD) \nLast Price: " +
                            str(data["price"][0]))
                        priceData = data['price'].apply(float).tolist()

                    if exchange == "Bitfinex":
                        a = plt.subplot2grid((6, 4), (0, 0),
                                             rowspan=5,
                                             colspan=4)
                        a2 = plt.subplot2grid((6, 4), (5, 0),
                                              rowspan=1,
                                              colspan=4,
                                              sharex=a)

                        dataLink = 'https://api.bitfinex.com/v1/trades/btcusd?limit=2000'
                        data = urllib.request.urlopen(dataLink)
                        data = data.read().decode("utf-8")
                        data = json.loads(data)

                        #Makes data a panda dataset
                        data = pd.DataFrame(data)

                        data["datestamp"] = np.array(
                            data["timestamp"]).astype("datetime64[s]")
                        allDates = data["datestamp"].tolist()

                        buys = data[(data['type'] == 'buy')]
                        #buys["datestamp"] = np.array(buys["timestamp"]).astype("datetime64[s]")
                        buyDates = (buys["datestamp"]).tolist()

                        sells = data[(data['type'] == 'sell')]
                        #sells["datestamp"] = np.array(sells["timestamp"]).astype("datetime64[s]")
                        sellDates = (sells["datestamp"]).tolist()

                        volume = data["amount"].apply(float).tolist()

                        a.clear()

                        a.plot_date(buyDates,
                                    buys["price"],
                                    lightColour,
                                    label="buys")
                        a.plot_date(sellDates,
                                    sells["price"],
                                    darkColour,
                                    label="sells")

                        a2.fill_between(allDates,
                                        0,
                                        volume,
                                        facecolor=darkColour)

                        #Makes it easier to see dates on the graph
                        a.xaxis.set_major_locator(mticker.MaxNLocator(5))
                        a.xaxis.set_major_formatter(
                            mdates.DateFormatter("%Y-%m-%d %H:%M:%S"))
                        plt.setp(a.get_xticklabels(), visible=False)

                        #Creates legend
                        a.legend(bbox_to_anchor=(0, 1.02, 1, .102),
                                 loc=3,
                                 ncol=2,
                                 borderaxespad=0)
                        a.set_title(
                            "Bitfinex BTC Prices (USD) \nLast Price: " +
                            str(data["price"][0]))
                        priceData = data['price'].apply(float).tolist()

                    if exchange == "Huobi":
                        a = plt.subplot2grid((6, 4), (0, 0),
                                             rowspan=6,
                                             colspan=4)

                        data = urllib.request.urlopen(
                            "http://seaofbtc.com/api/basic/price?key=1&tf=1d&exchange="
                            + programName).read()
                        data = data.decode()

                        data = json.loads(data)

                        dateStamp = np.array(data[0]).astype("datetime64[s]")
                        dateStamp = dateStamp.tolist()

                        df = pd.DataFrame({'Datetime': dateStamp})

                        df['Price'] = data[1]
                        df['Volume'] = data[2]
                        df['Symbol'] = "BTCUSD"
                        df['MPLDate'] = df['Datetime'].apply(
                            lambda date: mdates.date2num(date.to_pydatetime()))

                        df = df.set_index("Datetime")

                        lastPrice = df["Price"][-1]

                        a.plot_date(df["MPLDate"][-4500:],
                                    df['Price'][-4500:],
                                    lightColour,
                                    label="price")

                        a.xaxis.set_major_locator(mticker.MaxNLocator(5))
                        a.xaxis.set_major_formatter(
                            mdates.DateFormatter("%Y-%m-%d %H:%M:%S"))

                        a.set_title(
                            "Huobi BTCUSD PRICES BTC Prices (USD) \nLast Price: "
                            + str(lastPrice))
                        priceData = df['price'].apply(float).tolist()

                except Exception as e:
                    print("Failed because of:", e)

            else:
                if counter > 12:
                    try:
                        if exchange == 'Huobi':
                            if topIndicator != "none":

                                a = plt.subplot2grid((6, 4), (1, 0),
                                                     rowspan=5,
                                                     colspan=4)
                                a0 = plt.subplot2grid((6, 4), (0, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)
                            else:
                                a = plt.subplot2grid((6, 4), (0, 0),
                                                     rowspan=6,
                                                     colspan=4)

                        else:
                            if topIndicator != "none" and bottomIndicator != "none":
                                # actual price chart.
                                a = plt.subplot2grid((6, 4), (1, 0),
                                                     rowspan=3,
                                                     colspan=4)
                                # volume!
                                a2 = plt.subplot2grid((6, 4), (4, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)
                                # top indicator
                                a0 = plt.subplot2grid((6, 4), (0, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)
                                # bottom indicator
                                a3 = plt.subplot2grid((6, 4), (5, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)

                            elif topIndicator != "none":
                                a = plt.subplot2grid((6, 4), (1, 0),
                                                     rowspan=4,
                                                     colspan=4)
                                a2 = plt.subplot2grid((6, 4), (5, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)
                                a0 = plt.subplot2grid((6, 4), (0, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)
                            elif bottomIndicator != "none":
                                a = plt.subplot2grid((6, 4), (0, 0),
                                                     rowspan=4,
                                                     colspan=4)
                                a2 = plt.subplot2grid((6, 4), (4, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)
                                # a0 = plt.subplot2grid((6,4), (0,0), sharex=a, rowspan=1, colspan=4)
                                a3 = plt.subplot2grid((6, 4), (5, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)

                            else:
                                a = plt.subplot2grid((6, 4), (0, 0),
                                                     rowspan=5,
                                                     colspan=4)
                                a2 = plt.subplot2grid((6, 4), (5, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)

                        print('http://seaofbtc.com/api/basic/price?key=1&tf=' +
                              dataPace + '&exchange=' + programName)
                        data = urllib.request.urlopen(
                            'http://seaofbtc.com/api/basic/price?key=1&tf=' +
                            dataPace + '&exchange=' + programName).read()

                        data = str(data).replace('b', '').replace("'", '')
                        data = json.loads(data)

                        dateStamp = np.array(data[0]).astype('datetime64[s]')
                        dateStamp = dateStamp.tolist()

                        df = pd.DataFrame({'Datetime': dateStamp})
                        df['Price'] = data[1]
                        df['Volume'] = data[2]
                        df['Symbol'] = "BTCUSD"
                        df['MPLDate'] = df['Datetime'].apply(
                            lambda date: mdates.date2num(date.to_pydatetime()))
                        df = df.set_index('Datetime')

                        OHLC = df['Price'].resample(resampleSize).ohlc()
                        OHLC = OHLC.dropna()

                        volumeData = df['Volume'].resample(resampleSize).sum()

                        OHLC['dateCopy'] = OHLC.index
                        OHLC['MPLDates'] = OHLC['dateCopy'].apply(
                            lambda date: mdates.date2num(date.to_pydatetime()))
                        del OHLC['dateCopy']

                        # volumeData['dateCopy'] = volumeData.index
                        # volumeData['MPLDates'] = volumeData['dateCopy'].apply(lambda date: mdates.date2num(date.to_pydatetime()))
                        # del volumeData['dateCopy']

                        priceData = OHLC['close'].apply(float).tolist()

                        a.clear()
                        if middleIndicators != "none":
                            for eachMA in middleIndicators:
                                ewma = pd.stats.moments.ewma
                                # print("type:",eachMA[0],"periods:",eachMA[1])
                                if eachMA[0] == "sma":
                                    sma = pd.rolling_mean(
                                        OHLC["close"], eachMA[1])
                                    label = str(eachMA[1]) + " SMA"
                                    a.plot(OHLC['MPLDates'], sma, label=label)
                                if eachMA[0] == "ema":
                                    ewma = pd.stats.moments.ewma
                                    label = str(eachMA[1]) + " EMA"
                                    a.plot(OHLC['MPLDates'],
                                           ewma(OHLC["close"], eachMA[1]),
                                           label=label)

                            # a.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
                            #   ncol=2, borderaxespad=0.)

                            a.legend(loc=0)

                        if topIndicator[0] == "rsi":
                            rsiIndicator(priceData, "top")
                        elif topIndicator == "macd":
                            try:
                                computeMACD(priceData, location="top")
                            except:
                                print("failed macd")

                        if bottomIndicator[0] == "rsi":
                            rsiIndicator(priceData, "bottom")
                        elif bottomIndicator == "macd":
                            try:
                                computeMACD(priceData, location="bottom")
                            except:
                                print("failed macd")

                        csticks = candlestick_ohlc(
                            a,
                            OHLC[['MPLDates', 'open', 'high', 'low',
                                  'close']].values,
                            width=candleWidth,
                            colorup=lightColour,
                            colordown=darkColour)
                        a.set_ylabel("price")
                        if exchange != 'Huobi':
                            a2.fill_between(volumeData['MPLDates'],
                                            0,
                                            volumeData['volume'],
                                            facecolor='#183A54')  # , alpha=.4)
                            a2.set_ylabel("volume")

                        a.xaxis.set_major_locator(mticker.MaxNLocator(3))
                        a.xaxis.set_major_formatter(
                            mdates.DateFormatter('%Y-%m-%d %H:%M'))

                        plt.setp(a.get_xticklabels(), visible=False)

                        if topIndicator != "none":
                            plt.setp(a0.get_xticklabels(), visible=False)

                        if bottomIndicator != "none":
                            plt.setp(a2.get_xticklabels(), visible=False)

                        x = (len(OHLC['close'])) - 1

                        if dataPace == '1d':
                            title = exchange + ' 1 Day Data with ' + resampleSize + ' Bars\nLast Price: ' + str(
                                OHLC['close'][x])
                        if dataPace == '3d':
                            title = exchange + ' 3 Day Data with ' + resampleSize + ' Bars\nLast Price: ' + str(
                                OHLC['close'][x])
                        if dataPace == '7d':
                            title = exchange + ' 7 Day Data with ' + resampleSize + ' Bars\nLast Price: ' + str(
                                OHLC['close'][x])

                        if topIndicator != "none":
                            a0.set_title(title)
                        else:
                            a.set_title(title)
                        print('NewGraph!')

                        counter = 0

                    except Exception as e:
                        counter = 9000

                else:
                    counter += 1
コード例 #5
0
def animate(i):
    global refreshRate
    global DatCounter

##################################
##################################
    def computeMACD(x, slow=26, fast=12,location="bottom"):
        """
        compute the MACD (Moving Average Convergence/Divergence) using a fast and slow exponential moving avg'
        return value is emaslow, emafast, macd which are len(x) arrays
        """
        values = {'key': 1,'prices':x}


        url = "http://seaofbtc.com/api/indicator/macd"
        data = urllib.parse.urlencode(values)
        data = data.encode('utf-8')
        req = urllib.request.Request(url, data)
        resp = urllib.request.urlopen(req)
        respData = resp.read()
        newData = str(respData).replace("b","").replace('[','').replace(']','').replace("'",'')

        #print(newData)

        split = newData.split('::')

        macd = split[0]
        ema9 = split[1]
        hist = split[2]

        macd = macd.split(", ")
        ema9 = ema9.split(", ")
        hist = hist.split(", ")


        try:
            macd = [float(i) for i in macd]
        except Exception as e:
            print(str(e)+"  macd")
        try:
            ema9 = [float(i) for i in ema9]
        except Exception as e:
            print(str(e)+"  ema9")
        try:
            hist = [float(i) for i in hist]
        except Exception as e:
            print(str(e)+"  hist")





        print("call!!!")




        if location == "top":
            try:
                a0.plot(OHLC['MPLDates'][fast:], macd[fast:], color=darkColor, lw=2)
                a0.plot(OHLC['MPLDates'][fast:], ema9[fast:], color=lightColor, lw=1)
                a0.fill_between(OHLC['MPLDates'][fast:], hist[fast:], 0, alpha=0.5, facecolor=darkColor, edgecolor=darkColor)
                datLabel = "MACD"
                a0.set_ylabel(datLabel)
            except Exception as e:
                print(str(e))
                topIndicator = "none"


        elif location == "bottom":
            try:
                a3.plot(OHLC['MPLDates'][fast:], macd[fast:], color=darkColor, lw=2)
                a3.plot(OHLC['MPLDates'][fast:], ema9[fast:], color=lightColor, lw=1)
                a3.fill_between(OHLC['MPLDates'][fast:], hist[fast:], 0, alpha=0.5, facecolor=darkColor, edgecolor=darkColor)
                datLabel = "MACD"
                a3.set_ylabel(datLabel)
            except Exception as e:
                print(str(e))
                bottomIndicator = "none"

##################################
##################################

    def rsiIndicator(priceData,location="top"):

        if location == "top":
            values = {'key': 1,'prices':priceData,'periods':topIndicator[1]}

        elif location == "bottom":
            values = {'key': 1,'prices':priceData,'periods':bottomIndicator[1]}


        url = "http://seaofbtc.com/api/indicator/rsi"
        data = urllib.parse.urlencode(values)
        data = data.encode('utf-8')
        req = urllib.request.Request(url, data)
        resp = urllib.request.urlopen(req)
        respData = resp.read()
        newData = str(respData).replace("b","").replace('[','').replace(']','').replace("'",'')
        priceList = newData.split(', ')
        rsiData = [float(i) for i in priceList]

        print("call!!!")


        if location == "top":
            a0.plot_date(OHLC['MPLDates'], rsiData,lightColor, label ="RSI")
            datLabel = "RSI("+str(topIndicator[1])+")"
            a0.set_ylabel(datLabel)

        elif location == "bottom":
            a3.plot_date(OHLC['MPLDates'], rsiData,lightColor, label ="RSI")
            datLabel = "RSI("+str(bottomIndicator[1])+")"
            a3.set_ylabel(datLabel)




    def moving_average(x, n, type='simple'):

        x = np.asarray(x)
        if type=='simple':
            weights = np.ones(n)
        else:
            weights = np.exp(np.linspace(-1, 0, n))

        weights /= weights.sum()


        a =  np.convolve(x, weights, mode='full')[:len(x)]
        return a


    if chartLoad:
        if paneCount == 1:
            if DataPace == "tick":
                try:
                    if exchange == "BTC-e":
                        a = plt.subplot2grid((6,4), (0,0), rowspan=5, colspan=4)
                        a2 = plt.subplot2grid((6,4), (5,0), rowspan=1, colspan=4, sharex = a)

                        dataLink = 'https://btc-e.com/api/3/trades/btc_usd?limit=2000'
                        data = urllib.request.urlopen(dataLink)
                        data = data.readall().decode('utf-8')
                        data = json.loads(data)
                        data = data["btc_usd"]
                        data = pd.DataFrame(data)


                        data["datestamp"] = np.array(data['timestamp']).astype('datetime64[s]')
                        allDates = data["datestamp"].tolist()

                        buys = data[(data['type']=='bid')]
                        buyDates = (buys["datestamp"]).tolist()


                        sells = data[(data['type']=='ask')]
                        sellDates = (sells["datestamp"]).tolist()

                        volume = data["amount"]

                        a.clear()

                        a.plot_date(buyDates,buys["price"], lightColor, label ="buys")

                        a.plot_date(sellDates,sells["price"], darkColor, label = "sells")

                        a2.fill_between(allDates,0, volume, facecolor='#183A54')

                        a.xaxis.set_major_locator(mticker.MaxNLocator(5))
                        a.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))
                        plt.setp(a.get_xticklabels(), visible=False)




                        a.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
                                 ncol=2, borderaxespad=0.)

                        title = 'Last Price: '+str(data["price"][1999])
                        a.set_title(title)

                    if exchange == 'Bitstamp':
                        a = plt.subplot2grid((6,4), (0,0), rowspan=5, colspan=4)
                        a2 = plt.subplot2grid((6,4), (5,0), rowspan=1, colspan=4, sharex = a)

                        dataLink = 'https://www.bitstamp.net/api/transactions/'
                        data = urllib.request.urlopen(dataLink)
                        data = data.readall().decode('utf-8')
                        data = json.loads(data)
                        data = pd.DataFrame(data)
                        data["datestamp"] = np.array(data['date'].apply(int)).astype('datetime64[s]')
                        datestamps = data["datestamp"].tolist()
                        volume = data["amount"].apply(float).tolist()

                        a.clear()

                        a.plot_date(datestamps,data["price"], '#183A54')


                        a2.fill_between(datestamps,0, volume, facecolor='#183A54')


                        a.xaxis.set_major_locator(mticker.MaxNLocator(5))
                        a.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))
                        plt.setp(a.get_xticklabels(), visible=False)

                        title = exchange+' Tick Data\nLast Price: '+str(data["price"][0])
                        a.set_title(title)
                        priceData = data["price"].apply(float).tolist()


                    if exchange == 'Bitfinex':
                        a = plt.subplot2grid((6,4), (0,0), rowspan=5, colspan=4)
                        a2 = plt.subplot2grid((6,4), (5,0), rowspan=1, colspan=4, sharex = a)

                        dataLink = 'https://api.bitfinex.com/v1/trades/btcusd?limit=2000'

                        data = urllib.request.urlopen(dataLink)
                        data = data.readall().decode('utf-8')
                        data = json.loads(data)
                        data = pd.DataFrame(data)

                        volume = data["amount"].apply(float).tolist()


                        data["datestamp"] = np.array(data['timestamp']).astype('datetime64[s]')
                        allDates = data["datestamp"].tolist()

                        buys = data[(data['type']=='buy')]
                        buyDates = (buys["datestamp"]).tolist()

                        sells = data[(data['type']=='sell')]
                        sellDates = (sells["datestamp"]).tolist()

                        a.clear()


                        a.plot_date(buyDates,buys["price"], lightColor, label ="buys")
                        a.plot_date(sellDates,sells["price"], darkColor, label = "sells")
                        a2.fill_between(allDates,0, volume, facecolor='#183A54')


                        a.xaxis.set_major_locator(mticker.MaxNLocator(5))
                        a.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))
                        plt.setp(a.get_xticklabels(), visible=False)
                        a.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
                           ncol=2, borderaxespad=0.)

                        title = exchange+' Tick Data\nLast Price: '+str(data["price"][0])
                        a.set_title(title)
                        priceData = data["price"].apply(float).tolist()

                    if exchange == 'Huobi':
                        try:
                            a = plt.subplot2grid((6,4), (0,0), rowspan=6, colspan=4)

                            data = urllib.request.urlopen('http://seaofbtc.com/api/basic/price?key=1&tf=1d&exchange='+programName).read()

                            data = str(data).replace('b','').replace("'",'')
                            data = json.loads(data)



                            dateStamp = np.array(data[0]).astype('datetime64[s]')
                            dateStamp = dateStamp.tolist()
                            print('here')

                            df = pd.DataFrame({'Datetime':dateStamp})




                            df['Price'] = data[1]

                            df['Volume'] = data[2]
                            df['Symbol'] = "BTCUSD"
                            df['MPLDate'] = df['Datetime'].apply(lambda date: mdates.date2num(date.to_pydatetime()))
                            df = df.set_index('Datetime')
                            lastPrice = df['Price'][-1]

                            a.plot_date(df['MPLDate'][-4500:],df['Price'][-4500:], lightColor, label ="price")

                            a.xaxis.set_major_locator(mticker.MaxNLocator(5))
                            a.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))


                            title = exchange+' Tick Data\nLast Price: '+str(lastPrice)
                            a.set_title(title)
                            priceData = df['Price'].apply(float).tolist()
                        except Exception as e:
                            print(str(e))




                except Exception as e:
                    print("failed",str(e))
                    DatCounter = 9000


##### ALL OTHER, NON-TICK, DATA. ##################################
            else:
                if DatCounter > 12:
                    try:
                        if exchange == 'Huobi':
                            if topIndicator != "none":

                                a = plt.subplot2grid((6,4), (1,0), rowspan=5, colspan=4)
                                a0 = plt.subplot2grid((6,4), (0,0), sharex=a, rowspan=1, colspan=4)
                            else:
                                a = plt.subplot2grid((6,4), (0,0), rowspan=6, colspan=4)

                        else:
                            if topIndicator != "none" and bottomIndicator != "none":
                                # actual price chart.
                                a = plt.subplot2grid((6,4), (1,0), rowspan=3, colspan=4)
                                # volume!
                                a2 = plt.subplot2grid((6,4), (4,0), sharex=a, rowspan=1, colspan=4)
                                # top indicator
                                a0 = plt.subplot2grid((6,4), (0,0), sharex=a, rowspan=1, colspan=4)
                                # bottom indicator
                                a3 = plt.subplot2grid((6,4), (5,0), sharex=a, rowspan=1, colspan=4)

                            elif topIndicator != "none":
                                a = plt.subplot2grid((6,4), (1,0), rowspan=4, colspan=4)
                                a2 = plt.subplot2grid((6,4), (5,0), sharex=a, rowspan=1, colspan=4)
                                a0 = plt.subplot2grid((6,4), (0,0), sharex=a, rowspan=1, colspan=4)
                            elif bottomIndicator != "none":
                                a = plt.subplot2grid((6,4), (0,0), rowspan=4, colspan=4)
                                a2 = plt.subplot2grid((6,4), (4,0), sharex=a, rowspan=1, colspan=4)
                                #a0 = plt.subplot2grid((6,4), (0,0), sharex=a, rowspan=1, colspan=4)
                                a3 = plt.subplot2grid((6,4), (5,0), sharex=a, rowspan=1, colspan=4)

                            else:
                                a = plt.subplot2grid((6,4), (0,0), rowspan=5, colspan=4)
                                a2 = plt.subplot2grid((6,4), (5,0), sharex=a, rowspan=1, colspan=4)



                        print('http://seaofbtc.com/api/basic/price?key=1&tf='+DataPace+'&exchange='+programName)
                        data = urllib.request.urlopen('http://seaofbtc.com/api/basic/price?key=1&tf='+DataPace+'&exchange='+programName).read()





                        data = str(data).replace('b','').replace("'",'')
                        data = json.loads(data)

                        dateStamp = np.array(data[0]).astype('datetime64[s]')
                        dateStamp = dateStamp.tolist()

                        df = pd.DataFrame({'Datetime':dateStamp})
                        df['Price'] = data[1]
                        df['Volume'] = data[2]
                        df['Symbol'] = "BTCUSD"
                        df['MPLDate'] = df['Datetime'].apply(lambda date: mdates.date2num(date.to_pydatetime()))
                        df = df.set_index('Datetime')


                        OHLC =  df['Price'].resample(resampleSize, how='ohlc')
                        OHLC = OHLC.dropna()

                        volumeData = df['Volume'].resample(resampleSize, how={'volume':'sum'})

                        OHLC['dateCopy'] = OHLC.index
                        OHLC['MPLDates'] = OHLC['dateCopy'].apply(lambda date: mdates.date2num(date.to_pydatetime()))
                        del OHLC['dateCopy']

                        volumeData['dateCopy'] = volumeData.index
                        volumeData['MPLDates'] = volumeData['dateCopy'].apply(lambda date: mdates.date2num(date.to_pydatetime()))
                        del volumeData['dateCopy']


                        priceData = OHLC['close'].apply(float).tolist()

                        a.clear()
                        if middleIndicator != "none":
                            for eachMA in middleIndicator:
                                ewma = pd.stats.moments.ewma

                                if eachMA[0] == "sma":
                                    sma = pd.rolling_mean(OHLC["close"],eachMA[1])
                                    label = str(eachMA[1])+" SMA"
                                    a.plot(OHLC['MPLDates'],sma, label=label)
                                if eachMA[0] == "ema":
                                    ewma = pd.stats.moments.ewma
                                    label = str(eachMA[1])+" EMA"
                                    a.plot(OHLC['MPLDates'],ewma(OHLC["close"], eachMA[1]), label=label)


                            a.legend(loc=0)






                        if topIndicator[0] == "rsi":
                            rsiIndicator(priceData,"top")
                        elif topIndicator == "macd":
                            try:
                                computeMACD(priceData,location="top")
                            except:
                                print("failed macd")




                        if bottomIndicator[0] == "rsi":
                            rsiIndicator(priceData,"bottom")
                        elif bottomIndicator == "macd":
                            try:
                                computeMACD(priceData,location="bottom")
                            except:
                                print("failed macd")






                        csticks = candlestick_ohlc(a, OHLC[['MPLDates', 'open', 'high', 'low', 'close']].values, width=candleWidth, colorup=lightColor, colordown=darkColor)
                        a.set_ylabel("price")
                        if exchange != 'Huobi':
                            a2.fill_between(volumeData['MPLDates'],0, volumeData['volume'], facecolor='#183A54')#, alpha=.4)
                            a2.set_ylabel("volume")


                        a.xaxis.set_major_locator(mticker.MaxNLocator(3))
                        a.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))

                        plt.setp(a.get_xticklabels(), visible=False)

                        if topIndicator != "none":
                            plt.setp(a0.get_xticklabels(), visible=False)

                        if bottomIndicator != "none":
                            plt.setp(a2.get_xticklabels(), visible=False)

                        x = (len(OHLC['close']))-1

                        if DataPace == '1d':
                            title = exchange+' 1 Day Data with '+resampleSize+' Bars\nLast Price: '+str(OHLC['close'][x])
                        if DataPace == '3d':
                            title = exchange+' 3 Day Data with '+resampleSize+' Bars\nLast Price: '+str(OHLC['close'][x])
                        if DataPace == '7d':
                            title = exchange+' 7 Day Data with '+resampleSize+' Bars\nLast Price: '+str(OHLC['close'][x])


                        if topIndicator != "none":
                            a0.set_title(title)
                        else:
                            a.set_title(title)
                        print('NewGraph!')

                        DatCounter = 0









                    except Exception as e:
                        print(str(e),"main animate non tick")
                        DatCounter = 9000

                else:
                    DatCounter += 1
コード例 #6
0
ファイル: bt2heatmap.py プロジェクト: xiaoqiwang19/BatMeth2
def plotheatmaper(mymatrix, outFileName,
               colorMapDict={'colorMap': ['binary'], 'missingDataColor': 'black', 'alpha': 1.0},
               plotTitle='',
               xAxisLabel='', yAxisLabel='', regionsLabel='',
               zMin=None, zMax=None,
               yMin=None, yMax=None,
               averageType='median',
               reference_point_label=None,
               startLabel='TSS', endLabel="TES",
               heatmapHeight=25,
               heatmapWidth=7.5,
               perGroup=False, whatToShow='plot, heatmap and colorbar',
               plot_type='lines',
               linesAtTickMarks=False,
               image_format=None,
               legend_location='upper-left',
               box_around_heatmaps=True,
               label_rotation=0.0,
               dpi=200,
               interpolation_method='auto',
               num_samples=1):

    if reference_point_label is not None:
        reference_point_label = [reference_point_label] * num_samples
    startLabel = startLabel
    endLabel = endLabel

    matrix_flatten = None
    if zMin is None:
        matrix_flatten = mymatrix.flatten()
        # try to avoid outliers by using np.percentile
        zMin = np.percentile(matrix_flatten, 1.0)
        if np.isnan(zMin):
            zMin = [None]
        else:
            zMin = [zMin]  # convert to list to support multiple entries
    elif 'auto' in zMin:
        matrix_flatten = mymatrix.flatten()
        auto_min = np.percentile(matrix_flatten, 1.0)
        if np.isnan(auto_min):
            auto_min = None
        new_mins = [float(x) if x != 'auto' else auto_min for x in zMin]
        zMin = new_mins
    else:
        new_mins = [float(x) for x in zMin]
        zMin = new_mins

    if zMax is None:
        if matrix_flatten is None:
            matrix_flatten = mymatrix.flatten()
        # try to avoid outliers by using np.percentile
        zMax = np.percentile(matrix_flatten, 98.0)
        if np.isnan(zMax) or zMax <= zMin[0]:
            zMax = [None]
        else:
            zMax = [zMax]
    elif 'auto' in zMax:
        matrix_flatten = mymatrix.flatten()
        auto_max = np.percentile(matrix_flatten, 98.0)
        if np.isnan(auto_max):
            auto_max = None
        new_maxs = [float(x) if x != 'auto' else auto_max for x in zMax]
        zMax = new_maxs
    else:
        new_maxs = [float(x) for x in zMax]
        zMax = new_maxs
    if (len(zMin) > 1) & (len(zMax) > 1):
        for index, value in enumerate(zMax):
            if value <= zMin[index]:
                sys.stderr.write("Warnirng: In bigwig {}, the given zmin ({}) is larger than "
                                 "or equal to the given zmax ({}). Thus, it has been set "
                                 "to None. \n".format(index + 1, zMin[index], value))
                zMin[index] = None

    if yMin is None:
        yMin = [None]
    if yMax is None:
        yMax = [None]
    if not isinstance(yMin, list):
        yMin = [yMin]
    if not isinstance(yMax, list):
        yMax = [yMax]

    plt.rcParams['font.size'] = 8.0
    fontP = FontProperties()

    showSummaryPlot = False
    showColorbar = False

    if whatToShow == 'plot and heatmap':
        showSummaryPlot = True
    elif whatToShow == 'heatmap and colorbar':
        showColorbar = True
    elif whatToShow == 'plot, heatmap and colorbar':
        showSummaryPlot = True
        showColorbar = True

    # colormap for the heatmap
    if colorMapDict['colorMap']:
        cmap = []
        for color_map in colorMapDict['colorMap']:
            cmap.append(plt.get_cmap(color_map))
            cmap[-1].set_bad(colorMapDict['missingDataColor'])  # nans are printed using this color

    if colorMapDict['colorList'] and len(colorMapDict['colorList']) > 0:
        # make a cmap for each color list given
        cmap = []
        for color_list in colorMapDict['colorList']:
            cmap.append(matplotlib.colors.LinearSegmentedColormap.from_list(
                'my_cmap', color_list.replace(' ', '').split(","), N=colorMapDict['colorNumber']))
            cmap[-1].set_bad(colorMapDict['missingDataColor'])  # nans are printed using this color

    if len(cmap) > 1 or len(zMin) > 1 or len(zMax) > 1:
        # position color bar below heatmap when more than one
        # heatmap color is given
        colorbar_position = 'below'
    else:
        colorbar_position = 'side'

    grids = prepare_layout(mymatrix, (heatmapWidth, heatmapHeight),
                           showSummaryPlot, showColorbar, perGroup, colorbar_position)

    # figsize: w,h tuple in inches
    figwidth = heatmapWidth / 2.54
    figheight = heatmapHeight / 2.54
    if showSummaryPlot:
        # the summary plot ocupies a height
        # equal to the fig width
        figheight += figwidth

    numsamples = num_samples
    if perGroup:
        num_cols = num_groups
    else:
        num_cols = numsamples
    total_figwidth = figwidth * num_cols
    if showColorbar:
        if colorbar_position == 'below':
            figheight += 1 / 2.54
        else:
            total_figwidth += 1 / 2.54

    fig = plt.figure(figsize=(total_figwidth, figheight))
    fig.suptitle(plotTitle, y=1 - (0.06 / figheight))

    # color map for the summary plot (profile) on top of the heatmap
    cmap_plot = plt.get_cmap('jet')
    numgroups = num_groups
    if perGroup:
        color_list = cmap_plot(np.arange(num_samples) / num_samples)
    else:
        color_list = cmap_plot(np.arange(numgroups) / numgroups)
    alpha = colorMapDict['alpha']

    first_group = 0  # helper variable to place the title per sample/group
    for sample in range(num_samples):
        sample_idx = sample
        for group in range(numgroups):
            group_idx = group
            # add the respective profile to the
            # summary plot
            sub_matrix = get_matrix(mymatrix, group, sample)
            if showSummaryPlot:
                if perGroup:
                    sample_idx = sample + 2  # plot + spacer
                else:
                    group += 2  # plot + spacer
                first_group = 1

            if perGroup:
                ax = fig.add_subplot(grids[sample_idx, group])
                # the remainder (%) is used to iterate
                # over the available color maps (cmap).
                # if the user only provided, lets say two
                # and there are 10 groups, colormaps they are reused every
                # two groups.
                cmap_idx = group_idx % len(cmap)
                zmin_idx = group_idx % len(zMin)
                zmax_idx = group_idx % len(zMax)
            else:
                ax = fig.add_subplot(grids[group, sample])
                # see above for the use of '%'
                cmap_idx = sample % len(cmap)
                zmin_idx = sample % len(zMin)
                zmax_idx = sample % len(zMax)

            if group == first_group and not showSummaryPlot and not perGroup:
                title = sample_labels[sample]
                ax.set_title(title)

            if box_around_heatmaps is False:
                # Turn off the boxes around the individual heatmaps
                ax.spines['top'].set_visible(False)
                ax.spines['right'].set_visible(False)
                ax.spines['bottom'].set_visible(False)
                ax.spines['left'].set_visible(False)
            rows, cols = sub_matrix['matrix'].shape
            # if the number of rows is too large, then the 'nearest' method simply
            # drops rows. A better solution is to relate the threshold to the DPI of the image
            if interpolation_method == 'auto':
                if rows >= 1000:
                    interpolation_method = 'bilinear'
                else:
                    interpolation_method = 'nearest'

            # if np.clip is not used, then values of the matrix that exceed the zmax limit are
            # highlighted. Usually, a significant amount of pixels are equal or above the zmax and
            # the default behaviour produces images full of large highlighted dots.
            # If interpolation='nearest' is used, this has no effect
            sub_matrix['matrix'] = np.clip(sub_matrix['matrix'], zMin[zmin_idx], zMax[zmax_idx])
            img = ax.imshow(sub_matrix['matrix'],
                            aspect='auto',
                            interpolation=interpolation_method,
                            origin='upper',
                            vmin=zMin[zmin_idx],
                            vmax=zMax[zmax_idx],
                            cmap=cmap[cmap_idx],
                            alpha=alpha,
                            extent=[0, cols, rows, 0])
            img.set_rasterized(True)
            # plot border at the end of the regions

            if perGroup:
                ax.axes.set_xlabel(sub_matrix['group'])
                if sample < hm.matrix.get_num_samples() - 1:
                    ax.axes.get_xaxis().set_visible(False)
            else:
                ax.axes.get_xaxis().set_visible(False)
                ax.axes.set_xlabel(xAxisLabel)
            ax.axes.set_yticks([])
            if perGroup and group == 0:
                ax.axes.set_ylabel(sub_matrix['sample'])
            elif not perGroup and sample == 0:
                ax.axes.set_ylabel(sub_matrix['group'])

            # Plot vertical lines at tick marks if desired
            if linesAtTickMarks:
                xticks_heat, xtickslabel_heat = getTicks(reference_point_label, sample , startLabel, endLabel)
                xticks_heat = [x + 0.5 for x in xticks_heat]  # There's an offset of 0.5 compared to the profile plot
                if np.ceil(max(xticks_heat)) != float(sub_matrix['matrix'].shape[1]):
                    tickscale = float(sub_matrix['matrix'].shape[1]) / max(xticks_heat)
                    xticks_heat_use = [x * tickscale for x in xticks_heat]
                else:
                    xticks_heat_use = xticks_heat
                for x in xticks_heat_use:
                    ax.axvline(x=x, color='black', linewidth=0.5, dashes=(3, 2))

            # add labels to last block in a column
            if (perGroup and sample == numsamples - 1) or \
               (not perGroup and group_idx == numgroups - 1):

                # add xticks to the bottom heatmap (last group)
                ax.axes.get_xaxis().set_visible(True)
                xticks_heat, xtickslabel_heat = getTicks(reference_point_label, sample , startLabel, endLabel)
                xticks_heat = [x + 0.5 for x in xticks_heat]  # There's an offset of 0.5 compared to the profile plot
                if np.ceil(max(xticks_heat)) != float(sub_matrix['matrix'].shape[1]):
                    tickscale = float(sub_matrix['matrix'].shape[1]) / max(xticks_heat)
                    xticks_heat_use = [x * tickscale for x in xticks_heat]
                    ax.axes.set_xticks(xticks_heat_use)
                else:
                    ax.axes.set_xticks(xticks_heat)
                ax.axes.set_xticklabels(xtickslabel_heat, size=8)

                # align the first and last label
                # such that they don't fall off
                # the heatmap sides
                ticks = ax.xaxis.get_major_ticks()
                ticks[0].label1.set_horizontalalignment('left')
                ticks[-1].label1.set_horizontalalignment('right')

                ax.get_xaxis().set_tick_params(
                    which='both',
                    top=False,
                    direction='out')

                if showColorbar and colorbar_position == 'below':
                    # draw a colormap per each heatmap below the last block
                    if perGroup:
                        col = group_idx
                    else:
                        col = sample
                    ax = fig.add_subplot(grids[-1, col])
                    tick_locator = ticker.MaxNLocator(nbins=3)
                    cbar = fig.colorbar(img, cax=ax, alpha=alpha, orientation='horizontal', ticks=tick_locator)
                    labels = cbar.ax.get_xticklabels()
                    ticks = cbar.ax.get_xticks()
                    if ticks[0] == 0:
                        # if the label is at the start of the colobar
                        # move it a bit inside to avoid overlapping
                        # with other labels
                        labels[0].set_horizontalalignment('left')
                    if ticks[-1] == 1:
                        # if the label is at the end of the colobar
                        # move it a bit inside to avoid overlapping
                        # with other labels
                        labels[-1].set_horizontalalignment('right')
                    # cbar.ax.set_xticklabels(labels, rotation=90)

    if showColorbar and colorbar_position != 'below':
        if showSummaryPlot:
            # we don't want to colorbar to extend
            # over the profiles and spacer top rows
            grid_start = 2
        else:
            grid_start = 0

        ax = fig.add_subplot(grids[grid_start:, -1])
        fig.colorbar(img, cax=ax, alpha=alpha)

    if box_around_heatmaps:
        plt.subplots_adjust(wspace=0.10, hspace=0.025, top=0.85, bottom=0, left=0.04, right=0.96)
    else:
        #  When no box is plotted the space between heatmaps is reduced
        plt.subplots_adjust(wspace=0.05, hspace=0.01, top=0.85, bottom=0, left=0.04, right=0.96)

    plt.savefig(outFileName, bbox_inches='tight', pdd_inches=0, dpi=dpi, format=image_format)
    plt.close()
コード例 #7
0
def VSO_avg(table, VSE=False):

    #grab table range for plot title
    table_start = str(np.array(table.index.values[0], dtype='datetime64[s]'))
    table_end = str(np.array(table.index.values[-1], dtype='datetime64[s]'))
    time_range_str = table_start + ' TO ' + table_end
    time = table.index.values
    #num_ti = len(time)-1
    mag_line_i = []

    #n = 100  # vectors
    r = 6051.8
    scale = 500 / r  # venus radii/nT

    #scale location data by venus radius
    table['XSC'] = table['XSC'] / r
    table['YSC'] = table['YSC'] / r
    table['ZSC'] = table['ZSC'] / r
    table['RSC'] = table['RSC'] / r

    #plot location data
    fig, (ax1, ax2, ax3) = plt.subplots(nrows=1,
                                        ncols=3,
                                        sharex=True,
                                        sharey=True)
    ax1.plot(table['XSC'], table['YSC'], color=(139 / 255, 0, 0))
    ax2.plot(table['XSC'], table['ZSC'], color=(139 / 255, 0, 0))
    ax3.plot(table['YSC'], table['ZSC'], color=(139 / 255, 0, 0))

    #set axis labels
    ax1.set(xlabel='VSO X', ylabel='VSO Y')
    ax2.set(xlabel='VSO X', ylabel='VSO Z')
    ax3.set(xlabel='VSO Y', ylabel='VSO Z')

    if VSE == True:
        ax1.set(xlabel='VSE X', ylabel='VSE Y')
        ax2.set(xlabel='VSE X', ylabel='VSE Z')
        ax3.set(xlabel='VSE Y', ylabel='VSE Z')

    cax = plt.axes([0.93, 0.1, 0.020, 0.8])
    plt.subplots_adjust(bottom=0.1, left=0.07, right=0.91, top=0.9)

    #downsample table to minute cadence
    table = table.resample('T').mean()

    time = table.index.values
    num_ti = len(time) - 1
    print(num_ti)
    #linspace the # of vectors wanted
    for i in np.linspace(0, num_ti, num=num_ti):
        mag_line_i = mag_line_i + [int(round(i))]

    # define 3rd-axis values
    #o_mags_1 = table['Bz'].values # X vs Y
    #o_mags_2 = table['By'].values # X vs Z
    #o_mags_3 = table['Bx'].values # Y vs Z

    # define the colormap
    cmap = plt.get_cmap('viridis')
    # define the bins and normalize
    #     bounds1 = np.linspace(np.nanmin(o_mags_1), np.nanmax(o_mags_1), 60)
    #     norm1 = matplotlib.colors.BoundaryNorm(bounds1, cmap.N)
    #
    #     bounds2 = np.linspace(np.nanmin(o_mags_2), np.nanmax(o_mags_2), 60)
    #     norm2 = matplotlib.colors.BoundaryNorm(bounds2, cmap.N)
    #
    #     bounds3 = np.linspace(np.nanmin(o_mags_3), np.nanmax(o_mags_3), 60)
    #     norm3 = matplotlib.colors.BoundaryNorm(bounds3, cmap.N)

    #o_mags = list(o_mags_1) + list(o_mags_2) + list(o_mags_3)
    o_mags = table['|B|'].values
    bounds = np.linspace(np.nanmin(o_mags), np.nanmax(o_mags), 60)
    norm = matplotlib.colors.BoundaryNorm(bounds, cmap.N)

    # plot each MAG 3D vector individually
    for i, item in enumerate(mag_line_i):
        # Getting the color for the Bz line
        #         r = cmap(norm(o_mags_1[i]), bytes=True)[0]
        #         g = cmap(norm(o_mags_1[i]), bytes=True)[1]
        #         b = cmap(norm(o_mags_1[i]), bytes=True)[2]
        r = cmap(norm(o_mags[i]), bytes=True)[0]
        g = cmap(norm(o_mags[i]), bytes=True)[1]
        b = cmap(norm(o_mags[i]), bytes=True)[2]
        color1 = rgb2hex(r, g, b)
        # Plot
        bplot_1 = ax1.plot([
            table['XSC'][item], table['XSC'][item] + scale * table['Bx'][item]
        ], [
            table['YSC'][item], table['YSC'][item] + scale * table['By'][item]
        ],
                           color=color1)

        # Getting the color for the By line
        #         r = cmap(norm(o_mags_2[i]), bytes=True)[0]
        #         g = cmap(norm(o_mags_2[i]), bytes=True)[1]
        #         b = cmap(norm(o_mags_2[i]), bytes=True)[2]
        r = cmap(norm(o_mags[i]), bytes=True)[0]
        g = cmap(norm(o_mags[i]), bytes=True)[1]
        b = cmap(norm(o_mags[i]), bytes=True)[2]
        color2 = rgb2hex(r, g, b)
        # Plot
        bplot_2 = ax2.plot([
            table['XSC'][item], table['XSC'][item] + scale * table['Bx'][item]
        ], [
            table['ZSC'][item], table['ZSC'][item] + scale * table['Bz'][item]
        ],
                           color=color2)

        # Getting the color for the Bx line
        #         r = cmap(norm(o_mags_3[i]), bytes=True)[0]
        #         g = cmap(norm(o_mags_3[i]), bytes=True)[1]
        #         b = cmap(norm(o_mags_3[i]), bytes=True)[2]
        r = cmap(norm(o_mags[i]), bytes=True)[0]
        g = cmap(norm(o_mags[i]), bytes=True)[1]
        b = cmap(norm(o_mags[i]), bytes=True)[2]
        color3 = rgb2hex(r, g, b)
        # Plot
        bplot_3 = ax3.plot([
            table['YSC'][item], table['YSC'][item] + scale * table['By'][item]
        ], [
            table['ZSC'][item], table['ZSC'][item] + scale * table['Bz'][item]
        ],
                           color=color3)

    cb = matplotlib.colorbar.ColorbarBase(cax,
                                          cmap=cmap,
                                          norm=norm,
                                          ticks=bounds,
                                          orientation='vertical')
    cb.set_label(r'$B_{\perp}$ Strength (nT)')
    tick_locator = ticker.MaxNLocator(nbins=11)
    cb.locator = tick_locator
    cb.update_ticks()

    #add circle to represent venus
    add_venus_2D((0, 0), radius=1, angle=90, ax=ax1, colors=('k', 'w'))
    add_venus_2D((0, 0), radius=1, angle=90, ax=ax2, colors=('k', 'w'))
    add_venus_2D((0, 0), radius=1, angle=90, ax=ax3, colors=('w', 'w'))

    #darken plot background
    ax1.set_facecolor('xkcd:slate grey')
    ax2.set_facecolor('xkcd:slate grey')
    ax3.set_facecolor('xkcd:slate grey')

    #set title above middle plot
    ax2.set(title='VEX Orbit MAG Data: ' + time_range_str)

    #standardize plot limits
    #ax1.set_xlim([-5.5,3.5])
    #ax1.set_ylim([-12,2.5])
    #ax2.set_xlim([-5.5,3.5])
    #ax2.set_ylim([-12,2.5])
    #ax3.set_xlim([-5.5,3.5])
    #ax3.set_ylim([-12,2.5])
    #model bow shock

    L = 1.303
    epsilon = 1.056
    x0 = 0.788
    x = table['XSC'].values + [1.2]
    y = table['YSC'].values
    #print(table.iloc[11653])

    rho = np.sqrt((table['YSC'].values)**2 + (table['ZSC'].values)**2)
    BS = np.sqrt(L**2 - 2 * epsilon * (x - x0) * L - (epsilon**2 - 1) *
                 (x - x0)**2)
    BS_yz = np.sqrt(L**2 - 2 * epsilon * (0 - x0) * L - (epsilon**2 - 1) *
                    (0 - x0)**2)
    ax1.plot(x, BS, 'r')
    ax1.plot(x, -BS, 'r')
    ax2.plot(x, BS, 'r')
    ax2.plot(x, -BS, 'r')
    BSplt = plt.Circle((0, 0), BS_yz * 1.2, color='r', fill=False)
    ax3.add_artist(BSplt)

    #ax1.axis('equal')
    #ax2.axis('equal')
    #     X = table['XSC']
    #     Y = table['YSC']
    #     Z = table['ZSC']
    #
    #     max_range = np.array([X.max()-X.min(), Y.max()-Y.min(), Z.max()-Z.min()]).max() / 2.0
    #
    #     mid_x = (X.max()+X.min()) * 0.5
    #     mid_y = (Y.max()+Y.min()) * 0.5
    #     mid_z = (Z.max()+Z.min()) * 0.5
    #     ax1.set_xlim(mid_x - max_range, mid_x + max_range)
    #     ax1.set_ylim(mid_y - max_range, mid_y + max_range)
    #     ax1.set_zlim(mid_z - max_range, mid_z + max_range)
    #     ax2.set_xlim(mid_x - max_range, mid_x + max_range)
    #     ax2.set_ylim(mid_y - max_range, mid_y + max_range)
    #     ax2.set_zlim(mid_z - max_range, mid_z + max_range)
    plt.show()
コード例 #8
0
ファイル: plot_saga2.py プロジェクト: guanyilun/gc_plots
##############
# left panel #
##############
ax = plt.subplot(131, projection=imap.wcs)
ax = plotstyle.setup_axis(ax, nticks=[5, 5], fmt=None)
opts = {
    'cmap': 'planck_half',
    'interpolation': 'nearest',
    'vmin': 0,
    'vmax': 20,
    # 'norm': colors.LogNorm(vmin=5, vmax=50),
}
# background: total intensity
im = ax.imshow(imap_sm[0], **opts)
cax = plotstyle.add_colorbar_hpad(ax, pad="1%", hpad="50%")
locator = ticker.MaxNLocator(nbins=4)
fig.colorbar(im, cax=cax, orientation='horizontal',
             ticks=locator).set_label(texify("I [MJy/sr]"), fontsize=10)
cax.xaxis.set_label_position('top')
cax.xaxis.set_ticks_position('top')
ax.text(0.12, 1.03, texify("f090"), transform=ax.transAxes, fontsize=12)
ax.set_xlabel(r"$l$")
ax.set_ylabel(r"$b$")
# foreground: magnetic field orientation

theta = lib.Bangle(imap_sm[1], imap_sm[2], toIAU=True)
theta += np.pi / 2  # this gets the B-field angle corrected
# x- and y-components of magnetic field
Bx = np.cos(theta)
By = np.sin(theta)
# calculate polarization error as masking
コード例 #9
0
ファイル: plot_map.py プロジェクト: lsawade/lwsspy
def plot_map(fill=True,
             zorder=None,
             labelstopright: bool = True,
             labelsbottomleft: bool = True,
             borders: bool = False,
             rivers: bool = False,
             lakes: bool = False,
             outline: bool = False,
             ax=None,
             lw=0.5):
    """Plots map into existing axes.

    Parameters
    ----------
    fill : bool, optional
        fills the continents in light gray, by default True
    zorder : int, optional
        zorder of the map, by default -10
    projection : cartopy.crs.projection, optional
        projection to be used for the map.
    labelstopright : bool, optional
        flag to turn on or off the ticks
    labelsbottomleft : bool, optional
        flag to turn on or off the ticks
    borders : bool
        plot borders. Default True
    rivers : bool
        plot rivers. Default False
    lakes : bool 
        plot lakes. Default True
    lw : float
        outline width

    Returns
    -------
    matplotlib.pyplot.Axes
        Axes in which the map was plotted

    Notes
    -----

    :Author:
        Lucas Sawade ([email protected])

    :Last Modified:
        2021.09.22 11.45


    """

    if ax is None:
        ax = plt.gca()

    # Put lables all around
    if isinstance(ax.projection, cartopy.crs.PlateCarree):

        # Set xticks Should be automated, but I just don't know how rn
        # ax.set_xticks([-180, -135, -90, -45, 0, 45,
        #                90, 135, 180], crs=ax.projection)
        # ax.set_yticks([-90, -45, 0,  45, 90], crs=ax.projection)

        # Set label formatter
        degree_locator = mticker.MaxNLocator(nbins=9, steps=steps)
        ax.xaxis.set_major_locator(degree_locator)
        ax.yaxis.set_major_locator(degree_locator)
        ax.xaxis.set_major_formatter(LongitudeFormatter())
        ax.yaxis.set_major_formatter(LatitudeFormatter())

        ax.tick_params(labeltop=labelstopright,
                       labelright=labelstopright,
                       labelbottom=labelsbottomleft,
                       labelleft=labelsbottomleft)
        ax.grid(linewidth=2, color='black', alpha=0.5, linestyle='--')

    ax.spines['geo'].set_linewidth(lw)
    # Set gridlines
    # gl = ax.gridlines(draw_labels=False, linewidth=1, color='lightgray',
    #
    #     alpha=0.5, linestyle='-', zorder=-1.5)
    if outline:
        edgecolor = 'black'
    else:
        edgecolor = 'none'

    # Add land
    if fill:
        ax.add_feature(cartopy.feature.LAND,
                       zorder=zorder,
                       edgecolor=edgecolor,
                       linewidth=0.5,
                       facecolor=(0.8, 0.8, 0.8))
    else:
        ax.add_feature(cartopy.feature.LAND,
                       zorder=zorder,
                       edgecolor=edgecolor,
                       linewidth=0.5,
                       facecolor=(0, 0, 0, 0))

    if borders:
        ax.add_feature(cartopy.feature.BORDERS,
                       zorder=None if zorder is None else zorder + 1,
                       facecolor='none',
                       edgecolor=(0.5, 0.5, 0.5),
                       linewidth=0.25)

    if rivers:
        ax.add_feature(
            cartopy.feature.RIVERS,
            zorder=zorder,
            edgecolor=(0.3, 0.3, 0.7),
        )
        #    edgecolor=(0.5, 0.5, 0.7) )

    if lakes:
        ax.add_feature(cartopy.feature.LAKES,
                       zorder=None if zorder is None else zorder + 1,
                       edgecolor='black',
                       linewidth=0.5,
                       facecolor=(1.0, 1.0, 1.0))
    return ax
コード例 #10
0
ファイル: makeplot.py プロジェクト: trentagon/vplanet
def comp2huybers(plname, dir='.', xrange=False, show=True):
    """
  Creates plots of insolation, temperature, albedo, ice mass,
  and bed rock height over the length of the simulation

  Parameters
  ----------
  plname : string
    The name of the planet with .Climate data

  Keyword Arguments
  -----------------
  dir : string
    Directory of vplanet simulation (default = '.')
  xrange : float tuple, list, or numpy array
    Range of x-values (time) to restrict plot
    (default = False (no restriction))
  orbit : bool
    Plot orbital data (obliquity, eccentricity, COPP)
    (default = False)
  show : bool
    Show plot in Python (default = True)

  Output
  ------
  PDF format plot with name 'evol_<dir>.pdf'

  """
    if not isinstance(dir, (list, tuple)):
        dir = [dir]

    nfiles = len(dir)

    if nfiles > 1 and orbit == True:
        raise Exception("Error: cannot plot multiple files when orbit = True")

    fig = plt.figure(figsize=(8, 12))

    fig.subplots_adjust(wspace=0.3, top=0.9, hspace=0.2)

    for ii in np.arange(nfiles):
        out = vplot.GetOutput(dir[ii])
        #pdb.set_trace()

        ctmp = 0
        for p in range(len(out.bodies)):
            if out.bodies[p].name == plname:
                body = out.bodies[p]
                ctmp = 1
            else:
                if p == len(out.bodies) - 1 and ctmp == 0:
                    raise Exception("Planet %s not found in folder %s" %
                                    (plname, dir[ii]))

        try:
            ecc = body.Eccentricity
        except:
            ecc = np.zeros_like(body.Time) + getattr(out.log.initial,
                                                     plname).Eccentricity

        try:
            inc = body.Inc
        except:
            inc = np.zeros_like(body.Time)

        try:
            obl = body.Obliquity
        except:
            obltmp = getattr(out.log.initial, plname).Obliquity
            if obltmp.unit == 'rad':
                obltmp *= 180 / np.pi
            obl = np.zeros_like(body.Time) + obltmp

        f = open(dir[ii] + '/' + plname + '.in', 'r')
        lines = f.readlines()
        f.close()
        pco2 = 0
        #pdb.set_trace()
        for i in range(len(lines)):
            if lines[i].split() != []:
                if lines[i].split()[0] == 'dRotPeriod':
                    P = -1 * np.float(lines[i].split()[1])
                if lines[i].split()[0] == 'dSemi':
                    semi = np.float(lines[i].split()[1])
                    if semi < 0:
                        semi *= -1
                if lines[i].split()[0] == 'dpCO2':
                    pco2 = np.float(lines[i].split()[1])

        try:
            longp = (body.ArgP + body.LongA + body.PrecA + 180) * np.pi / 180.0
        except:
            longp = body.PrecA * np.pi / 180.0

        esinv = ecc * np.sin(longp)

        lats = np.unique(body.Latitude)
        nlats = len(lats)
        ntimes = len(body.Time)

        # plot temperature
        temp = np.reshape(body.TempLandLat, (ntimes, nlats))

        ax1 = plt.subplot(7, 1, 5)
        pos = ax1.figbox.get_points()
        c = plt.contourf(body.Time / 1e6, lats[lats > 58], temp.T[lats > 58],
                         20)
        plt.ylabel('Latitude')

        plt.ylim(60, 83)
        plt.yticks([60, 70, 80])
        if xrange == False:
            left = 0
        else:
            left = xrange[0]
#     plt.text(left,140,'\n'.join(titlestr),fontsize=20)
        if xrange:
            plt.xlim(xrange)
        # plt.contour(body.Time/1e6,lats[lats>60],temp.T[lats>60],levels=[0],colors='w')
        plt.xticks(visible=False)
        clb = plt.colorbar(c,
                           cax=plt.axes([
                               pos[1, 0] + 0.01, pos[0, 1], 0.01,
                               pos[1, 1] - pos[0, 1]
                           ]),
                           ticks=[-17, -15, -13, -11, -9, -7, -5])
        clb.set_label('Surface Temp.\n($^{\circ}$C)', fontsize=12)
        # clb.ax.set_yticklabels([-17,-15,-13,-11,-9,-7])
        # plot ice height
        ice = np.reshape(body.IceHeight + body.BedrockH, (ntimes, nlats))

        ax3 = plt.subplot(7, 1, 4)
        pos = ax3.figbox.get_points()
        #     pdb.set_trace()
        c = plt.contourf(body.Time / 1e6, lats[lats > 58], ice.T[lats > 58, :],
                         20)
        plt.ylabel('Latitude')
        plt.ylim(60, 83)
        #   plt.xlim(0,2e6)
        plt.yticks([60, 70, 80])
        if xrange:
            plt.xlim(xrange)
        # plt.contour(body.Time,lats[lats>60],ice.T[lats>60],levels=[0],colors='w')
        plt.xticks(visible=False)
        clb = plt.colorbar(c,
                           cax=plt.axes([
                               pos[1, 0] + 0.01, pos[0, 1], 0.01,
                               pos[1, 1] - pos[0, 1]
                           ]))
        #clb.set_label('Ice height (m)')
        clb.set_label('Ice sheet\nheight (m)', fontsize=12)

        # ax3p = ax3.twinx()
        #   plt.plot(body.Time,esinv,linestyle = 'solid',marker='None',color='salmon',linewidth=2)

        ax4 = plt.subplot(7, 1, 6)
        pos = ax4.figbox.get_points()
        acc = body.IceAccum
        c = plt.contourf(body.Time / 1e6, lats[lats > 58], acc.T[lats > 58],
                         20)
        plt.ylabel('Latitude')
        plt.ylim(60, 83)
        plt.yticks([60, 70, 80])
        plt.xticks(visible=False)
        if xrange == False:
            left = 0
        else:
            left = xrange[0]
#     plt.text(left,140,'\n'.join(titlestr),fontsize=20)
        if xrange:
            plt.xlim(xrange)
        clb = plt.colorbar(c,
                           cax=plt.axes([
                               pos[1, 0] + 0.01, pos[0, 1], 0.01,
                               pos[1, 1] - pos[0, 1]
                           ]))
        tloc = ticker.MaxNLocator(nbins=5)
        clb.locator = tloc
        clb.update_ticks()
        clb.set_label('Ice Accum.\n(m year$^{-1}$)', fontsize=12)

        ax5 = plt.subplot(7, 1, 7)
        pos = ax5.figbox.get_points()
        abl = body.IceAblate
        c = plt.contourf(body.Time / 1e6, lats[lats > 58], -abl.T[lats > 58],
                         20)
        plt.ylabel('Latitude')
        # plt.title(r'Ice Ablation (m year$^{-1}$)',fontsize=12)
        plt.ylim(60, 83)
        plt.yticks([60, 70, 80])
        plt.xlabel('Time (Myr)')
        if xrange == False:
            left = 0
        else:
            left = xrange[0]


#     plt.text(left,140,'\n'.join(titlestr),fontsize=20)
        if xrange:
            plt.xlim(xrange)
        clb = plt.colorbar(c,
                           cax=plt.axes([
                               pos[1, 0] + 0.01, pos[0, 1], 0.01,
                               pos[1, 1] - pos[0, 1]
                           ]))
        clb.set_label('Ice Ablation\n(m year$^{-1}$)', fontsize=12)

        plt.subplot(7, 1, 1)
        plt.plot(body.Time / 1e6,
                 obl,
                 linestyle='solid',
                 marker='None',
                 color=vplot.colors.dark_blue,
                 linewidth=2)
        plt.ylabel('Obliquity')
        plt.xticks(visible=False)
        if xrange:
            plt.xlim(xrange)

        plt.subplot(7, 1, 2)
        plt.plot(body.Time / 1e6,
                 ecc,
                 linestyle='solid',
                 marker='None',
                 color=vplot.colors.purple,
                 linewidth=2)
        plt.ylabel('Eccenticity')
        plt.xticks(visible=False)
        if xrange:
            plt.xlim(xrange)

        plt.subplot(7, 1, 3)
        plt.plot(body.Time / 1e6,
                 esinv,
                 linestyle='solid',
                 marker='None',
                 color=vplot.colors.red,
                 linewidth=2)
        plt.ylabel('CPP')
        plt.xticks(visible=False)
        if xrange:
            plt.xlim(xrange)

        if dir[ii] == '.':
            dir[ii] = 'cwd'

    if (sys.argv[1] == 'pdf'):
        plt.savefig('EarthClimateMilankovitch.pdf')
    if (sys.argv[1] == 'png'):
        plt.savefig('EarthClimateMilankovitch.png')
    if show:
        plt.show()
    else:
        plt.close()
コード例 #11
0
ファイル: filled_step.py プロジェクト: geib7592/matplotlib
                  plot_kwargs=dict(edgecolor='w', orientation='h'))
ax1.set_ylabel('counts')
ax1.set_xlabel('x')
ax2.set_xlabel('counts')
ax2.set_ylabel('x')

# work with labeled data

fig, (ax1, ax2) = plt.subplots(1,
                               2,
                               figsize=(9, 4.5),
                               tight_layout=True,
                               sharey=True)

arts = stack_hist(ax1,
                  dict_data,
                  color_cycle + hatch_cycle,
                  hist_func=hist_func)

arts = stack_hist(ax2,
                  dict_data,
                  color_cycle + hatch_cycle,
                  hist_func=hist_func,
                  labels=['set 0', 'set 3'])
ax1.xaxis.set_major_locator(mticker.MaxNLocator(5))
ax1.set_xlabel('counts')
ax1.set_ylabel('x')
ax2.set_ylabel('x')

plt.show()
コード例 #12
0
    def plot_pnl(self):

        style.use("ggplot")
        plt.figure(figsize=(10, 7))

        #get data
        total_pnl = self.get_total() / 1000000
        real_gains = self.get_real() / 1000000
        unreal_gains = self.get_unreal() / 1000000
        date = total_pnl.index.values

        ax1 = plt.subplot2grid(
            (1, 1),
            (0, 0),
            rowspan=1,
            colspan=1,
        )

        #create subplots
        ax1.plot_date(date,
                      total_pnl,
                      '-',
                      label="Total",
                      color="#0715FD",
                      linewidth=.7)  #totla pnl
        ax1.plot_date(date,
                      real_gains,
                      '--',
                      label="Realized",
                      color='#0715FD',
                      linewidth=.7)  #realized pnl
        ax1.plot_date(date,
                      unreal_gains,
                      '-',
                      label="Unrealized",
                      color='#aeabab',
                      linewidth=.7)  #unrealized pnl

        plt.title("Portfolio PnL", loc='left', color='#8b8b8b', fontsize=20)
        plt.ylabel("PnL (in millions of US$)", color='#636363', labelpad=10)

        #changes made to pnl plot(ax1)
        ax1.legend(loc=2, frameon=False, ncol=3)
        ax1.set_facecolor('w')  #change background of chart
        ax1.spines["left"].set_color('#8b8b8b')
        #formats y axis ticklabels to include commas
        ax1.get_yaxis().set_major_formatter(
            mticks.FuncFormatter(lambda x, p: format(int(x), ',')))
        #max number of tickers
        ax1.yaxis.set_major_locator(mticks.MaxNLocator(nbins=7, prune='both'))
        ax1.tick_params(axis='both', labelcolor='#636363', length=0)
        ax1.axhline(y=0, color='#636363', linewidth=.7)
        ax1.grid(False)

        #x axis tick labels for ax1
        ax1.xaxis.set_major_locator(mticks.MaxNLocator(nbins=10))
        ax1.tick_params(axis='both', labelcolor='#636363', length=0)
        ax1.set_xlim(xmin=date[0])  #set x-axis minimum
        plt.xticks(rotation=45)

        plt.tight_layout()
        plt.show()
        return
コード例 #13
0
 def test_integer(self, vmin, vmax, steps, expected):
     loc = mticker.MaxNLocator(nbins=5, integer=True, steps=steps)
     assert_almost_equal(loc.tick_values(vmin, vmax), expected)
コード例 #14
0
 def test_basic(self, vmin, vmax, expected):
     loc = mticker.MaxNLocator(nbins=5)
     assert_almost_equal(loc.tick_values(vmin, vmax), expected)
コード例 #15
0
def produce_figure_row(fig,axes,nrows,ncols,Delta_list, title_list,colorbar_unit_list,y_title_list,datapath, file_extension,cscale, row_num, \
  difference_on,pole,field_name,field_type_list,axes_direction='xy'):
    title = None
    letter_labels = np.array(
        ['(a)', '(b)', '(c)', '(d)', '(e)', '(f)', '(g)', '(h)', '(i)'])
    #for k in range(ncols):
    for k in range(ncols):
        print 'Plotting ' + field_name + ' fields for ' + Delta_list[k]
        ax = subplot(nrows, ncols, (row_num - 1) * ncols + (k + 1))
        filename = datapath + Delta_list[k] + file_extension
        #print filename
        (lat, lon, data, p_values, field, layer_interface,
         lat_lon_bounds) = load_data_from_mat_file(filename)
        if axes_direction == 'xy':
            (cscale, datamap) = plot_polar_field(lat,
                                                 lon,
                                                 data,
                                                 pole,
                                                 difference_on,
                                                 title,
                                                 p_values,
                                                 cscale,
                                                 field,
                                                 colorbar_on=False,
                                                 return_data_map=True)
        else:
            file_type = 'ocean_month_z'
            datamap=plot_vertical_section(lon,lat,data,difference_on,title,p_values,cscale,field,layer_interface,axes_direction,lat_lon_bounds,file_type,\
              colorbar_on=False,return_data_map=True)

        if row_num == 1:
            #ax.set_title(title_list[k], fontsize=18, y=1.13)
            ax.set_title(title_list[Delta_list[k]], fontsize=20, y=1.13)

        #if k==0:
        #	plt.ylabel(y_title_list[row_num-1], fontsize=18, labelpad=25)
        if k > 0:
            ax.set_yticks([])

        if k == 0 and row_num < 3:
            #ax.annotate(y_title_list[row_num-1], xy=(-0.4, 0.5), xycoords='axes fraction', fontsize=21,rotation=90,verticalalignment='center')
            #ax.annotate(field_type_list[row_num-1], xy=(-0.25, 0.5), xycoords='axes fraction', fontsize=21,rotation=90,verticalalignment='center')
            plt.ylabel(field_type_list[row_num - 1], fontsize=20, labelpad=25)

        text(1,
             1,
             letter_labels[(row_num - 1) * ncols + (k)],
             ha='right',
             va='bottom',
             transform=ax.transAxes,
             fontsize=15)
        #i_ row_num!=nrows:
        #	ax.set_xticks([])
        #else:
        #	plt.xlabel('latitude (deg)', fontsize=14)
        #	ax.set_xticks([-40 ,-60, -80])

    #Creating colorbar
    fig.subplots_adjust(right=0.8)
    tick_locator = ticker.MaxNLocator(nbins=5)
    cbar_ax = fig.add_axes(
        [0.825, 0.115 + ((nrows - row_num) * 0.435), 0.03, 0.33])
    if row_num == 1:
        ticks = np.array([-0.2, -0.1, 0, 0.1, 0.2])
    if row_num == 2:
        ticks = np.array([-0.1, -0.05, 0, 0.05, 0.1])
    #cbar=fig.colorbar(datamap, cax=cbar_ax)
    cbar = fig.colorbar(datamap, cax=cbar_ax, ticks=ticks)
    #cbar=fig.colorbar(datamap, cax=cbar_ax,ticks=tick_locator)
    cbar.set_label(colorbar_unit_list[row_num - 1], rotation=90, fontsize=20)
    cbar.ax.tick_params(labelsize=20)
コード例 #16
0
    def plotind(self,
                ind,
                subinds=None,
                upinds=None,
                downinds=None,
                masterax=None):

        ind._plotinit()

        sch = self.p.scheme

        # check subind
        subinds = subinds or []
        upinds = upinds or []
        downinds = downinds or []

        # plot subindicators on self with independent axis above
        for upind in upinds:
            self.plotind(upind)

        # Get an axis for this plot
        ax = masterax or self.newaxis(ind, rowspan=self.pinf.sch.rowsminor)

        indlabel = ind.plotlabel()

        for lineidx in range(ind.size()):
            line = ind.lines[lineidx]
            linealias = ind.lines._getlinealias(lineidx)

            lineplotinfo = getattr(ind.plotlines, '_%d' % lineidx, None)
            if not lineplotinfo:
                lineplotinfo = getattr(ind.plotlines, linealias, None)

            if not lineplotinfo:
                lineplotinfo = AutoInfoClass()

            if lineplotinfo._get('_plotskip', False):
                continue

            # Legend label only when plotting 1st line
            if masterax and not ind.plotinfo.plotlinelabels:
                label = indlabel * (lineidx == 0) or '_nolegend'
            else:
                label = lineplotinfo._get('_name', '') or linealias

            # plot data
            lplot = line.plotrange(self.pinf.xstart, self.pinf.xend)

            if not math.isnan(lplot[-1]):
                label += ' %.2f' % lplot[-1]

            plotkwargs = dict()
            linekwargs = lineplotinfo._getkwargs(skip_=True)

            if linekwargs.get('color', None) is None:
                if not lineplotinfo._get('_samecolor', False):
                    self.pinf.nextcolor(ax)
                plotkwargs['color'] = self.pinf.color(ax)

            plotkwargs.update(dict(aa=True, label=label))
            plotkwargs.update(**linekwargs)

            if ax in self.pinf.zorder:
                plotkwargs['zorder'] = self.pinf.zordernext(ax)

            pltmethod = getattr(ax, lineplotinfo._get('_method', 'plot'))
            plottedline = pltmethod(self.pinf.x, lplot, **plotkwargs)
            try:
                plottedline = plottedline[0]
            except:
                # Possibly a container of artists (when plotting bars)
                pass

            self.pinf.zorder[ax] = plottedline.get_zorder()

            if not math.isnan(lplot[-1]):
                # line has valid values, plot a tag for the last value
                self.drawtag(ax,
                             len(self.pinf.xreal),
                             lplot[-1],
                             facecolor='white',
                             edgecolor=self.pinf.color(ax))

        # plot subindicators that were created on self
        for subind in subinds:
            self.plotind(subind, subinds=self.dplotsover[subind], masterax=ax)

        if not masterax:
            # adjust margin if requested ... general of particular
            ymargin = ind.plotinfo._get('plotymargin', 0.0)
            ymargin = max(ymargin, self.pinf.sch.yadjust)
            if ymargin:
                ax.margins(y=ymargin)

            # Set specific or generic ticks
            yticks = ind.plotinfo._get('plotyticks', [])
            if not yticks:
                yticks = ind.plotinfo._get('plotyhlines', [])

            if yticks:
                ax.set_yticks(yticks)
            else:
                locator = mticker.MaxNLocator(nbins=4, prune='both')
                ax.yaxis.set_major_locator(locator)

            # Set specific hlines if asked to
            hlines = ind.plotinfo._get('plothlines', [])
            if not hlines:
                hlines = ind.plotinfo._get('plotyhlines', [])
            for hline in hlines:
                ax.axhline(hline,
                           color=self.pinf.sch.hlinescolor,
                           ls=self.pinf.sch.hlinesstyle,
                           lw=self.pinf.sch.hlineswidth)

            if self.pinf.sch.legendind and \
               ind.plotinfo._get('plotlegend', True):

                handles, labels = ax.get_legend_handles_labels()
                # Ensure that we have something to show
                if labels:
                    # Legend done here to ensure it includes all plots
                    legend = ax.legend(loc=self.pinf.sch.legendindloc,
                                       numpoints=1,
                                       frameon=False,
                                       shadow=False,
                                       fancybox=False,
                                       prop=self.pinf.prop)

                    legend.set_title(indlabel, prop=self.pinf.prop)
                    # hack: if title is set. legend has a Vbox for the labels
                    # which has a default "center" set
                    legend._legend_box.align = 'left'

        # plot subindicators on self with independent axis below
        for downind in downinds:
            self.plotind(downind)
コード例 #17
0
def run(opt='twse', debug=False, limit=0):
    maxlen = 30
    starttime = datetime.utcnow() - timedelta(days=300)
    endtime = datetime.utcnow()
    report = Report('bbands',
                    sort=[('buys', False), ('sells', False),
                          ('portfolio_value', False)],
                    limit=20)
    kwargs = {'debug': debug, 'limit': limit, 'opt': opt}
    idhandler = TwseIdDBHandler(
        **kwargs) if kwargs['opt'] == 'twse' else OtcIdDBHandler(**kwargs)
    for stockid in idhandler.stock.get_ids():
        try:
            kwargs = {
                'opt': opt,
                'targets': ['stock', 'future', 'credit'],
                'starttime': starttime,
                'endtime': endtime,
                'stockids': [stockid],
                'traderids': [],
                'base': 'stock',
                'callback': None,
                'limit': 1,
                'debug': debug
            }
            panel, dbhandler = collect_hisframe(**kwargs)
            if len(panel[stockid].index) < maxlen:
                continue

            sim_params = SimulationParameters(
                period_start=panel[stockid].index[0],
                period_end=panel[stockid].index[-1],
                data_frequency='daily',
                emission_rate='daily')

            bbands = BBands(dbhandler=dbhandler,
                            debug=debug,
                            sim_params=sim_params)
            results = bbands.run(panel).fillna(0)
            risks = bbands.perf_tracker.handle_simulation_end()
            report.collect(stockid, results, risks)
            print "%s pass" % (stockid)
        except:
            print traceback.format_exc()
            continue

    if report.report.empty:
        return

    # report summary
    stream = report.summary(dtype='html')
    report.write(stream, 'bbands.html')

    for stockid in report.iter_symbol():
        stream = report.iter_report(stockid, dtype='html')
        report.write(stream, "bbands_%s.html" % (stockid))

    for stockid in report.iter_symbol():
        perf = report.pool[stockid]
        dates = [date2num(i) for i in perf.index[maxlen:]]
        quotes = [
            perf[label][maxlen:].values
            for label in ['open', 'high', 'low', 'close']
        ]
        quotes = zip(*([dates] + quotes))

        fig = plt.figure(facecolor='#07000d')

        ax1 = plt.subplot2grid((6, 4), (1, 0),
                               rowspan=4,
                               colspan=4,
                               axisbg='#07000d')
        candlestick_ohlc(ax1,
                         quotes,
                         width=.6,
                         colorup='#53c156',
                         colordown='#ff1717')

        ax1.plot(dates,
                 perf['upper'][maxlen:].values,
                 '#e1edf9',
                 label='upper',
                 linewidth=1.5)
        ax1.plot(dates,
                 perf['middle'][maxlen:].values,
                 '#e1edf9',
                 label='middle',
                 linewidth=1.5)
        ax1.plot(dates,
                 perf['lower'][maxlen:].values,
                 '#e1edf9',
                 label='lower',
                 linewidth=1.5)

        ax1.grid(True, color='w')
        ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
        ax1.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
        ax1.yaxis.label.set_color("w")
        ax1.spines['bottom'].set_color("#5998ff")
        ax1.spines['top'].set_color("#5998ff")
        ax1.spines['left'].set_color("#5998ff")
        ax1.spines['right'].set_color("#5998ff")
        ax1.tick_params(axis='y', colors='w')
        plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))
        ax1.tick_params(axis='x', colors='w')
        plt.ylabel('Stock price and Volume')

        bbLeg = plt.legend(loc=9,
                           ncol=2,
                           prop={'size': 7},
                           fancybox=True,
                           borderaxespad=0.)
        bbLeg.get_frame().set_alpha(0.4)
        textEd = pylab.gca().get_legend().get_texts()
        pylab.setp(textEd[0:6], color='w')

        ax1v = ax1.twinx()
        ax1v.fill_between(dates,
                          0,
                          perf['volume'][maxlen:].values,
                          facecolor='#00ffe8',
                          alpha=.4)
        ax1v.axes.yaxis.set_ticklabels([])
        ax1v.grid(False)
        ###Edit this to 3, so it's a bit larger
        ax1v.set_ylim(0, 3 * perf['volume'][maxlen:].values.max())
        ax1v.spines['bottom'].set_color("#5998ff")
        ax1v.spines['top'].set_color("#5998ff")
        ax1v.spines['left'].set_color("#5998ff")
        ax1v.spines['right'].set_color("#5998ff")
        ax1v.tick_params(axis='x', colors='w')
        ax1v.tick_params(axis='y', colors='w')

        plt.setp(ax1.get_xticklabels(), visible=False)
        plt.subplots_adjust(left=.09,
                            bottom=.14,
                            right=.94,
                            top=.95,
                            wspace=.20,
                            hspace=0)
        plt.gcf().set_size_inches(18, 8)
        plt.savefig("bbands_%s.png" % (stockid), facecolor=fig.get_facecolor())
コード例 #18
0
    def plotdata(self, data, indicators):
        for ind in indicators:
            upinds = self.dplotsup[ind]
            for upind in upinds:
                self.plotind(upind,
                             subinds=self.dplotsover[upind],
                             upinds=self.dplotsup[upind],
                             downinds=self.dplotsdown[upind])

        # set the x axis data (if needed)
        self.setxdata(data)

        opens = data.open.plotrange(self.pinf.xstart, self.pinf.xend)
        highs = data.high.plotrange(self.pinf.xstart, self.pinf.xend)
        lows = data.low.plotrange(self.pinf.xstart, self.pinf.xend)
        closes = data.close.plotrange(self.pinf.xstart, self.pinf.xend)
        volumes = data.volume.plotrange(self.pinf.xstart, self.pinf.xend)

        vollabel = 'Volume'
        if self.pinf.sch.volume and self.pinf.sch.voloverlay:
            volplot = self.plotvolume(data, opens, highs, lows, closes,
                                      volumes, vollabel)
            axvol = self.pinf.daxis[data.volume]
            ax = axvol.twinx()
            self.pinf.daxis[data] = ax
        else:
            ax = self.newaxis(data, rowspan=self.pinf.sch.rowsmajor)

        datalabel = ''
        dataname = ''
        if hasattr(data, '_name') and data._name:
            datalabel += data._name

        if hasattr(data, '_compression') and \
           hasattr(data, '_timeframe'):
            tfname = TimeFrame.getname(data._timeframe, data._compression)
            datalabel += ' (%d %s)' % (data._compression, tfname)

        datalabel += ' O:%.2f H:%2.f L:%.2f C:%.2f' % \
                     (opens[-1], highs[-1], lows[-1], closes[-1])

        if self.pinf.sch.style.startswith('line'):
            plotted = plot_lineonclose(ax,
                                       self.pinf.x,
                                       closes,
                                       color=self.pinf.sch.loc,
                                       label=datalabel)
        else:
            if self.pinf.sch.style.startswith('candle'):
                plotted = plot_candlestick(ax,
                                           self.pinf.x,
                                           opens,
                                           highs,
                                           lows,
                                           closes,
                                           colorup=self.pinf.sch.barup,
                                           colordown=self.pinf.sch.bardown,
                                           label=datalabel)

            elif self.pinf.sch.style.startswith('bar') or True:
                # final default option -- should be "else"
                plotted = plot_ohlc(ax,
                                    self.pinf.x,
                                    opens,
                                    highs,
                                    lows,
                                    closes,
                                    colorup=self.pinf.sch.barup,
                                    colordown=self.pinf.sch.bardown,
                                    label=datalabel)

        self.pinf.zorder[ax] = plotted[0].get_zorder()

        # Code to place a label at the right hand side with the last value
        self.drawtag(ax,
                     len(self.pinf.xreal),
                     closes[-1],
                     facecolor='white',
                     edgecolor=self.pinf.sch.loc)

        ax.yaxis.set_major_locator(mticker.MaxNLocator(prune='both'))
        # make sure "over" indicators do not change our scale
        ax.set_ylim(ax.get_ylim())

        if self.pinf.sch.volume:
            if not self.pinf.sch.voloverlay:
                self.plotvolume(data, opens, highs, lows, closes, volumes,
                                vollabel)
            else:
                # Prepare overlay scaling/pushup or manage own axis
                if self.pinf.sch.volpushup:
                    # push up overlaid axis by lowering the bottom limit
                    axbot, axtop = ax.get_ylim()
                    axbot *= (1.0 - self.pinf.sch.volpushup)
                    ax.set_ylim(axbot, axtop)

        for ind in indicators:
            self.plotind(ind, subinds=self.dplotsover[ind], masterax=ax)

        handles, labels = ax.get_legend_handles_labels()
        if handles:
            # put data and volume legend entries in the 1st positions
            # because they are "collections" they are considered after Line2D
            # for the legend entries, which is not our desire
            if self.pinf.sch.volume and self.pinf.sch.voloverlay:
                if volplot:
                    # even if volume plot was requested, there may be no volume
                    labels.insert(0, vollabel)
                    handles.insert(0, volplot)

            didx = labels.index(datalabel)
            labels.insert(0, labels.pop(didx))
            handles.insert(0, handles.pop(didx))

            # feed handles/labels to legend to get right order
            legend = ax.legend(handles,
                               labels,
                               loc='upper left',
                               frameon=False,
                               shadow=False,
                               fancybox=False,
                               prop=self.pinf.prop,
                               numpoints=1,
                               ncol=1)

            # hack: if title is set. legend has a Vbox for the labels
            # which has a default "center" set
            legend._legend_box.align = 'left'

        for ind in indicators:
            downinds = self.dplotsdown[ind]
            for downind in downinds:
                self.plotind(downind,
                             subinds=self.dplotsover[downind],
                             upinds=self.dplotsup[downind],
                             downinds=self.dplotsdown[downind])
コード例 #19
0
def gen_eq_movie(allfiles,
                 my_rank,
                 ncpu,
                 quantity_code=1,
                 dpi=300,
                 xypix=512,
                 minval=-150,
                 maxval=150,
                 title_text='',
                 cbar_text='',
                 remove_mean=True):

    from rayleigh_diagnostics import Equatorial_Slices
    import numpy
    import matplotlib.pyplot as plt
    from matplotlib import ticker, font_manager

    nfiles = len(allfiles)
    dfiles = nfiles // ncpu
    my_start = my_rank * dfiles

    fmod = nfiles % ncpu
    if (my_rank < fmod):
        my_start = my_start + my_rank
        dfiles = dfiles + 1
    else:
        my_start = my_start + fmod
    my_end = my_start + dfiles

    #Before making the plots, set up the grid
    es = Equatorial_Slices(allfiles[0], path='')

    nr = es.nr
    nphi = es.nphi
    r = es.radius / numpy.max(es.radius)
    phi = numpy.zeros(nphi + 1, dtype='float64')
    phi[0:nphi] = es.phi
    phi[nphi] = numpy.pi * 2  # For display purposes, it is best to have a redunant data point at 0,2pi

    #We need to generate a cartesian grid of x-y coordinates (both X & Y are 2-D)
    radius_matrix, phi_matrix = numpy.meshgrid(r, phi)
    X = radius_matrix * numpy.cos(phi_matrix)
    Y = radius_matrix * numpy.sin(phi_matrix)

    qind = es.lut[quantity_code]
    field = numpy.zeros((nphi + 1, nr), dtype='float64')

    colormap = 'jet'
    colormap = 'RdYlBu_r'

    for i in range(my_start, my_end):
        if (my_rank == 0):
            print('  Processing file ', i - my_start + 1, 'of',
                  my_end - my_start)
        f = allfiles[i]
        es = Equatorial_Slices(f, path='')
        niter = es.niter

        for j in range(niter):
            jstring = "{:0>8d}".format(es.iters[j])
            savefile = 'eq_pngs/' + jstring + '.png'

            field[0:nphi, :] = es.vals[:, :, qind, j]
            field[nphi, :] = field[0, :]  #replicate phi=0 values at phi=2pi

            #remove the m=0 mean if desired (usually a good idea, but not always)
            if (remove_mean):
                for i in range(nr):
                    the_mean = numpy.mean(field[:, i])
                    field[:, i] = field[:, i] - the_mean

            #Plot

            xyin = xypix / dpi
            fig, ax = plt.subplots(figsize=(xyin, xyin), dpi=dpi)
            tsize = 10  # title font size
            cbfsize = 6  # colorbar font size

            img = ax.pcolormesh(X,
                                Y,
                                field,
                                cmap=colormap,
                                vmin=minval,
                                vmax=maxval)

            ax.axis('equal'
                    )  # Ensure that x & y axis ranges have a 1:1 aspect ratio
            ax.axis('off')  # Do not plot x & y axes

            # Plot bounding circles
            ax.plot(r[nr - 1] * numpy.cos(phi),
                    r[nr - 1] * numpy.sin(phi),
                    color='black')  # Inner circle
            ax.plot(r[0] * numpy.cos(phi),
                    r[0] * numpy.sin(phi),
                    color='black')  # Outer circle

            ax.set_title(title_text, fontsize=tsize)
            #colorbar ...
            cbar = plt.colorbar(img,
                                orientation='horizontal',
                                shrink=0.5,
                                aspect=10,
                                ax=ax)
            cbar.set_label(cbar_text)

            tick_locator = ticker.MaxNLocator(nbins=5)
            cbar.locator = tick_locator
            cbar.update_ticks()
            cbar.ax.tick_params(labelsize=cbfsize)  #font size for the ticks

            t = cbar.ax.xaxis.label
            t.set_fontsize(cbfsize)  # font size for the axis title

            plt.savefig(savefile)
            plt.close()
コード例 #20
0
    def data(self):
        #120 candlov max za zapros
        #BTC,ETH,XRP,EOS,ETH,OMG,BCH,IOTA,LTC,NEO,XRP,ELF,EO
        #url = "https://api.bitfinex.com/v2/candles/trade:5m:tBTCUSD/hist?start=1497887100000&end=1497922800000&limit=1000"
        url = "https://api.bitfinex.com/v2/candles/trade:1D:tETCUSD/hist?start=1502496000000&limit=1000"
        #start = datetime.utcnow()

        response = requests.request("GET", url)

        time.sleep(1)

        with open('myRest.ts', 'w') as file:

            #for i in range(len(qq[0][0])):
            #stri = (str(qq[0][0][i]))
            file.write(
                (response.text.replace('],[',
                                       '\n').replace('[[',
                                                     '').replace(']]', '')))
            #file.write("\n")

        time.sleep(1)

        loaded = pd.read_csv(
            'myRest.ts',
            delimiter=',',
            names=['Timestamp', 'Open', 'Close', 'High', 'Low', 'Volume'])

        loaded = loaded[::-1]

        #loaded = indicators.randomwalk(loaded)

        #loaded.reindex(indeex=loaded.index[::-1])

        loaded = indicators.HA(loaded)

        #loaded = indicators.chaikin_oscillator(loaded)
        #loaded = indicators.chaikin_oscillator2(loaded)

        #loaded = indicators.moving_average(loaded,10)
        #loaded = indicators.exponential_moving_average(loaded,10)

        #loaded = indicators.acc_dist(loaded)
        #loaded = indicators.chaikin_oscillator(loaded)

        chaikin = tb.ADOSC(high=loaded['HA_High'].values,
                           low=loaded['HA_Low'].values,
                           close=loaded['HA_Close'].values,
                           volume=loaded['Volume'].values,
                           fastperiod=3,
                           slowperiod=10)
        #loaded = indicators.chaikin_oscillator2(loaded)

        loaded = loaded.join(pd.Series(chaikin, name='TALib_Chaikin'))

        #upperband, middleband, lowerband = tb.BBANDS(close=loaded['Close'].values, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0)

        #loaded = loaded.join(pd.Series(upperband,name='BOLLINGER_upper'))
        #loaded = loaded.join(pd.Series(middleband,name='BOLLINGER_middle'))
        #loaded = loaded.join(pd.Series(lowerband,name='BOLLINGER_lower'))

        #loaded = indicators.accumulation_distribution(loaded,0)

        loaded = indicators.nulltest(loaded)

        #loaded = indicators.backtest(loaded)#backtest(loaded)
        #loaded = indicators.backtest_bull(loaded)
        #loaded=np.loadtxt('myRest.ts',delimiter=',')#,ndmin=2)

        #logging.info(type(loaded))

        #logging.info(loaded['Graph'].values)

        #logging.info(loaded.get_value(999, 'Balance'))

        with open('backtest', 'w') as file:
            file.write(loaded.to_string())

        ########################################################### PLOT NUMBER ONE - GRAPH

        #fig = plt.figure()
        ax1 = plt.subplot2grid((1, 1), (0, 0))

        timestamps = loaded['Timestamp'].values
        timestamps = np.multiply(timestamps, 0.001)

        balancep = loaded['Balance'].values
        openp = loaded['HA_Open'].values
        highp = loaded['HA_High'].values
        lowp = loaded['HA_Low'].values
        closep = loaded['HA_Close'].values
        volumep = loaded['Volume'].values

        x = 0
        ohlc = []
        datep = [
            mdates.date2num(dt.datetime.fromtimestamp(ts)) for ts in timestamps
        ]
        y = len(datep)

        sizemultiplier = 3 * 8

        while x < y:
            append_me = datep[x], openp[x], highp[x], lowp[x], closep[
                x], volumep[x]
            ohlc.append(append_me)

            if loaded.at[x, 'Graph'] == 1:
                plt.text(datep[x],
                         closep[x] + 0.4 * sizemultiplier,
                         "o",
                         fontsize=12,
                         color='k')
                plt.plot([datep[x], datep[x]],
                         [closep[x], closep[x] + 0.35 * sizemultiplier],
                         color='k',
                         linestyle='-',
                         linewidth=2)
            else:
                if loaded.at[x, 'Graph'] == -1:
                    if balancep[x] - balancep[x - 1] > 0:
                        coloris = 'g'
                    else:
                        coloris = 'r'
                    plt.text(datep[x],
                             closep[x] + 0.4 * sizemultiplier,
                             "c" +
                             str(round(balancep[x] - balancep[x - 1], 3)),
                             fontsize=12,
                             color=coloris)
                    plt.plot([datep[x], datep[x]],
                             [closep[x], closep[x] + 0.35 * sizemultiplier],
                             color='k',
                             linestyle='-',
                             linewidth=2)
                else:
                    if loaded.at[x, 'Graph'] == 2:
                        plt.text(datep[x],
                                 closep[x] + 0.4 * sizemultiplier,
                                 "oS",
                                 fontsize=12,
                                 color='k')
                        plt.plot(
                            [datep[x], datep[x]],
                            [closep[x], closep[x] + 0.35 * sizemultiplier],
                            color='k',
                            linestyle='-',
                            linewidth=2)
                    else:
                        if loaded.at[x, 'Graph'] == -2:
                            if balancep[x] - balancep[x - 1] < 0:
                                coloris = 'r'
                            else:
                                coloris = 'g'
                            plt.text(
                                datep[x],
                                closep[x] + 0.4 * sizemultiplier,
                                "cS" +
                                str(round(balancep[x] - balancep[x - 1], 3)),
                                fontsize=12,
                                color=coloris)
                            plt.plot(
                                [datep[x], datep[x]],
                                [closep[x], closep[x] + 0.35 * sizemultiplier],
                                color='k',
                                linestyle='-',
                                linewidth=2)
            x += 1

        candlestick_ohlc(ax1,
                         ohlc,
                         width=0.02 * sizemultiplier,
                         colorup='#77d879',
                         colordown='#db3f3f')

        plt.plot_date(datep, balancep, fmt='-')

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

        ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
        ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
        ax1.grid(True)

        plt.xlabel('Date')
        plt.ylabel('Price')
        plt.title('ETC/USD, 3h')
        plt.legend()
        plt.subplots_adjust(left=0.09,
                            bottom=0.20,
                            right=0.94,
                            top=0.90,
                            wspace=0.2,
                            hspace=0)
        plt.show()

        ########################################################### PLOT NUMBER TWO - REVENUE
        '''
コード例 #21
0
#3 plot the SAR data
# Let's plot the SAR data image nicely...
from matplotlib import ticker
import cartopy.crs as ccrs

SAR_C = xr.open_rasterio('/content/sentinel 1_data.tif')
array_input = SAR_C

plt.figure(figsize=(9, 6))
ax1 = plt.axes(projection=ccrs.Robinson())
ax1.coastlines()
ax1.add_feature(cartopy.feature.OCEAN)
ax1.gridlines(draw_labels=True)

p1 = array_input.plot(ax=ax1,
                      vmin=-24,
                      vmax=10,
                      cmap='RdBu_r',
                      transform=ccrs.PlateCarree(),
                      add_colorbar=False)

plt.title('sar for 15/Mar/2017 (Spain)')
ax_cb = plt.axes([0.25, 0.05, 0.525, 0.02])
tick_locator = ticker.MaxNLocator(nbins=10)
cb = plt.colorbar(p1, cax=ax_cb, orientation='horizontal')
cb.locator = tick_locator
cb.update_ticks()
cb.ax.set_xlabel(r'$\overline{\gamma^o}$ [dB]')
コード例 #22
0
ファイル: plotter.py プロジェクト: tkkr6895/QATM
                               colspan=4,
                               axisbg='#07000d')
        candlestick(ax1,
                    newAr[-SP:],
                    width=.6,
                    colorup='#53c156',
                    colordown='#ff1717')

        Label1 = str(MA1) + ' SMA'
        Label2 = str(MA2) + ' SMA'

        ax1.plot(date[-SP:], Av1[-SP:], '#e1edf9', label=Label1, linewidth=1.5)
        ax1.plot(date[-SP:], Av2[-SP:], '#4ee6fd', label=Label2, linewidth=1.5)

        ax1.grid(True, color='w')
        ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
        ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
        ax1.yaxis.label.set_color("w")
        ax1.spines['bottom'].set_color("#5998ff")
        ax1.spines['top'].set_color("#5998ff")
        ax1.spines['left'].set_color("#5998ff")
        ax1.spines['right'].set_color("#5998ff")
        ax1.tick_params(axis='y', colors='w')
        plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))
        ax1.tick_params(axis='x', colors='w')
        plt.ylabel('Stock price and Volume')

        maLeg = plt.legend(loc=9,
                           ncol=2,
                           prop={'size': 7},
                           fancybox=True,
コード例 #23
0
#plot results
if exudynTestGlobals.useGraphics:
    import matplotlib.pyplot as plt
    import matplotlib.ticker as ticker

    symStr = ['r-', 'g-', 'b-', 'k-']
    symStr2 = ['r--', 'g--', 'b--', 'k--']
    for i in range(4):
        s = str(i)
        data = np.loadtxt('solution/rollingDiscTrail' + s + '.txt',
                          comments='#',
                          delimiter=',')
        plt.plot(data[:, 1], data[:, 2], symStr[i],
                 label='trail wheel' + s)  #x/y coordinates of trail
        data = np.loadtxt('solution/rollingDiscForce' + s + '.txt',
                          comments='#',
                          delimiter=',')
        #plt.plot(data[:,0], data[:,2], symStr[i],label='wheel force y'+s)
        #data = np.loadtxt('solution/rollingDiscAngVelLocal'+s+'.txt', comments='#', delimiter=',')
        #plt.plot(data[:,0], data[:,1], symStr2[i],label='wheel ang vel'+s)

    ax = plt.gca()  # get current axes
    ax.grid(True, 'major', 'both')
    ax.xaxis.set_major_locator(
        ticker.MaxNLocator(10))  #use maximum of 8 ticks on y-axis
    ax.yaxis.set_major_locator(
        ticker.MaxNLocator(10))  #use maximum of 8 ticks on y-axis
    plt.tight_layout()
    plt.legend()
    plt.show()
コード例 #24
0
                       colspan=4,
                       facecolor='#07000d')  # 第6行第1列起,占1行4列
ax1.plot(plot_mat.time[100:160].values,
         plot_mat.macd[100:160].values,
         color='#4ee6fd',
         linewidth=2)  # MACD线
ax1.plot(plot_mat.time[100:160].values,
         plot_mat.dea9[100:160].values,
         color='#e1edf9',
         linewidth=1)  # DEA线
ax1.fill_between(plot_mat.time[100:160].values,
                 plot_mat.macd[100:160].values - plot_mat.dea9[100:160].values,
                 0,
                 alpha=0.5,
                 facecolors='#00ffe8')  # 填充差值
ax1.yaxis.set_major_locator(mticker.MaxNLocator())  # 设置纵坐标
ax1.spines['bottom'].set_color('#5998ff')
ax1.spines['top'].set_color('#5998ff')
ax1.spines['left'].set_color('#5998ff')
ax1.spines['right'].set_color('#5998ff')
ax1.tick_params(axis='y', colors='w')
ax1.tick_params(axis='x', colors='w')
plt.ylabel('MACD', color='w')

plt.plot()
plt.show()

#绘制一个汇总图
fig = plt.figure(facecolor='#07000d', figsize=(15, 10))
ax = plt.subplot2grid((6, 4), (1, 0),
                      rowspan=4,
コード例 #25
0
 def graph_data(self, istock, MA1, MA2):
     """
     Use this to dynamically pull a stock.
     """
     try:
         print('Currently Pulling', stock)
         urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=10y/csv'
         stockFile =[]
         try:
             sourceCode = urllib.request.urlopen(urlToVisit).read().decode()
             splitSource = sourceCode.split('\n')
             for eachLine in splitSource:
                 splitLine = eachLine.split(',')
                 if len(splitLine)==6:
                     if 'values' not in eachLine:
                         stockFile.append(eachLine)
         except Exception as e:
             print(str(e), 'failed to organize pulled data.')
     except Exception as e:
         print(str(e), 'failed to pull pricing data')
     try:
         date, closep, highp, lowp, openp, volume = np.loadtxt(
             stockFile,
             delimiter=',', 
             unpack=True,                                           
             converters={ 0: self.bytes_per_date_to_num('%Y%m%d')}
             )
         x = 0
         y = len(date)
         newAr = []
         while x < y:
             appendLine = date[x],openp[x],highp[x],lowp[x],closep[x],volume[x]
             newAr.append(appendLine)
             x+=1
         Av1 = self.moving_average(closep, MA1)
         Av2 = self.moving_average(closep, MA2)
         SP = len(date[MA2-1:])
         fig = plt.figure(facecolor='#07000d')
         ax1 = plt.subplot2grid((6,4), (1,0), rowspan=4, colspan=4, axisbg='#07000d')
         candlestick_ohlc(ax1, newAr[-SP:], width=.6, colorup='#53c156', colordown='#ff1717')
         Label1 = str(MA1)+' SMA'
         Label2 = str(MA2)+' SMA'
         ax1.plot(date[-SP:],Av1[-SP:],'#e1edf9',label=Label1, linewidth=1.5)
         ax1.plot(date[-SP:],Av2[-SP:],'#4ee6fd',label=Label2, linewidth=1.5)
         ax1.grid(True, color='w')
         ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
         ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
         ax1.yaxis.label.set_color("w")
         ax1.spines['bottom'].set_color("#5998ff")
         ax1.spines['top'].set_color("#5998ff")
         ax1.spines['left'].set_color("#5998ff")
         ax1.spines['right'].set_color("#5998ff")
         ax1.tick_params(axis='y', colors='w')
         plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))
         ax1.tick_params(axis='x', colors='w')
         plt.ylabel('Stock price and Volume')
         maLeg = plt.legend(
             loc=9, 
             ncol=2, 
             prop={'size':7},
             fancybox=True, 
             borderaxespad=0.0
             )
         maLeg.get_frame().set_alpha(0.4)
         textEd = pylab.gca().get_legend().get_texts()
         pylab.setp(textEd[0:5], color = 'w')
         volumeMin = 0
         ax0 = plt.subplot2grid((6,4), (0,0), sharex=ax1, rowspan=1, colspan=4, axisbg='#07000d')
         rsi = self.rsi(closep)
         rsiCol = '#c1f9f7'
         posCol = '#386d13'
         negCol = '#8f2020'
         ax0.plot(date[-SP:], rsi[-SP:], rsiCol, linewidth=1.5)
         ax0.axhline(70, color=negCol)
         ax0.axhline(30, color=posCol)
         ax0.fill_between(date[-SP:], rsi[-SP:], 70, where=(rsi[-SP:]>=70), facecolor=negCol, edgecolor=negCol, alpha=0.5)
         ax0.fill_between(date[-SP:], rsi[-SP:], 30, where=(rsi[-SP:]<=30), facecolor=posCol, edgecolor=posCol, alpha=0.5)
         ax0.set_yticks([30,70])
         ax0.yaxis.label.set_color("w")
         ax0.spines['bottom'].set_color("#5998ff")
         ax0.spines['top'].set_color("#5998ff")
         ax0.spines['left'].set_color("#5998ff")
         ax0.spines['right'].set_color("#5998ff")
         ax0.tick_params(axis='y', colors='w')
         ax0.tick_params(axis='x', colors='w')
         plt.ylabel('RSI')
         ax1v = ax1.twinx()
         ax1v.fill_between(date[-SP:],volumeMin, volume[-SP:], facecolor='#00ffe8', alpha=.4)
         ax1v.axes.yaxis.set_ticklabels([])
         ax1v.grid(False)
         ax1v.set_ylim(0, 3*volume.max())
         ax1v.spines['bottom'].set_color("#5998ff")
         ax1v.spines['top'].set_color("#5998ff")
         ax1v.spines['left'].set_color("#5998ff")
         ax1v.spines['right'].set_color("#5998ff")
         ax1v.tick_params(axis='x', colors='w')
         ax1v.tick_params(axis='y', colors='w')
         ax2 = plt.subplot2grid(
             (6, 4), 
             (5, 0), 
             sharex=ax1, 
             rowspan=1, 
             colspan=4, 
             axisbg='#07000d'
             )
         fillcolor = '#00ffe8'
         # nslow = 26
         # nfast = 12
         nema = 9
         _, _, macd = self.compute_macd(closep)
         ema9 = self.exp_moving_average(macd, nema)
         ax2.plot(date[-SP:], macd[-SP:], color='#4ee6fd', lw=2)
         ax2.plot(date[-SP:], ema9[-SP:], color='#e1edf9', lw=1)
         ax2.fill_between(
             date[-SP:], 
             macd[-SP:]-ema9[-SP:], 
             0, 
             alpha=0.5, 
             facecolor=fillcolor, 
             edgecolor=fillcolor
             )
         plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))
         ax2.spines['bottom'].set_color("#5998ff")
         ax2.spines['top'].set_color("#5998ff")
         ax2.spines['left'].set_color("#5998ff")
         ax2.spines['right'].set_color("#5998ff")
         ax2.tick_params(axis='x', colors='w')
         ax2.tick_params(axis='y', colors='w')
         plt.ylabel('MACD', color='w')
         ax2.yaxis.set_major_locator(mticker.MaxNLocator(nbins=5, prune='upper'))
         for label in ax2.xaxis.get_ticklabels():
             label.set_rotation(45)
         plt.suptitle(stock.upper(),color='w')
         plt.setp(ax0.get_xticklabels(), visible=False)
         plt.setp(ax1.get_xticklabels(), visible=False)
         ax1.annotate(
             'Big news!',
             (date[510], Av1[510]),
             xytext=(0.8, 0.9), 
             textcoords='axes fraction',
             arrowprops=dict(facecolor='white', shrink=0.05),
             fontsize=14, 
             color = 'w',
             horizontalalignment='right', 
             verticalalignment='bottom'
             )
         plt.subplots_adjust(
             left=.09, 
             bottom=.14, 
             right=.94, 
             top=.95, 
             wspace=.20, 
             hspace=0
             )
         plt.show()
         fig.savefig('example.png', facecolor=fig.get_facecolor())
     except Exception as e:
         print('main loop', str(e))
コード例 #26
0
 def createPage(self):  
     ds=g.sday
     de=g.eday
     stockn=g.stock
     matplotlib.use('TkAgg')
     # df1 = jq.get_price(stockn,start_date=ds,end_date=de, frequency='daily') # 聚宽获取股票数据
     # df1 = ts.get_hist_data(stockn,start=ds,end=de)   # tushare获取股票 数据
     # df1 = Getdailyfromtscode(stockn,ds,de)
     df1 = get_data(stockn, ds, de)
     df1['trade_date'] = mdates.date2num(df1['trade_date'])
     df2=df1.copy()
     # df2.dropna(inplace=True)
     # df2.insert(0,'date',df2.index)
     df2 = df2.reset_index()
     # df2 = data_clean(df2)
     print(df1)
     print(df2)
     days=df2
     g.df=df2
     MA1 = g.MA1
     MA2 = g.MA2
     Av1=mylib.G_MA(days['close'],MA1)
     Av2=mylib.G_MA(days['close'],MA2)
     SP = len(days.trade_date.values[MA2-1:])
     SP1 = len(days.trade_date.values[MA1-1:])
     fig = plt.figure(facecolor='#07000d',figsize=(7,4))
     ax1 = plt.subplot2grid((7,4), (0,0), rowspan=4, colspan=4, facecolor='#07000d')
     daysreshape = days.reset_index()
     print(daysreshape)
     # daysreshape['trade_date']=mdates.date2num(daysreshape['trade_date'].astype(dt.date))
     daysreshape = daysreshape.reindex(columns=['date','open','high','low','close'])
     candlestick_ohlc(ax1, daysreshape.values, width=.6, colorup='#ff1717', colordown='#53c156')
     # candlestick_ohlc(ax1, daysreshape.values, width=.6, colorup='#ff1717', colordown='#53c156')
     Label1 = str(MA1)+' MA'
     Label2 = str(MA2)+' MA'
     ax1.plot(days.trade_date.values,Av1,'#e1edf9',label=Label1, linewidth=1.5)
     ax1.plot(days.trade_date.values[-SP:],Av2[-SP:],'#4ee6fd',label=Label2, linewidth=1.5)
     ax1.grid(True, color='r')
     ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
     ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
     ax1.yaxis.label.set_color("w")
     ax1.spines['bottom'].set_color("#5998ff")
     ax1.spines['top'].set_color("#5998ff")
     ax1.spines['left'].set_color("#5998ff")
     ax1.spines['right'].set_color("#5998ff")
     ax1.tick_params(axis='y', colors='w')
     plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))
     ax1.tick_params(axis='x', colors='w')
     plt.ylabel('Stock price')
     ax1v = ax1.twinx()
     ax1v.spines['bottom'].set_color("#5998ff")
     ax1v.spines['top'].set_color("#5998ff")
     ax1v.spines['left'].set_color("#5998ff")
     ax1v.spines['right'].set_color("#5998ff")
     ax1v.tick_params(axis='x', colors='w')
     ax1v.tick_params(axis='y', colors='w')
     ax0 = plt.subplot2grid((7,4), (4,0),sharex=ax1,rowspan=1, colspan=4, facecolor='#07000d')
     v1=mylib.G_MA(days['vol'],g.MA1)
     v2=mylib.G_MA(days['vol'],g.MA2)
     v3=mylib.G_MA(days['vol'],g.MA3)
     rsiCol = '#c1f9f7'
     posCol = '#386d13'
     negCol = '#8f2020'
     ax0.plot(days.trade_date.values, v1, rsiCol, linewidth=1)
     ax0.plot(days.trade_date.values, v2, posCol, linewidth=1)
     ax0.bar(days.trade_date.values,days.vol.values, facecolor='yellow', alpha=.4)
     ax0.yaxis.label.set_color("w")
     ax0.spines['bottom'].set_color("#5998ff")
     ax0.spines['top'].set_color("#5998ff")
     ax0.spines['left'].set_color("#5998ff")
     ax0.spines['right'].set_color("#5998ff")
     ax0.tick_params(axis='y', colors='w')
     ax0.tick_params(axis='x', colors='w')
     ax0.yaxis.set_major_locator(mticker.MaxNLocator(nbins=4, prune='upper'))#plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(nbins=4,prune='upper'))
     ax0.tick_params(axis='x', colors='w')
     plt.ylabel('volume')                     
     if g.index=='KDJ' :
         mydraw.draw_KDJ(ax1,days,9,3,3)
     if g.index=='MACD' :
         mydraw.draw_MACD(ax1,days,12,26,9)
     if g.index=='RSI' :
         mydraw.draw_RSI(ax1,days,6,12,24)
     if g.index=='OBV' :
         mydraw.draw_OBV(ax1,days,6,12)               
     plt.suptitle(stockn,color='w')
     plt.setp(ax0.get_xticklabels(), visible=False)
     plt.setp(ax1.get_xticklabels(), visible=False)
     plt.subplots_adjust(left=.04, bottom=.04, right=.96, top=.96, wspace=.15, hspace=0)
     self.canvas =FigureCanvasTkAgg(fig, master=self.root)
     toolbar =NavigationToolbar2Tk(self.canvas, self.root)
     toolbar.update()
     self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
コード例 #27
0
def plot_error_map(backend, figsize=(12, 9), show_title=True):
    """Plots the error map of a given backend.

    Args:
        backend (IBMQBackend): Given backend.
        figsize (tuple): Figure size in inches.
        show_title (bool): Show the title or not.

    Returns:
        Figure: A matplotlib figure showing error map.

    Raises:
        VisualizationError: Input is not IBMQ backend.

    Example:
        .. jupyter-execute::
            :hide-code:
            :hide-output:

            from qiskit.test.ibmq_mock import mock_get_backend
            mock_get_backend('FakeVigo')

        .. jupyter-execute::

            from qiskit import QuantumCircuit, execute, IBMQ
            from qiskit.visualization import plot_error_map
            %matplotlib inline

            IBMQ.load_account()
            provider = IBMQ.get_provider(hub='ibm-q')
            backend = provider.get_backend('ibmq_vigo')
            plot_error_map(backend)
    """
    color_map = cm.viridis

    props = backend.properties().to_dict()
    config = backend.configuration().to_dict()

    n_qubits = config['n_qubits']

    # U2 error rates
    single_gate_errors = [0] * n_qubits
    for gate in props['gates']:
        if gate['gate'] == 'u2':
            _qubit = gate['qubits'][0]
            single_gate_errors[_qubit] = gate['parameters'][0]['value']

    # Convert to percent
    single_gate_errors = 100 * np.asarray(single_gate_errors)
    avg_1q_err = np.mean(single_gate_errors)

    single_norm = matplotlib.colors.Normalize(vmin=min(single_gate_errors),
                                              vmax=max(single_gate_errors))
    q_colors = [color_map(single_norm(err)) for err in single_gate_errors]

    cmap = config['coupling_map']

    directed = False
    if n_qubits < 20:
        for edge in cmap:
            if not [edge[1], edge[0]] in cmap:
                directed = True
                break

    cx_errors = []
    for line in cmap:
        for item in props['gates']:
            if item['qubits'] == line:
                cx_errors.append(item['parameters'][0]['value'])
                break
        else:
            continue

    # Convert to percent
    cx_errors = 100 * np.asarray(cx_errors)
    avg_cx_err = np.mean(cx_errors)

    cx_norm = matplotlib.colors.Normalize(vmin=min(cx_errors),
                                          vmax=max(cx_errors))
    line_colors = [color_map(cx_norm(err)) for err in cx_errors]

    # Measurement errors

    read_err = []

    for qubit in range(n_qubits):
        for item in props['qubits'][qubit]:
            if item['name'] == 'readout_error':
                read_err.append(item['value'])

    read_err = 100 * np.asarray(read_err)
    avg_read_err = np.mean(read_err)
    max_read_err = np.max(read_err)

    fig = plt.figure(figsize=figsize)
    gridspec.GridSpec(nrows=2, ncols=3)

    grid_spec = gridspec.GridSpec(
        12,
        12,
        height_ratios=[1] * 11 + [0.5],
        width_ratios=[2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2])

    left_ax = plt.subplot(grid_spec[2:10, :1])
    main_ax = plt.subplot(grid_spec[:11, 1:11])
    right_ax = plt.subplot(grid_spec[2:10, 11:])
    bleft_ax = plt.subplot(grid_spec[-1, :5])
    bright_ax = plt.subplot(grid_spec[-1, 7:])

    plot_gate_map(backend,
                  qubit_color=q_colors,
                  line_color=line_colors,
                  qubit_size=28,
                  line_width=5,
                  plot_directed=directed,
                  ax=main_ax)
    main_ax.axis('off')
    main_ax.set_aspect(1)

    single_cb = matplotlib.colorbar.ColorbarBase(bleft_ax,
                                                 cmap=color_map,
                                                 norm=single_norm,
                                                 orientation='horizontal')
    tick_locator = ticker.MaxNLocator(nbins=5)
    single_cb.locator = tick_locator
    single_cb.update_ticks()
    single_cb.update_ticks()
    bleft_ax.set_title('H error rate (%) [Avg. = {}]'.format(
        round(avg_1q_err, 3)))

    cx_cb = matplotlib.colorbar.ColorbarBase(bright_ax,
                                             cmap=color_map,
                                             norm=cx_norm,
                                             orientation='horizontal')
    tick_locator = ticker.MaxNLocator(nbins=5)
    cx_cb.locator = tick_locator
    cx_cb.update_ticks()
    bright_ax.set_title('CNOT error rate (%) [Avg. = {}]'.format(
        round(avg_cx_err, 3)))

    if n_qubits < 10:
        num_left = n_qubits
        num_right = 0
    else:
        num_left = math.ceil(n_qubits / 2)
        num_right = n_qubits - num_left

    left_ax.barh(range(num_left),
                 read_err[:num_left],
                 align='center',
                 color='#007d79')
    left_ax.axvline(avg_read_err, linestyle='--', color='#212121')
    left_ax.set_yticks(range(num_left))
    left_ax.set_xticks([0, round(avg_read_err, 2), round(max_read_err, 2)])
    left_ax.set_yticklabels([str(kk) for kk in range(num_left)], fontsize=12)
    left_ax.invert_yaxis()
    left_ax.set_title('Readout Error (%)', fontsize=12)

    for spine in left_ax.spines.values():
        spine.set_visible(False)

    if num_right:
        right_ax.barh(range(num_left, n_qubits),
                      read_err[num_left:],
                      align='center',
                      color='#007d79')
        right_ax.axvline(avg_read_err, linestyle='--', color='#212121')
        right_ax.set_yticks(range(num_left, n_qubits))
        right_ax.set_xticks(
            [0, round(avg_read_err, 2),
             round(max_read_err, 2)])
        right_ax.set_yticklabels([str(kk) for kk in range(num_left, n_qubits)],
                                 fontsize=12)
        right_ax.invert_yaxis()
        right_ax.invert_xaxis()
        right_ax.yaxis.set_label_position("right")
        right_ax.yaxis.tick_right()
        right_ax.set_title('Readout Error (%)', fontsize=12)
    else:
        right_ax.axis('off')

    for spine in right_ax.spines.values():
        spine.set_visible(False)

    if show_title:
        fig.suptitle('{name} Error Map'.format(name=backend.name()),
                     fontsize=24,
                     y=0.9)
    if get_backend() in ['module://ipykernel.pylab.backend_inline', 'nbAgg']:
        plt.close(fig)
    return fig
コード例 #28
0
def template_ratemap(module, cmap='YlGnBu_r', length_unit='cm', box=True,
                     window_type=None, palette=None):
    """
    Convenience function to plot nice template cell firing rate maps

    Parameters
    ----------
    module : Module
        Module for which to plot the template cell firing rate.
    cmap : Colormap or registered colormap name, optional
        Colormap to use for the plot.
    length_unit : string, optional
        The length unit to add to the axis labels. If None, no length unit is
        printed.
    box : bool, optional
        If True, a box representning the environment where the true recordings
        were done is added to the plot.
    window_type : None or string, optional
        If not None, a polygon representning the window of possible phases is
        added to the plot. The value of this variable is passed to
        `Module.window` as the keyword `window_type`. See this method for
        possible values.
    palette : sequence, optional
        Color palette to use for the box and window: the first color is used
        for the box, the second for the window.

    Returns
    -------
    See `TemplateGridCell.plot_ratemap`

    """
    cell = module.template()
    axes, cbar = cell.plot_ratemap(cmap=cmap,
                                   #edgecolor='face'
                                   )

    #cbar.solids.set(edgecolor='face')
    cbar.set_label(r"$f \ / \ \bar{f}$")
    cbar.locator = ticker.MaxNLocator(nbins=2)
    cbar.update_ticks()

    range_ = next(iter(module)).params['range_']
    axes.set(xticks=range_[0], yticks=range_[1])
    if length_unit is None:
        axes.set(xlabel=r"$x$",
                 ylabel=r"$y$")
    else:
        axes.set(xlabel=r"$x \ / \ \mathrm{{{}}}$".format(length_unit),
                 ylabel=r"$y \ / \ \mathrm{{{}}}$".format(length_unit))

    if palette is None:
        palette = COLOR_CYCLE

    if box:
        xy = (range_[0][0], range_[1][0])
        width = range_[0][1] - range_[0][0]
        height = range_[1][1] - range_[1][0]
        rect = patches.Rectangle(xy=xy, width=width, height=height,
                                 fill=False, color=palette[0],
                                 linewidth=4.0)
        axes.add_patch(rect)
    if window_type is not None:
        try:
            windowpatch = module.window(window_type=window_type).patch(
                fill=False, color=palette[1], linewidth=4.0)
            axes.add_patch(windowpatch)
        except ValueError:
            for c, wt in zip(palette[1:], window_type):
                windowpatch = module.window(window_type=wt).patch(
                    fill=False, color=c, linewidth=4.0)
                axes.add_patch(windowpatch)

    return axes, cbar
コード例 #29
0
ファイル: 9_14_load_and_graph.py プロジェクト: yohei1996/CNN
import numpy as np
import datetime as dt
import os
from matplotlib import pylab as plt
import matplotlib.ticker as ticker
os.chdir(
    "c:\\Users\\nishitsuji\\Documents\\myfile\\python_tensorflow\\9_12_DGIM_validation\\"
)

folder_name = "9_12_data_save"
if folder_name not in os.listdir():
    os.chdir("./" + folder_name)
os.chdir("./" + folder_name)

accuracy_load = np.load(file="./" + "2019_09_14accuracy.npy")
# accuracy_load = np.load(file="./"+"2019_09_14accuracy.npy")
print("accuracy_load:", accuracy_load)

x = np.linspace(0, 20, 20)
y = accuracy_load
fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(111)
# ax = fig.add_axes([0,0,1,1])
ax.plot(x, y * 100, label="Accuracy", color="red")
# plt.legend()
# plt.title("Accuracy")
plt.xlabel("Epoch")
plt.gca().get_xaxis().set_major_locator(ticker.MaxNLocator(integer=True))
plt.ylabel("accuracy")
plt.show()
コード例 #30
0
def plot_impact_summary(df, fname):

    fig, axes = plt.subplots(figsize=(7, 4),
                             nrows=2,
                             ncols=2,
                             sharex=True,
                             sharey='row')
    plt.subplots_adjust(hspace=0.05, wspace=0.065)
    axes = axes.flat

    mods = [
        'tuz', 'sox1', 'wue', 'cmax', 'pmax', 'cgn', 'sox2', 'pmax2', 'lcst',
        'cap', 'mes'
    ]

    # exclude unnecessary data
    df = df[df['Unnamed: 0'] == 'actual']
    df.drop(df.filter(like='WUE(').columns.to_list(), axis=1, inplace=True)

    GPP = df.filter(like='A(').columns.to_list()
    E = df.filter(like='E(').columns.to_list()
    twet = [e for e in df.index.to_list() if e.split('_')[-1] == 'wet']
    tinter = [e for e in df.index.to_list() if e.split('_')[-1] == 'inter']

    for i, ax in enumerate(axes):

        if i < 2:
            sub = df[GPP]

        else:
            sub = df[E]

        if i % 2 == 0:
            sub = sub.loc[twet]
            ax.axvspan(-0.1,
                       0.9,
                       hatch='.' * 6,
                       facecolor='none',
                       edgecolor='#2e7d9b',
                       alpha=0.1)  # color calib.

        else:
            sub = sub.loc[tinter]
            ax.axvspan(0.9,
                       1.9,
                       hatch='.' * 6,
                       facecolor='none',
                       edgecolor='#fc8635',
                       alpha=0.1)  # color calib.

        # we're plotting in reverse order
        sub = sub.iloc[::-1]
        sub.reset_index(inplace=True)
        pos = np.arange(float(len(sub)) + 1)

        # ref model
        ax.hlines(sub[sub.filter(like='std').columns],
                  pos[:-1] - 0.1,
                  pos[1:] - 0.1,
                  linewidth=0.75,
                  alpha=0.75,
                  zorder=20,
                  label=which_model('std'))
        pos += 0.0275  # necessary alignment when plotting

        for j, p in enumerate(pos[:-1]):

            next(ax._get_lines.prop_cycler)  # skip black used for Medlyn

            for mod in mods:

                ax.scatter(p,
                           sub[sub.filter(like=mod).columns].values[j][0],
                           marker=r'$\diamondsuit$',
                           s=45.,
                           c=next(ax._get_lines.prop_cycler)['color'],
                           label=which_model(mod))
                p += 0.075

        ax.set_xlim(-0.1, 4.9)

        if i > 1:
            ax.set_xticks(np.arange(0.4, 4.5))
            ax.set_xticklabels(
                ['Wet', 'Inter.', 'Dry', '2 x $D_a$', '2 x $C_a$'])

            if i < 3:
                render_ylabels(ax, r'$E$', r'mm w$^{-1}$')

        elif i < 1:
            render_ylabels(ax, 'GPP', r'gC m$^{-2}$ w$^{-1}$')
            ax.set_title('Wet calibration')

        else:
            ax.set_title('Intermediate calibration')

        ax.set_xticks(np.arange(0.9, 5.), minor=True)
        ax.yaxis.set_major_locator(ticker.MaxNLocator(3))
        ax.set_yticklabels(ax.get_yticks())  # force LaTex
        ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%.d'))

        # subplot labelling
        ax.text(0.025,
                0.95,
                r'\textbf{(%s)}' % (string.ascii_lowercase[i]),
                transform=ax.transAxes,
                weight='bold')

        # remove spines and add grid
        ax.spines['right'].set_visible(False)
        ax.spines['top'].set_visible(False)
        ax.tick_params(which='major', length=0)
        ax.tick_params(which='minor', length=0)
        #ax.grid(which='major', axis='y')
        ax.xaxis.grid(which='minor')
        ax.yaxis.grid(which='major')

        __, top = ax.get_ylim()
        ax.set_ylim(0., top)

    # legend
    handles, labels = ax.get_legend_handles_labels()
    ax.legend(handles[:len(mods) + 1],
              labels[:len(mods) + 1],
              bbox_to_anchor=(1.025, 1. / 3.),
              loc=3)

    fig.savefig(fname)
    plt.close()