def test_BoxAnnotation(): box = BoxAnnotation() assert box.plot is None assert box.left is None assert box.left_units == 'data' assert box.right is None assert box.right_units == 'data' assert box.bottom is None assert box.bottom_units == 'data' assert box.top is None assert box.top_units == 'data' assert box.x_range_name == 'default' assert box.y_range_name == 'default' assert box.level == 'annotation' check_line_properties(box, "", '#cccccc', 1, 0.3) check_fill_properties(box, "", "#fff9ba", 0.4) check_properties_existence(box, [ "render_mode", "plot", "visible", "left", "left_units", "right", "right_units", "bottom", "bottom_units", "top", "top_units", "x_range_name", "y_range_name", "level", ], LINE, FILL)
def test_BoxAnnotation(): box = BoxAnnotation() assert box.plot is None assert box.left == None assert box.left_units == 'data' assert box.right == None assert box.right_units == 'data' assert box.bottom == None assert box.bottom_units == 'data' assert box.top == None assert box.top_units == 'data' assert box.x_range_name == 'default' assert box.y_range_name == 'default' assert box.level == 'annotation' yield check_line, box, "", '#cccccc', 1, 0.3 yield check_fill, box, "", "#fff9ba", 0.4 yield (check_props, box, [ "render_mode", "plot", "left", "left_units", "right", "right_units", "bottom", "bottom_units", "top", "top_units", "x_range_name", "y_range_name", "level", ], LINE, FILL)
def test_BoxAnnotation(): box = BoxAnnotation() assert box.plot is None assert box.left == 'auto' assert box.left_units == 'data' assert box.right == 'auto' assert box.right_units == 'data' assert box.bottom == 'auto' assert box.bottom_units == 'data' assert box.top == 'auto' assert box.top_units == 'data' assert box.x_range_name == 'default' assert box.y_range_name == 'default' assert box.level == 'annotation' yield check_line, box yield check_fill, box yield (check_props, box, [ "plot", "left", "left_units", "right", "right_units", "bottom", "bottom_units", "top", "top_units", "x_range_name", "y_range_name", "level", ], LINE, FILL)
def grafica_distribucion_estandar(lista, file="index.html"): lista_ordenada = ordenamiento_insercion(lista) mu = media(lista_ordenada) sigma = desviacion_estandar(lista_ordenada) x, y = valores_x_y_distribucion_normal(lista_ordenada) output_file(file) f = figure() f.line(x, y) # Creating span annotation for mu span = Span(location=mu, dimension='height', line_color='blue', line_width=2) f.add_layout(span) # Creating a box annotations for sigmas sigma_1 = BoxAnnotation(left=mu - 1 * sigma, right=mu + sigma, line_width=1, fill_color='grey', fill_alpha=0.3) f.add_layout(sigma_1) sigma_2_left = BoxAnnotation(left=mu - 2 * sigma, right=mu - 1 * sigma, line_width=1, fill_color='grey', fill_alpha=0.2) f.add_layout(sigma_2_left) sigma_2_right = BoxAnnotation(left=mu + sigma, right=mu + 2 * sigma, line_width=1, fill_color='grey', fill_alpha=0.2) f.add_layout(sigma_2_right) show(f)
def bok_sca3(df): # 10部以上电影导演07到17年每年电影数量和平均得分散点图 df1 = df.copy() df1['size'] = df1['movie_year'] * 5 colors = ['chocolate', 'skyblue', 'red', 'lawngreen', 'purple'] colmark = 0 df1['color'] = np.nan for i in df1['direcname'].unique(): df1['color'][df1['direcname'] == i] = colors[colmark] colmark += 1 source = ColumnDataSource(df1) output_file('10部以上电影导演07到17年电影得分.html') box = BoxAnnotation(top=4.3, fill_color='gray', fill_alpha=0.1) hover = HoverTool(tooltips=[('该年电影总量', '@movie_year'), ('该年电影平均得分', '@score_mean')]) p = figure(plot_width=800, plot_height=400, title='10部以上导演07到17年年电影量和均分', tools=[hover, 'pan, wheel_zoom, box_select, reset']) p.circle(x='year', y='score_mean', source=source, size='size', legend='direcname', color='color', alpha=0.6) p.legend.orientation = 'horizontal' p.legend.background_fill_alpha = 0.5 p.add_layout(box) show(p)
'@kw_norm')]) result = figure(plot_width=800, plot_height=300, title='餐饮类型得分', x_axis_label='人均消费', y_axis_label='性价比得分', tools=[hover, 'box_select,reset,xwheel_zoom,pan,crosshair']) result.circle(x='price', y='xjb_norm', source=source, line_color='black', line_dash=[6, 4], fill_alpha=0.6, size='size') price_mid = BoxAnnotation(left=40, right=80, fill_alpha=0.1, fill_color='navy') result.add_layout(price_mid) #散点图 data_type = data_final_q1.index.tolist() kw = figure(plot_width=800, plot_height=300, title='口味得分', x_range=data_type, tools=[hover, 'box_select,reset,xwheel_zoom,pan,crosshair']) kw.vbar(x='type', top='kw_norm', source=source, width=0.8, alpha=0.7,
hover = HoverTool(tooltips=[("餐饮类型", "@type"), ("人均消费", "@price"), ("性价比得分", "@xjb_norm"), ("口味得分", "@kw_norm") ]) # 设置标签显示内容 s1 = figure(plot_width=800, plot_height=250, title='餐饮类型得分情况', x_axis_label = '人均消费', y_axis_label = '性价比得分', tools=[hover,'box_select,lasso_select,reset,xwheel_zoom,pan,crosshair']) s1.circle(x = 'price', y = 'xjb_norm',size = 'size',source = source, color="navy", alpha=0.5) center = BoxAnnotation(left=40, right=100, # 设置矩形四边位置 fill_alpha=0.1, fill_color='gray' # 设置透明度、颜色 ) s1.add_layout(center) # 散点图 rangename = data_th5.index.tolist() s2 = figure(plot_width=800, plot_height=250, title='口味得分', x_range = rangename) s2.vbar(x='type', width=0.9, bottom=0,top='kw_norm', source = source, line_width = 1,line_alpha = 0.8,line_color = 'black', line_dash = [5,2], # 单独设置线参数 fill_color = 'red',fill_alpha = 0.6 # 单独设置填充颜色参数 ) #s2.xaxis.major_label_orientation = 'vertical' #s2.xaxis.major_label_text_baseline = 'bottom' # 直方图1
line_color='green', line_alpha=0.7, line_width=1.5, line_dash=[6, 4]) y = Span(location=y_mean, dimension='width', line_color='green', line_alpha=0.7, line_width=1.5, line_dash=[6, 4]) p4.add_layout(x) p4.add_layout(y) # 绘制辅助线 bg1 = BoxAnnotation(bottom=y_mean, right=x_mean, fill_alpha=0.1, fill_color='olive') label1 = Label(x=0.1, y=0.45, text="少量大打折", text_font_size="10pt") p4.add_layout(bg1) p4.add_layout(label1) # 绘制第一象限 bg2 = BoxAnnotation(bottom=y_mean, left=x_mean, fill_alpha=0.1, fill_color='firebrick') label2 = Label(x=0.5, y=0.45, text="大量大打折", text_font_size="10pt") p4.add_layout(bg2) p4.add_layout(label2) # 绘制第二象限
def success_table(): if request.method == "POST": #Stock Ticker Input #returns lookback period (in days) #bottom [] percentile of returns #input for stock price period (in years) try: company_name = request.form['Company Name'] Ticker = request.form['Ticker'] ReturnsLBperiod = int(request.form['ReturnsLBperiod']) ReturnsQuantile = float(request.form['ReturnsQuantile']) StockPricePeriod = int(request.form['StockPricePeriod']) end = datetime.now() start = datetime(end.year - StockPricePeriod, end.month, end.day) df = web.DataReader(Ticker, 'yahoo', start=start, end=end) '''Scrape Reuters Search''' def get_headlines(links_site): '''scrape the html of the site''' resp = requests.get(links_site) if not resp.ok: return None html = resp.content s = str(html) '''Extract raw data''' headlines = re.findall(r'headline: "(.*?)",', s) dates = re.findall(r'date: "(.*?)",', s) links = re.findall(r'href: "(.*?)",', s) '''FORMAT ALL RAW DATA - format headlines, links and time''' '''Eliminate HTML tags from headline''' headlines = [ re.sub('<[^<]+?>', '', item) for item in headlines ] '''Edit links''' prefix = 'https://www.reuters.com' links = [prefix + x for x in links] '''Reformat time''' dates_stripped = [date.split(" ") for date in dates] index1 = 0 while (index1 < len(dates)): ''' Extract raw time and convert''' year = dates_stripped[index1][2] rawmonth = dates_stripped[index1][0] raw_day = dates_stripped[index1][1] month = time.strptime(rawmonth, "%B").tm_mon day = raw_day.split(",")[0] dates[index1] = str(year) + "-" + str(month) + "-" + str( day) + " 00:00:00" index1 = index1 + 1 dataframe = pd.DataFrame({ 'dates': dates, 'headlines': headlines, 'links': links }) return dataframe def scrape_reuters(query, upper_page_limit=500): index = 1 all_news = pd.DataFrame({ 'dates': [], 'headlines': [], 'links': [] }) '''Loop through subsequent Reuters pages''' while (index <= upper_page_limit): site = 'https://www.reuters.com/assets/searchArticleLoadMoreJson?blob=' + query + '&bigOrSmall=big&articleWithBlog=true&sortBy=relevance&dateRange=all&numResultsToShow=10&pn=' + str( index) + '&callback=addMoreNewsResults' current_site_news = get_headlines(site) all_news = pd.concat([all_news, current_site_news]) index = index + 1 grouped_headlines = all_news.groupby( 'dates')['headlines'].apply(list) grouped_links = all_news.groupby('dates')['links'].apply(list) grouped_news = pd.DataFrame({ 'headlines': grouped_headlines, 'links': grouped_links }) return grouped_news market_name = 'nasdaq' pages_to_scrape = 25 counter_headlines = scrape_reuters( company_name, pages_to_scrape) # scrape company news counter_headlines.columns = ['Company headlines', 'Company links'] market_headlines = scrape_reuters( market_name, pages_to_scrape) # scrape market news market_headlines.columns = ['Market headlines', 'Market links'] all_headlines = pd.concat([counter_headlines, market_headlines], axis=1, sort=False) df["% Change"] = df["Adj Close"].pct_change( periods=ReturnsLBperiod) * 100 threshold = df['% Change'].quantile(ReturnsQuantile) criteria_1 = df["% Change"] >= -threshold criteria_2 = df["% Change"] <= threshold df_filtered = df[criteria_1 | criteria_2] df_news = df_filtered.join(all_headlines) df3 = df.join(counter_headlines) # creating Drawdown dates table df_news.index = pd.to_datetime(df_news.index) DDEnd = pd.to_datetime(pd.Series(df_news.index), format='%Y-%m-%d') DDStart = DDEnd - pd.Timedelta(days=ReturnsLBperiod) df2 = pd.DataFrame({ "Returns Date": DDEnd, "% Return": np.round(df_news['% Change'].values, 2), str(company_name) + "-related Headlines": df_news['Company headlines'].values, "Source: Reuter links": df_news['Company links'].values, "Market Headlines": df_news['Market headlines'].values }) df2 = df2.dropna(subset=[ str(company_name) + "-related Headlines" ]) #to drop if all values in the row are nan ##creating candlestick chart: p = figure(x_axis_type='datetime', width=1000, height=300) p.title.text = "Stock Price Chart for " + str( company_name) + " from " + str( start.strftime('%m/%d/%Y')) + " to " + str( end.strftime('%m/%d/%Y') ) + ", shaded areas represent bottom " + str( round(100 * ReturnsQuantile, 1)) + "%/ top " + str( round(100 * (1 - ReturnsQuantile), 1)) + "% percentile of " + str( ReturnsLBperiod) + "-day returns" p.grid.grid_line_alpha = 0.3 source = ColumnDataSource( data={ 'date': np.array(df.index.values, dtype=np.datetime64), 'close': df['Close'], 'SP move': df['% Change'], 'news': df3['Company headlines'].values }) p.line(x='date', y='close', line_width=2, color='black', source=source) p.add_tools( HoverTool(tooltips=[('date', '@date{%F}'), ('close', '$@close{%0.2f}'), ('SP move', '@{SP move}%'), ('news', '@news{safe}')], formatters={ 'date': 'datetime', 'close': 'printf' }, mode='vline')) ##shading returns period on candlestick chart for i, j, k in zip(DDStart, DDEnd, df_news['% Change'].values): if k < 0: p.add_layout( BoxAnnotation(left=i, right=j, fill_alpha=0.4, fill_color='red')) else: p.add_layout( BoxAnnotation(left=i, right=j, fill_alpha=0.4, fill_color='green')) script1, div1 = components(p) cdn_js = CDN.js_files[0] cdn_css = CDN.css_files[0] return render_template("plot.html", text=df2.to_html(), script1=script1, div1=div1, cdn_css=cdn_css, cdn_js=cdn_js) except Exception as e: return render_template("plot.html", text=str(e))
from bokeh.core.enums import Dimensions from bokeh.models.renderers import Renderer from bokeh.models.callbacks import Callback from bokeh.models.annotations import BoxAnnotation from bokeh.models import ColumnDataSource, Tool, Drag from bokeh.plotting import figure from bokeh.io import curdoc import numpy as np DEFAULT_BOX_OVERLAY = lambda: BoxAnnotation(level="overlay", render_mode="css", top_units="screen", left_units="screen", bottom_units="screen", right_units="screen", fill_color="lightgrey", fill_alpha=0.5, line_color="black", line_alpha=1.0, line_width=2, line_dash=[4, 4]) class SingleBrushTool(Drag): __implementation__ = "singleBrushTool.ts" # source = Instance(ColumnDataSource) # plot = Instance(figure) names = List(String, help=""" A list of names to query for. If set, only renderers that
def make_figure( x, y, target_high=60, target_low=50, window_size=50, x_range=None, y_max_lower_bound=70, y_min_upper_bound=70, plot_width=400, plot_height=150, title="Temperature", y_axis_label="Temperature (F)", x_axis_label="Time", measurement_name="Temp.", tools="pan,crosshair,hover,box_select,lasso_select,save,reset,help"): window = np.ones(window_size) / float(window_size) y_avg = np.convolve(y, window, 'same') y_std = window_stdev(y, window_size) / 2 y_max = max(y.max(), y_max_lower_bound) y_min = min(y.min(), y_min_upper_bound) if x_range == None: x_range = (x.max(), x.min()) plot = figure(plot_width=plot_width, plot_height=plot_height, x_range=x_range, y_range=(y_min, y_max), title=title, x_axis_label=x_axis_label, y_axis_label=y_axis_label, x_axis_type="datetime", tools=tools) if target_high and target_low: upper = BoxAnnotation(bottom=target_high, fill_alpha=0.2, fill_color='red') plot.add_layout(upper) lower = BoxAnnotation(top=target_low, fill_alpha=0.2, fill_color='red') plot.add_layout(lower) target = BoxAnnotation(bottom=target_low, top=target_high, fill_alpha=0.2, fill_color='green') plot.add_layout(target) plot.varea(x=x[window_size // 2:-window_size // 2], y1=y_avg[window_size // 2:-window_size // 2] + y_std[window_size // 2:-window_size // 2], y2=y_avg[window_size // 2:-window_size // 2] - y_std[window_size // 2:-window_size // 2], alpha=0.6, color='darkgray', legend_label='Std. ' + measurement_name) plot.line(x, y, legend_label=measurement_name, color='darkblue') plot.line(x[window_size // 2:-window_size // 2], y_avg[window_size // 2:-window_size // 2], color='black', legend_label='Avg. ' + measurement_name, line_dash=[2]) plot.legend.orientation = "horizontal" return plot
def plot_unranked_influence(csv_filename): influence_results = pd.read_csv(csv_filename) # Create a ColumnDataSource from df: source source = ColumnDataSource(influence_results) TOOLS = "box_select,lasso_select,help,pan,wheel_zoom,box_zoom,reset" TITLE = "Influence scores for training data (colored and ordered by helpfulness)" p = figure(tools=TOOLS, toolbar_location="above", plot_width=800, plot_height=400, title=TITLE) p.toolbar.logo = "normal" color_mapper = LinearColorMapper( palette=Plasma256, low=np.min(influence_results['label'].values), high=np.max(influence_results['label'].values)) # region that always fills the top of the plot upper = BoxAnnotation(bottom=0, fill_alpha=0.025, fill_color='green') p.add_layout(upper) # region that always fills the bottom of the plot lower = BoxAnnotation(top=0, fill_alpha=0.025, fill_color='firebrick') p.add_layout(lower) color_bar = ColorBar(color_mapper=color_mapper, location=(0, 0)) p.add_layout(color_bar, 'right') # add a circle renderer with x and y coordinates, size, color, and alpha cr = p.circle('index', 'score', size=5, fill_color={ 'field': 'label', 'transform': color_mapper }, hover_fill_color="orange", line_color={ 'field': 'label', 'transform': color_mapper }, hover_line_color="orange", fill_alpha=1.0, hover_fill_alpha=1.0, source=source) p.add_tools( HoverTool(tooltips=[("score", "@score"), ('index', '@index'), ("label", "@label"), ('pos_rank', '@pos_rank'), ("neg_rank", "@neg_rank")], renderers=[cr], mode='mouse')) p.outline_line_width = 3 p.outline_line_alpha = 0.15 p.outline_line_color = "navy" p.xaxis.axis_label = 'Index (unranked)' p.yaxis.axis_label = 'Influence Score' output_file("{}_unranked_influence.html".format(csv_filename)) save(p)
director = "邓衍成" source3 = get_source(target_dir_num_score, director) # 邓衍成 p.circle( x='year', y='dirscore', source=source3, size=[i * point_size for i in source3.data["dirnum"]], color=Spectral4[2], fill_alpha=0.6, # 填充的颜色、透明度 legend=director) # 绘制矩形 from bokeh.models.annotations import BoxAnnotation bg = BoxAnnotation(top=badmovie_score, fill_alpha=0.1, fill_color="red") p.add_layout(bg) p.xaxis.axis_line_width = 3 p.yaxis.axis_line_width = 3 p.xaxis.axis_label_text_font_style = "italic" p.yaxis.axis_label_text_font_style = "italic" p.ygrid.grid_line_alpha = 0.8 p.ygrid.grid_line_dash = "dashed" p.xgrid.grid_line_alpha = 0.8 p.xgrid.grid_line_dash = "dashed" p.legend.location = "top_right" p.legend.click_policy = "hide" show(p)
x3, y3 = list(range(40, 50)), list(range(50, 60)) # create a new plot f1 = figure(width=250, plot_height=250, title="Circles") f1.circle(x1, y1, size=10, color="navy", alpha=0.5) # create another one f2 = figure(width=250, height=250, title="Triangles") f2.triangle(x2, y2, size=10, color="firebrick", alpha=0.5) # create and another f3 = figure(width=250, height=250, title="Squares") f3.square(x3, y3, size=10, color="olive", alpha=0.5) #create a span annotation span_4 = Span(location=4, dimension='height', line_color='green', line_width=2) f1.add_layout(span_4) #create a box annotation box_2_6 = BoxAnnotation(left=2, right=6, fill_color="firebrick", fill_alpha=0.3) f1.add_layout(box_2_6) # put all the plots in a grid layout f = gridplot([[f1, f2], [None, f3]]) # show the results show(f)
p3 = figure(title="回售年限-税前回售收益率", tooltips=TOOLTIPS, **options) p3.circle('back_to_sell_years', "income_tosell_before_taxes", color={ 'field': 'credit', 'transform': color_mapper }, size=12, alpha=0.6, source=source) p3.add_layout(color_bar, 'right') # labels = LabelSet(x='back_to_sell_years', y='income_tosell_before_taxes', text='bond_name', level='glyph', # x_offset=10, y_offset=0, source=source, render_mode='canvas') # p3.add_layout(labels) center1 = BoxAnnotation(left=0, right=365, fill_alpha=0.1, fill_color='navy') p3.add_layout(center1) center2 = BoxAnnotation(left=365, right=730, fill_alpha=0.1, fill_color='red') p3.add_layout(center2) center3 = BoxAnnotation(left=730, fill_alpha=0.1, fill_color='green') p3.add_layout(center3) center4 = BoxAnnotation(top=0, fill_alpha=0.1, fill_color='black') p3.add_layout(center4) # 转股价值与价值溢价 # p4 = figure(title="转股价值-价值溢价",tooltips=TOOLTIPS,**options) # p4.circle("to_stock_value", "value_premium", color={'field': 'credit', 'transform': color_mapper}, size=10, alpha=0.6,source=source) # p4.add_layout(color_bar, 'right')
# 显示 show(p) ''' 辅助标注 - 矩形 ''' from bokeh.models.annotations import BoxAnnotation # 导入BoxAnnotation模块 # 创建数据并绘图 x = np.linspace(0, 20, 200) y = np.sin(x) p = figure(y_range=(-2, 2)) p.line(x, y) # 绘制辅助矩形1 upper = BoxAnnotation(bottom=1, fill_alpha=0.1, fill_color='olive', line_width=2, line_dash=[6,2], line_color='red') p.add_layout(upper) # 在图中增加注释 # 绘制辅助矩形2 middle = BoxAnnotation(top=0.6, bottom=-0.6, left=7, right=12, # 设置矩形四边位置 fill_alpha=0.1, fill_color='navy' # 设置透明度、颜色 ) p.add_layout(middle) # 绘制辅助矩形3 lower = BoxAnnotation(top=-1, fill_alpha=0.5, fill_color='firebrick') p.add_layout(lower) # 显示 show(p) ''' 注释 '''
title='不同菜系消费性价比对比', tools=[hover, 'box_select,reset,xwheel_zoom,pan,crosshair'], x_axis_label='人均消费', y_axis_label='性价比得分') p1.circle(x='xf_m', y='xjb_nor', source=source, fill_color='color1', line_color='black', size='size', line_dash=[6, 4], line_width=2, fill_alpha=0.8) xf_qj = BoxAnnotation(bottom=0, top=1.1, left=40, right=80, fill_color='#235789', fill_alpha=0.1) # 平均消费区间 p1.add_layout(xf_qj) #show(p1) #绘制口味分柱状图 p2 = figure(plot_width=800, plot_height=200, x_range=f_source()['typ'], y_range=[0, 1.2], title='不同菜系口味得分', tools=[hover, 'box_select,reset,xwheel_zoom,pan,crosshair']) p2.vbar(x='typ', top='kw_nor', source=source, width=0.5, color='#D94F56') #show(p2) #绘制人均消费得分柱状图
# 纵向的:平均打折占比 height = Span( location=mean_disper, # 设置位置,对应坐标值 dimension='height', # 设置方向,width为横向,height为纵向 line_color='olive', line_width=3, # 设置线颜色、线宽 line_dash="dashed") p.add_layout(height) # 辅助矩形 from bokeh.models.annotations import BoxAnnotation # 象限1:左上 left_up = BoxAnnotation( bottom=mean_discount, right=mean_disper, # 设置矩形四边位置 fill_alpha=0.1, fill_color='olive' # 设置透明度、颜色 ) p.add_layout(left_up) # 象限2:右上 right_up = BoxAnnotation( bottom=mean_discount, left=mean_disper, # 设置矩形四边位置 fill_alpha=0.1, fill_color='firebrick' # 设置透明度、颜色 ) p.add_layout(right_up) # 象限3:左下 left_down = BoxAnnotation(
#f.x_range=Range1d(start=0,end=10) # to define axes #f.y_range=Range1d(start=0,end=5) #f.xaxis.bounds=(2,8) # to restrict axis showed f.xaxis[0].ticker.desired_num_ticks=6 #Styling legend f.legend.location='top_left' f.legend.background_fill_alpha=0 f.legend.border_line_color=None f.legend.margin=60 #create a span annotation for f span_4=Span(location=4,dimension='height',line_color='red',line_width=2) f.add_layout(span_4) #create a box annotation box_2_6=BoxAnnotation(left=2,right=6,fill_color='firebrick',fill_alpha=0.2) f.add_layout(box_2_6) #create annotation description=Label(x=6,y=0.25,text='This graph is for testing', render_mode='css', text_font_size='10px') f.add_layout(description) #create labeles for glyphs labels=LabelSet(x='petal_length',y='petal_width',text='species', source=setosa, text_font_size='5px') f.add_layout(labels) #grid= gridplot([[f],[f1]]) show(f)