Esempio n. 1
0
def CHART_Running_Annual_Vol_with_Hourly_Samples(frequency,window,trading_hours_per_day):
    Trading_Hours_in_Trading_Year=252*trading_hours_per_day #Calculates Trading Hours in a year    
    Sample=data['Price'][frequency-1::frequency] #Creates New Sampling list based on frequency input
    Returns=np.log(Sample) - np.log(Sample.shift(1)) #Calculates Returns on New Sample    
    
    Running_Variance=Returns.rolling(window).var() #Calculates hourly running variance based on 'window size' input
    Running_Annual_Vol=np.sqrt(Running_Variance)*np.sqrt(Trading_Hours_in_Trading_Year/frequency)
    
    #Place Running Vols and Time Series in DataFrame
    DF=pd.DataFrame(Sample)
    DF['Running_Vol']=Running_Annual_Vol
    
    #Create Plot
    DF.Price.plot()
    plt.legend()
    plt.ylabel('Yield (%)')
    DF.Running_Vol.plot(secondary_y=True, style='g',rot=90)
    plt.xlabel('Date')
    plt.ylabel('Running Vol') 
    plt.title('10 Year Bund Yield vs Annualized Running Vol (Window Size=200)')
    plt.legend(bbox_to_anchor=(0.8, 1))
    plt.text(0.8, 5.4, "Frequency={}. Window Size={}. Trading Hours per Day={}".format(frequency, window,trading_hours_per_day))

    
    return plt
Esempio n. 2
0
    def plot(cls, data, figure_folder, msg="", suffix=""):

        fig, ax = plt.subplots()

        plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.2)

        x = np.arange(len(data[:]))

        ax.plot(x, data[:, 0], c="red", linewidth=2, label="agent 01")
        ax.plot(x, data[:, 1], c="blue", linewidth=2, label="agent 12")
        ax.plot(x, data[:, 2], c="green", linewidth=2, label="agent 20")

        plt.ylim([-0.01, 1.01])

        plt.text(0, -0.23, "PARAMETERS. {}".format(msg))

        ax.legend(fontsize=12,
                  bbox_to_anchor=(1.1, 1.05))  # loc='upper center'
        ax.set_xlabel("$t$")
        ax.set_ylabel("Proportion of agents proceeding to indirect exchange")

        ax.set_title("Money emergence with a basal ganglia model")

        # Save fig
        if not exists(figure_folder):
            mkdir(figure_folder)
        fig_name = "{}/figure_{}.pdf".format(figure_folder,
                                             suffix.split(".p")[0])
        plt.savefig(fig_name)
        plt.close()
def add_comment_with_file_name(fig, file_name):
    plt.text(0.005,
             0.005,
             file_name,
             transform=fig.transFigure,
             fontsize='x-small',
             color='0.5')
Esempio n. 4
0
def CHART_Running_Annual_Vol_with_Daily_Samples_on_Specific_Time_of_Day(frequency,sampling_time,window,trading_hours_per_day):
    Original_DAILY_Sample=data['Price'][sampling_time-1::trading_hours_per_day] #Grabs the Hourly Data and Converts it into Daily Data based on Sampling Time of Day AND Trading Hours per Day 
    NEW_Sample=Original_DAILY_Sample[frequency-1::frequency] #Creates New Sampling list based on sampling frequency input
    Returns=np.log(NEW_Sample) - np.log(NEW_Sample.shift(1)) #Calculates Returns on New Sample    
    Running_Variance=Returns.rolling(window).var() #Calculates daily running variance based on 'window size' input
    Running_Annual_Vol=np.sqrt(Running_Variance)*np.sqrt(252/frequency) 
    
    #Place NEW Sampled data (prices) and Running Vols in DataFrame
    DF=pd.DataFrame(NEW_Sample)
    DF['Running_Vol']=Running_Annual_Vol
    
    #Create Plot
    DF.Price.plot()
    plt.legend()
    #data.Price.plot()
    plt.ylabel('Yield (%)')
    DF.Running_Vol.plot(secondary_y=True, style='g',rot=90)
    plt.xlabel('Date')
    plt.ylabel('Running Vol') 
    plt.title('10 Year Bund Yield vs Annualized Running Vol ')
    plt.legend(bbox_to_anchor=(0.8, 1))
    plt.text(0.8, 3.5, "Sampling Time={}. Window Size={}. Trading Hours per Day={}".format(sampling_time, window,trading_hours_per_day))

    
    return plt
    def plot(cls, data, figure_folder, msg="", suffix=""):

        fig, ax = plt.subplots()

        plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.2)

        x = np.arange(len(data[:]))

        ax.plot(x, data[:, 0], c="red", linewidth=2, label="agent 01")
        ax.plot(x, data[:, 1], c="blue", linewidth=2, label="agent 12")
        ax.plot(x, data[:, 2], c="green", linewidth=2, label="agent 20")

        plt.ylim([-0.01, 1.01])

        plt.text(0, -0.23, "PARAMETERS. {}".format(msg))

        ax.legend(fontsize=12, bbox_to_anchor=(1.1, 1.05))  # loc='upper center'
        ax.set_xlabel("$t$")
        ax.set_ylabel("Proportion of agents proceeding to indirect exchange")

        ax.set_title("Money emergence with a basal ganglia model")

        # Save fig
        if not exists(figure_folder):
            mkdir(figure_folder)
        fig_name = "{}/figure_{}.pdf".format(figure_folder, suffix.split(".p")[0])
        plt.savefig(fig_name)
        plt.close()
    def plot(cls, data, msg=""):

        x = np.arange(len(data[:]))

        plt.plot(x, data[:, 0], c="red", linewidth=2)
        plt.plot(x, data[:, 1], c="blue", linewidth=2)
        plt.plot(x, data[:, 2], c="green", linewidth=2)
        plt.ylim([-0.01, 1.01])
        plt.text(0, -0.12, "{}".format(msg))

        plt.show()
Esempio n. 7
0
    def plot(cls, data, msg=""):

        x = np.arange(len(data[:]))

        plt.plot(x, data[:, 0], c="red", linewidth=2)
        plt.plot(x, data[:, 1], c="blue", linewidth=2)
        plt.plot(x, data[:, 2], c="green", linewidth=2)
        plt.ylim([-0.01, 1.01])
        plt.text(0, -0.12, "{}".format(msg))

        plt.show()
Esempio n. 8
0
def plot_fault_framework(fault_framework):
    fm = fault_framework
    plt.plot(fm.Y_PC, fm.DEP, '-o')
    plt.axis('equal')
    plt.axhline(0, color='black')
    plt.gca().set_yticks(fm.DEP)
    plt.gca().set_xticks(fm.Y_PC)
    plt.grid('on')
    plt.xlabel('From trench to continent(km)')
    plt.ylabel('depth (km)')

    for xi, yi, dip in zip(fm.Y_PC, fm.DEP, fm.DIP_D):
        plt.text(xi, yi, 'dip = %.1f' % dip)

    plt.gca().invert_yaxis()
Esempio n. 9
0
def draw(x, y, x_text, y_text, title):
    plt.figure(figsize=(30, 5))
    plt.plot(x, y, color='red', label='data_check_result')
    for i in range(1, len(x)):
        plt.text(x[i], y[i], str((x[i], round(y[i], 4))))
    #plt.text(x,y,(x,y),color='red')
    plt.xlabel(x_text)
    plt.ylabel(y_text)
    plt.title(title)
    plt.grid(True)
    plt.legend()
    pic = time.strftime("%Y-%m-%d_%H_%S_%M", time.localtime()) + ".pdf"

    plt.savefig(pic)
    plt.show()
Esempio n. 10
0
def plot_fault_framework(fault_framework):
    fm = fault_framework
    plt.plot(fm.Y_PC, fm.DEP, '-o')
    plt.axis('equal')
    plt.axhline(0, color='black')
    plt.gca().set_yticks(fm.DEP)
    plt.gca().set_xticks(fm.Y_PC)
    plt.grid('on')
    plt.xlabel('From trench to continent(km)')
    plt.ylabel('depth (km)')

    for xi, yi, dip in zip(fm.Y_PC, fm.DEP, fm.DIP_D):
        plt.text(xi, yi, 'dip = %.1f'%dip)

    plt.gca().invert_yaxis()
def profit_firmA_against_profit_firmB(file_name, folder=None):

    if folder is None:
        folder = "data/figures"

    os.makedirs(folder, exist_ok=True)

    bkp = backup.RunBackup.load(file_name=file_name)
    parameters = bkp.parameters

    profit_max = parameters.n_positions * parameters.n_prices * parameters.unit_value

    x = np.arange(parameters.t_max)
    y = np.zeros((2, parameters.t_max))

    for f in range(2):
        for t in range(parameters.t_max):
            y[f, t] = np.mean(bkp.profits[:t + 1, f] / profit_max)

        # y = np.array([np.mean(for_y[i][t]) for t in range(parameters.t_max)])
        # y_err = np.array([np.std(for_y[i][t]) for t in range(parameters.t_max)])

    fig = plt.Figure()

    plt.plot(x, y[0], label="Firm A")
    plt.plot(x, y[1], label="Firm B")
    # plt.fill_between(x, y - (y_err / 2), y + (y_err / 2), color="C{}".format(i), alpha=.25)

    plt.legend()
    plt.xlabel("t")
    plt.ylabel("Mean profit")

    plt.text(0.005,
             0.005,
             file_name,
             transform=fig.transFigure,
             fontsize='x-small',
             color='0.5')

    plt.title("Evolution of profits over time ($r={}$)".format(
        bkp.field_of_view / 2))

    plt.tight_layout()

    plt.savefig("{}/{}_mean_profit.pdf".format(folder, file_name))

    plt.show()
def show_prediction_result(image, label_image, clf):
    size = (8, 8)
    plt.figure(figsize=(15, 10))
    plt.imshow(image, cmap='gray_r')
    candidates = []
    predictions = []
    for region in regionprops(label_image):
        # skip small images
        #     if region.area < 100:
        #         continue
        # draw rectangle around segmented coins
        minr, minc, maxr, maxc = region.bbox
        # make regions square
        maxwidth = np.max([maxr - minr, maxc - minc])
        minr, maxr = int(0.5 * ((maxr + minr) - maxwidth)) - 3, int(0.5 * ((maxr + minr) + maxwidth)) + 3
        minc, maxc = int(0.5 * ((maxc + minc) - maxwidth)) - 3, int(0.5 * ((maxc + minc) + maxwidth)) + 3
        rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,
                                  fill=False, edgecolor='red', linewidth=2, alpha=0.2)
        plt.gca().add_patch(rect)
        # predict digit
        candidate = image[minr:maxr, minc:maxc]
        candidate = np.array(imresize(candidate, size), dtype=float)
        # invert
        # candidate = np.max(candidate) - candidate
        #     print im
        # rescale to 16 in integer
        candidate = (candidate - np.min(candidate))
        if np.max(candidate) == 0:
            continue
        candidate /= np.max(candidate)
        candidate[candidate < 0.2] = 0.0
        candidate *= 16
        candidate = np.array(candidate, dtype=int)
        prediction = clf.predict(candidate.reshape(-1))
        candidates.append(candidate)
        predictions.append(prediction)
        plt.text(minc - 10, minr - 10, "{}".format(prediction), fontsize=50)
    plt.xticks([], [])
    plt.yticks([], [])
    plt.tight_layout()
    plt.show()
    return candidates, predictions
def pos_firmA_over_pos_firmB(file_name, folder=None):

    if folder is None:
        folder = "data/figures"

    os.makedirs(folder, exist_ok=True)

    bkp = backup.RunBackup.load(file_name=file_name)

    pos = bkp.positions[-1000:]

    fig = plt.figure()
    ax = fig.add_subplot(111)

    ax.scatter(pos[:, 0], pos[:, 1], color="black", alpha=0.05)
    ax.axvline(0.5, color="white", linewidth=0.5, linestyle="--")
    ax.axhline(0.5, color="white", linewidth=0.5, linestyle="--")

    plt.xlim(-1, bkp.parameters.n_positions)
    plt.ylim(-1, bkp.parameters.n_positions)
    plt.xticks(
        range(0, bkp.parameters.n_positions + 1,
              round(bkp.parameters.n_positions / 5)))
    plt.yticks(
        range(0, bkp.parameters.n_positions + 1,
              round(bkp.parameters.n_positions / 5)))

    plt.xlabel("Position A")
    plt.ylabel("Position B")

    plt.text(0.005,
             0.005,
             file_name,
             transform=fig.transFigure,
             fontsize='x-small',
             color='0.5')

    plt.title("$r={:.2f}$".format(bkp.field_of_view / 2))
    ax.set_aspect(1)
    plt.tight_layout()
    plt.savefig("{}/{}_evo_positions.pdf".format(folder, file_name))
    plt.show()
Esempio n. 14
0
def show_prediction_result(image, label_image, clf):
    size = (8, 8)
    plt.figure(figsize=(15, 10))
    plt.imshow(image, cmap='gray_r')
    candidates = []
    predictions = []
    for region in regionprops(label_image):
        # skip small images
        #     if region.area < 100:
        #         continue
        # draw rectangle around segmented coins
        minr, minc, maxr, maxc = region.bbox
        # make regions square
        maxwidth = np.max([maxr - minr, maxc - minc])
        minr, maxr = int(0.5 * ((maxr + minr) - maxwidth)) - 3, int(0.5 * ((maxr + minr) + maxwidth)) + 3
        minc, maxc = int(0.5 * ((maxc + minc) - maxwidth)) - 3, int(0.5 * ((maxc + minc) + maxwidth)) + 3
        rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,
                                  fill=False, edgecolor='red', linewidth=2, alpha=0.2)
        plt.gca().add_patch(rect)
        # predict digit
        candidate = image[minr:maxr, minc:maxc]
        candidate = np.array(imresize(candidate, size), dtype=float)
        # invert
        # candidate = np.max(candidate) - candidate
        #     print im
        # rescale to 16 in integer
        candidate = (candidate - np.min(candidate))
        if np.max(candidate) == 0:
            continue
        candidate /= np.max(candidate)
        candidate[candidate < 0.2] = 0.0
        candidate *= 16
        candidate = np.array(candidate, dtype=int)
        prediction = clf.predict(candidate.reshape(-1))
        candidates.append(candidate)
        predictions.append(prediction)
        plt.text(minc - 10, minr - 10, "{}".format(prediction), fontsize=50)
    plt.xticks([], [])
    plt.yticks([], [])
    plt.tight_layout()
    plt.show()
    return candidates, predictions
Esempio n. 15
0
 def plot_sites(self,
                sites,
                marker='s',
                color='white',
                ms=5,
                text=True,
                fs=8,
                offset_X=0,
                offset_Y=0):
     lons, lats = vj.sites_db.get_pos(sites)
     self.basemap.plot(lons,
                       lats,
                       linestyle='None',
                       marker=marker,
                       color=color,
                       ms=ms,
                       latlon=True)
     if text:
         lons += offset_X
         lats += offset_Y
         x, y = self.basemap(lons, lats)
         for xi, yi, ti in zip(x, y, sites):
             plt.text(xi, yi, ti, fontsize=fs)
Esempio n. 16
0
 def plot_overview(self,suffix=''):
     x=self.x; y=self.y; r=self.radius; cx,cy=self.center.real,self.center.imag
     ax=plt.axes()
     plt.scatter(x,y, marker='o', c='b', s=40)
     plt.axhline(y=0,color='grey', zorder=-1)
     plt.axvline(x=0,color='grey', zorder=-2)
     t=linspace(0,2*pi,201)
     circx=r*cos(t) + cx
     circy=r*sin(t) + cy
     plt.plot(circx,circy,'g-')
     plt.plot([cx],[cy],'gx',ms=12)
     if self.ZorY == 'Z':
         philist,flist=[self.phi_a,self.phi_p,self.phi_n],[self.fa,self.fp,self.fn]
     elif self.ZorY == 'Y':
         philist,flist=[self.phi_m,self.phi_s,self.phi_r],[self.fm,self.fs,self.fr]
     for p,f in zip(philist,flist):
         if f is not None:
             xpos=cx+r*cos(p); ypos=cy+r*sin(p); xos=0.2*(xpos-cx); yos=0.2*(ypos-cy)
             plt.plot([0,xpos],[0,ypos],'co-')
             ax.annotate('{:.3f} Hz'.format(f), xy=(xpos,ypos),  xycoords='data',
                         xytext=(xpos+xos,ypos+yos), textcoords='data', #textcoords='offset points',
                         arrowprops=dict(arrowstyle="->", shrinkA=0, shrinkB=10)
                         )
     #plt.xlim(0,0.16)
     #plt.ylim(-0.1,0.1)
     plt.axis('equal')
     if self.ZorY == 'Z':
         plt.xlabel(r'resistance $R$ in Ohm'); plt.ylabel(r'reactance $X$ in Ohm')
     if self.ZorY == 'Y':
         plt.xlabel(r'conductance $G$ in Siemens'); plt.ylabel(r'susceptance $B$ in Siemens')
     plt.title("fitting the admittance circle with Powell's method")
     tx1='best fit (fmin_powell):\n'
     tx1+='center at G+iB = {:.5f} + i*{:.8f}\n'.format(cx,cy)
     tx1+='radius = {:.5f};  '.format(r)
     tx1+='residue: {:.2e}'.format(self.resid)
     txt1=plt.text(-r,cy-1.1*r,tx1,fontsize=8,ha='left',va='top')
     txt1.set_bbox(dict(facecolor='gray', alpha=0.25))
     idxlist=self.to_be_annotated('triple')
     ofs=self.annotation_offsets(idxlist,factor=0.1,xshift=0.15)
     for i,j in enumerate(idxlist):
         xpos,ypos = x[j],y[j]; xos,yos = ofs[i].real,ofs[i].imag
         ax.annotate('{:.1f} Hz'.format(self.f[j]), xy=(xpos,ypos),  xycoords='data',
                     xytext=(xpos+xos,ypos+yos), textcoords='data', #textcoords='offset points',
                     arrowprops=dict(arrowstyle="->", shrinkA=0, shrinkB=10)
                     )
     if self.show: plt.show()
     else: plt.savefig(join(self.sdc.plotpath,'c{}_fitted_{}_circle'.format(self.sdc.case,self.ZorY)+suffix+'.png'), dpi=240)
     plt.close()
Esempio n. 17
0
print('rmse in training cross-validation:',np.sqrt(-best_cv.best_score_))


#%%
final_estimator = best_cv.best_estimator_

# save the final estimator
estimator_file = 'wind_power_icing_final_estimator_from_gridsearch.pkl'
pickle.dump(final_estimator, open(estimator_file,'wb'))
# save the configuration as text file
print(final_estimator, file=open('wind_power_icing_final_estimator_config.txt','w'))

# now use this estimator on the test data
y_test_predicted = final_estimator.predict(X_test)

mse_test = metrics.mean_squared_error(y_test, y_test_predicted)
rmse_test = np.sqrt(mse_test)
print('mse on test data:', mse_test)
print('rmse on test data', rmse_test)

r2 = np.corrcoef(y_test_predicted, y_test)[0,1]**2

plt.figure()
sns.regplot(y_test_predicted, y_test)
plt.ylabel('ploss test')
plt.xlabel('ploss test predicted')
plt.text(0.1,0.9,'R^2={:.2f}'.format(r2), transform = plt.gca().transAxes)
plt.text(0.1,0.85,'RMSE={:.2f}'.format(rmse_test), transform = plt.gca().transAxes)
plt.text(0.1,0.8,'N={:.2f}'.format(len(y_test)), transform = plt.gca().transAxes)
plt.savefig(target_var+'_vs_'+target_var+'_predicted_on_test_set_lead_hour'+str(lead_hour)+'.svg')
Esempio n. 18
0
# The sequential mode is designed to work with exactly one input tensor and one output tensor.
model = Sequential()

model.add(SimpleRNN(500, activation='relu', input_shape=(lags, 1)))

model.add(Dense(1, activation='linear'))

model.compile(optimizer='rmsprop', loss='mse', metrics=['mae'])

model.summary()

model.fit(g, epochs=500, steps_per_epoch=10, verbose=False)

x = np.linspace(-6 * np.pi, 6 * np.pi, 1000)
d = transform(x)

g_ = TimeseriesGenerator(d, d, length=lags, batch_size=len(d))

f = list(g_)[0][0].reshape((len(d) - lags, lags, 1))
y = model.predict(f, verbose=False)

plt.figure(figsize=(10, 6))
plt.plot(x[lags:], d[lags:], label='data', alpha=0.75)
plt.plot(x[lags:], y, 'r.', label='pred', ms=3)
plt.axvline(-2 * np.pi, c='g', ls='--')
plt.axvline(2 * np.pi, c='g', ls='--')
plt.text(-15, 22, 'out-of-sample')
plt.text(-2, 22, 'in-sample')
plt.text(10, 22, 'out-of-sample')
plt.legend()
Esempio n. 19
0
def CHART_Running_Vol_with_Space_Increment_Sampling(increment_in_bp,window,trading_hours_per_day):
    Trading_Hours_in_Trading_Year=252*trading_hours_per_day #Calculates Trading Hours in a year
    Increment_Sample=[] #Create a List for the samples
    Dates_List=[] #Create list for Dates    
    
    Increment_Sample.append(data['Price'][0]) #Add the first data point in our data
    Dates_List.append(DATES[0:1]) #Add the first Date


    Index_List=[1] #Create a list for the index of the samples

    #Loop to add the element in the list ONLY if its value is more than X bp away from last sample
    counter=0 #counter to keep track in which hours did we sample
    for i in data['Price']:
        counter+=1
        if abs(i-np.array(Increment_Sample[-1:]))>=(increment_in_bp/100):
            Increment_Sample.append(i)
            Index_List.append(counter)
            Dates_List.append(DATES[counter])

        else:
            continue
    
    #Convert to a DataFrame
    Increment_Sample=pd.DataFrame(Increment_Sample)
    
    #Calculate Returns on NEW sample
    Returns=np.log(Increment_Sample) - np.log(Increment_Sample.shift(1))
    
    #Calculate Running average distance(in hours) between samples
    dt=pd.DataFrame([x - Index_List[i - 1] for i, x in enumerate(Index_List)][1:]).rolling(window).mean()
    
    # Calculate Running Variance
    Running_Variance=Returns.rolling(window).var() #Calculates hourly running variance based on 'window size' input
    
    #Calculate Annualized Vol based on average distance (in hours) between samples (dt) and the trading hours in a year
    Annual_Vol=np.sqrt(Running_Variance)*np.sqrt(Trading_Hours_in_Trading_Year/dt) 
    
    Final_DF=pd.DataFrame(Annual_Vol)#Create dataframe with Running Annual Vol
    Final_DF['Dates']=Dates_List   #Add sampled dates to the dataframe
    Final_DF.set_index('Dates',inplace=True, drop=True) #Set Dates as the index
    Final_DF.columns = ['Running_Annual_Vol']  #Assign column name

    #Create Plot
    Increment_Sample.columns = ['Price']  #Assign column name
    Increment_Sample.plot()
    plt.legend()
    plt.ylabel('Yield (%)')
    
    #plt.plot([], [], ' ', label="Extra label on the legend")
    #plt.legend()
    #data.Price.plot()
    
    Final_DF.Running_Annual_Vol.plot(secondary_y=True, style='g',rot=90)
    plt.xlabel('Date')
    plt.ylabel('Running Vol') 
    plt.title('10 Year Bund Yield vs Annualized Running Vol ')
    plt.legend(bbox_to_anchor=(.8, 1)) 
    plt.text(0.8, 7.2, "SAMPLING ONLY IF MOVE IS ≥ {} bp. Window Size= {}".format(increment_in_bp, window))
        
    return plt 
Esempio n. 20
0
    def plot_fenbi_seq(biIdx, frsBiType, plt=None, color=None):
        x_fenbi_seq = []
        y_fenbi_seq = []
        for i in range(len(biIdx)):
            if biIdx[i] is not None:
                fenType = -frsBiType if i % 2 == 0 else frsBiType
                #         dt = chanK['enddate'][biIdx[i]]
                # 缠论k线
                dt = chanK.index[biIdx[i]] if chanK_flag else chanK['enddate'][
                    biIdx[i]]
                # print i,k_data['high'][dt], k_data['low'][dt]
                time_long = long(
                    time.mktime(
                        (dt + datetime.timedelta(hours=8)).timetuple()) *
                    1000000000)
                # print x_date_list.index(time_long) if time_long in x_date_list else 0
                if fenType == 1:
                    if plt is not None:
                        if color is None:
                            plt.text(x_date_list.index(time_long),
                                     k_data['high'][dt],
                                     str(k_data['high'][dt]),
                                     ha='left',
                                     fontsize=12)
                        else:
                            col_v = color[0] if fenType > 0 else color[1]
                            plt.text(x_date_list.index(time_long),
                                     k_data['high'][dt],
                                     str(k_data['high'][dt]),
                                     ha='left',
                                     fontsize=12,
                                     bbox=dict(facecolor=col_v, alpha=0.5))

                    x_fenbi_seq.append(x_date_list.index(time_long))
                    y_fenbi_seq.append(k_data['high'][dt])
                if fenType == -1:
                    if plt is not None:
                        if color is None:
                            plt.text(x_date_list.index(time_long),
                                     k_data['low'][dt],
                                     str(k_data['low'][dt]),
                                     va='bottom',
                                     fontsize=12)
                        else:
                            col_v = color[0] if fenType > 0 else color[1]
                            plt.text(x_date_list.index(time_long),
                                     k_data['low'][dt],
                                     str(k_data['low'][dt]),
                                     va='bottom',
                                     fontsize=12,
                                     bbox=dict(facecolor=col_v, alpha=0.5))

                    x_fenbi_seq.append(x_date_list.index(time_long))
                    y_fenbi_seq.append(k_data['low'][dt])
    #             bottom_time = None
    #             for k_line_dto in m_line_dto.member_list[::-1]:
    #                 if k_line_dto.low == m_line_dto.low:
    #                     # get_price返回的日期,默认时间是08:00:00
    #                     bottom_time = k_line_dto.begin_time.strftime('%Y-%m-%d') +' 08:00:00'
    #                     break
    #             x_fenbi_seq.append(x_date_list.index(long(time.mktime(datetime.strptime(bottom_time, "%Y-%m-%d %H:%M:%S").timetuple())*1000000000)))
    #             y_fenbi_seq.append(m_line_dto.low)
        return x_fenbi_seq, y_fenbi_seq
Esempio n. 21
0
plt.subplot(211)  # 令子图subplot(211)成为figure1的当前图
plt.title('Easy as 1,2,3')  # 添加subplot 211 的标题

'==========================================='
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

# 数据的直方图
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75)

plt.xlabel('Smarts')
plt.ylabel('Probability')
# 添加标题
plt.title('Histogram of IQ')
# 添加文字
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()

'==========================================='

ax = plt.subplot(111)

t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2 * np.pi * t)
line, = plt.plot(t, s, lw=2)

plt.annotate(
    'local max',
    xy=(2, 1),
def distance_over_fov(file_name, pool_backup, fig_folder=None):

    span_ratio = 0.33

    if fig_folder is None:
        fig_folder = "data/figures"

    os.makedirs(fig_folder, exist_ok=True)

    parameters = pool_backup.parameters
    backups = pool_backup.backups

    n_simulations = parameters.n_simulations

    n_positions = parameters.n_positions
    p_max = parameters.p_max

    # Compute profit max
    profit_max = n_positions * p_max

    # Containers
    x = np.zeros(n_simulations)
    y = np.zeros(n_simulations)
    y_err = np.zeros(n_simulations)
    z = np.zeros(n_simulations)

    # How many time steps from the end of the simulation are included in analysis
    span = int(span_ratio * parameters.t_max)

    for i, b in enumerate(backups):

        try:
            # Save the parameter that affected the customers field of view
            x[i] = b.field_of_view / 2
        except AttributeError:
            x[i] = b.parameters.r

        # Compute the mean distance between the two firms
        data = np.absolute(b.positions[-span:, 0] -
                           b.positions[-span:, 1]) / n_positions

        spacing = np.mean(data)
        spacing_std = np.std(data)

        y[i] = spacing
        y_err[i] = spacing_std

        # Get mean profits
        z[i] = np.mean(b.profits[-span:, :]) / profit_max

    # Plot this
    fig = plt.figure(figsize=(10, 6))
    ax = plt.subplot()

    ax.set_xlim(-0.01, 1.01)
    if max(y) < 0.5:
        ax.set_ylim(-0.01, 0.51)

    ax.set_xticks(np.arange(0, 1.1, 0.25))
    ax.set_yticks(np.arange(0, 0.51, 0.1))

    ax.set_xlabel("$r$")
    ax.set_ylabel("Mean distance")

    ax.set_title("Mean distance between firms over $r$")

    # add comment with file name
    plt.text(0.005,
             0.005,
             file_name,
             transform=fig.transFigure,
             fontsize='x-small',
             color='0.5')

    # show random
    plt.text(0.005,
             0.005,
             file_name,
             transform=fig.transFigure,
             fontsize='x-small',
             color='0.5')

    abc = ax.scatter(x, y, c=z, zorder=10, alpha=0.25)
    fig.colorbar(abc, label="Profits")

    plt.tight_layout()

    if file_name:
        plt.savefig("{}/{}.pdf".format(fig_folder, file_name))

    plt.show()
Esempio n. 23
0
        sweepFreq_dict["SWEEP_FREQ_C2V"] = False
        sweepFreq_dict["SWEEP_FREQ_C2C"] = False

        print(motor_dict)
        print(sweepFreq_dict)
        dB, Deg, Freq, max_freq = analyzer.analyze(dot_dat_file_dir,
                                                   motor_dict, sweepFreq_dict)
        # for el in (dB, Deg, Freq, max_freq):
        #     print(el)

        plt.figure(4, figsize=(20, 8))
        plt.plot(Freq, dB, '--.', label=data_fname)

        index, value = analyzer.find_nearest(dB, -3)  # find -3dB freq
        VLBW = Freq[index]
        plt.text(VLBW, -5, f'{VLBW:.0f} Hz', color='red', fontsize=20)
        plt.plot([0, max_freq], [-3, -3], 'k--')
        plt.ylabel('Velocity Closed-loop transfer function amplitude [dB]')

        plt.xscale('log')
        plt.xlabel('Frequency [Hz]')
        plt.legend()

        # 2. Plot designed Bode plot
        # plt.figure(4, figsize=(20,8))
        mag, phase, omega = MagPhaseOmega
        index_max_freq = sum(omega / (2 * np.pi) < max_freq)
        plt.plot((omega / (2 * np.pi))[:index_max_freq],
                 20 * np.log10(mag[:index_max_freq]),
                 '-.',
                 label=f'designed:$\\delta={delta}$')