Esempio n. 1
0
def plotaCandlestick(df):
    # recebe o df do ativo e plota Candlestick dinamico

    # fonte dos dados
    source = df

    # configura as cores
    open_close_color = alt.condition("datum.open <= datum.close",
                                     alt.value("#06982d"),
                                     alt.value("#ae1325"))

    # labels no eixo x
    base = alt.Chart(source).encode(alt.X('data:T',
                                          axis=alt.Axis(
                                              format='%d - %m - %Y',
                                              labelAngle=-45,
                                              title='Data: ano - mês - dia')),
                                    color=open_close_color)

    # plotas os traços
    rule = base.mark_rule().encode(
        alt.Y(
            'low:Q',
            title='Preço (R$)',
            scale=alt.Scale(zero=False),
        ), alt.Y2('high:Q')).interactive()

    # plotas as barras
    bar = base.mark_bar().encode(alt.Y('open:Q'),
                                 alt.Y2('close:Q')).interactive()

    # une traços + barras, ajusta tamanho
    return (rule + bar).properties(width=600, height=600)
Esempio n. 2
0
def plot_ind(df, short_var, long_var):
    '''Returns a candlestick chart designed for crossover strategy use.
    Parameters:
        df: DataFrame
        short_var/long_var: str, indicator column names
    Returns:
        Altair Interactive Chart
    '''
    scales = alt.selection_interval(bind='scales')
    move_color = alt.condition('datum.price_close - datum.price_open > 0',
                               alt.value("#047220"), alt.value("#910513"))
    price = alt.Chart(df).mark_line(size=0.5).encode(
        alt.X('date:T', title='Date'),
        alt.Y('price_mean_a:Q', title='Arithmetic Mean Price')).properties(
            width=600, title=df['base_asset_id'].iloc[0]).add_selection(scales)
    candles1 = alt.Chart(df).mark_rule().encode(alt.X('date:T', title=None),
                                                alt.Y('price_low:Q',
                                                      title=None),
                                                alt.Y2('price_high:Q',
                                                       title=None),
                                                color=move_color)
    candles2 = alt.Chart(df).mark_bar().encode(alt.X('date:T', title=None),
                                               alt.Y('price_open:Q',
                                                     title=None),
                                               alt.Y2('price_close:Q',
                                                      title=None),
                                               color=move_color)
    ind1 = alt.Chart(df).mark_line(color='#1967e5').encode(
        alt.X('date:T', title='Date'),
        alt.Y('{}:Q'.format(short_var), title=None))
    ind2 = alt.Chart(df).mark_line(color='blue').encode(
        alt.X('date:T', title='Date'),
        alt.Y('{}:Q'.format(long_var), title=None))
    return price + candles1 + candles2 + ind1 + ind2
Esempio n. 3
0
def plot_leaderboard_time(data, series, file_name):
    """Plots the per-day time distribution for the leaderboard rankings.

    Args:
        data: Leaderboard data frame.
        series: Which series to use; 'one_star' or 'two_stars'.
        file_name: Output file base name.
    """

    print(f'leaderboard_time:{series}')

    quantiles = data.loc[(slice(None), slice(None), [1, 25, 50, 75, 100])].unstack()
    points = (quantiles[series] / 60).rename(columns=lambda r: f'r{r}').reset_index()

    y_title = f'Time to get {series.replace("_", " ")} (ranks 25..75, min)'
    y_scale = alt.Scale(type='log')

    base = alt.Chart(points).encode(x='year:O', color='year:N')
    rule = base.mark_rule().encode(alt.Y('r1:Q', title=y_title, scale=y_scale), alt.Y2('r100:Q'))
    bar = base.mark_bar().encode(alt.Y('r25:Q'), alt.Y2('r75:Q'))
    faceted = (rule + bar).facet(column=alt.Column('day:O', title='Day of contest'))
    faceted.configure_scale(bandPaddingInner=0.4).save(file_name + '.html')

    points['yday'] = points.day + (points.year - points.year.mean())/(1.5*(points.year.max() - points.year.min()))
    alt.Chart(points) \
        .encode(x=alt.X('yday:Q', title='day'), color='year:N') \
        .mark_rule() \
        .encode(alt.Y('r25:Q', title=y_title, scale=y_scale), alt.Y2('r75:Q')) \
        .properties(width=1000, height=600) \
        .save(file_name + '.byday.html')
Esempio n. 4
0
def get_candlestick(data_dict, sampling_freq, **kwargs):
    source = pd.DataFrame(list(data_dict))

    source.ts = source.ts.astype("datetime64[ms]")

    source = source.set_index("ts")

    source = source.price.resample(sampling_freq).ohlc().reset_index().bfill()

    open_close_color = alt.condition(
        "datum.open <= datum.close",
        alt.value(MatColors.GREEN_700.value),
        alt.value(MatColors.RED_700.value),
    )

    base_chart = alt.Chart(source).encode(
        alt.X("ts:T", axis=alt.Axis(labelAngle=-45,)), color=open_close_color
    )

    rule = base_chart.mark_rule().encode(
        alt.Y("low:Q", scale=alt.Scale(zero=False), title="Price"), alt.Y2("high:Q")
    )

    bar = base_chart.mark_bar().encode(alt.Y("open:Q"), alt.Y2("close:Q"))

    return rule + bar
Esempio n. 5
0
def chart_regression(b0,w1,df,show_vlines):
    'Produces chart showing Absatz vs. Werbeausgaben'
    #df["Absatz_Prognose"] = float(b0) + float(w1) *df["Werbeausgaben"] 
    df["Schätzfehler"] = df["Schätzfehler"]
    min_x, max_x = df["Werbeausgaben"].min(), df["Werbeausgaben"].max()
    min_y, max_y = -19,20#df.min().min(), df.max().max()
    points = alt.Chart(df).mark_circle(color="#434A56",size=100).encode(
            alt.X("Werbeausgaben",scale=alt.Scale(domain=(0.9*min_x,1.1*max_x))),
            alt.Y("Absatz",scale=alt.Scale(domain=(0.9*min_y,1.1*max_y))
                , title="Absatz"),
            tooltip= [alt.Tooltip(field="Schätzfehler",title="Schätzfehler",type="quantitative", format=".2f"),
                     alt.Tooltip(field="Absatz_Prognose", title="geschätzter Absatz", type="quantitative", format=".2f")
                    ]
    )
    line = alt.Chart(df).mark_line(color="#F63366", size=2).encode(
            alt.X("Werbeausgaben"),#,scale=alt.Scale(domain=(0.9*min_x,1.1*max_x))),
            alt.Y("Absatz_Prognose")#alt.Y("Absatz_Prognose")
    )
    vlines = alt.Chart(df).mark_rule(color="#434A56").encode(
            alt.X("Werbeausgaben"),
           alt.Y("Absatz_Prognose"),#alt.Y2("Absatz_Prognose")
            alt.Y2("Absatz"),
    )
    if (b0 == 0) & (w1 == 0):
        chart = points
    else:
        chart = points + line 
    if show_vlines: chart = chart + vlines
    return chart.properties(
                                width=780
                            ,   height=400
                            ).interactive()
Esempio n. 6
0
    def draw_single_trend(self,
                          return_chart=False,
                          country_name='Cases',
                          arima_on=True,
                          lstm_on=True):

        df_plot, df_cl = self._create_df_plot(country_name, lstm_on=lstm_on)
        trend_chart = alt.Chart(df_plot).mark_line().encode(
            x=alt.X("Date:T", scale=alt.Scale(zero=False)),
            y=alt.Y("cases:Q", scale=alt.Scale(zero=False)),
            color=alt.Color('Type',
                            sort=[country_name, 'ARIMA_pred', "LSTM_pred"]),
            strokeDash=alt.condition(
                alt.FieldOneOfPredicate(field='Type',
                                        oneOf=['ARIMA_pred', 'LSTM_pred']),
                #((alt.datum.Type == 'ARIMA_pred') or (alt.datum.Type == 'LSTM_pred')),
                alt.value([10,
                           5]),  # dashed line: 5 pixels  dash + 5 pixels space
                alt.value([0])),
            tooltip=["Date:T",
                     "Cases:O"]).properties(width=800,
                                            height=300).interactive()

        band = alt.Chart(df_cl).mark_area(opacity=0.5, color='grey').encode(
            x=alt.X("Date:T", scale=alt.Scale(zero=False)),
            y=alt.Y('lower', title='cases'),
            y2=alt.Y2('upper',
                      title='cases')).properties(width=800,
                                                 height=300).interactive()

        if return_chart:
            return band + trend_chart
        else:
            st.altair_chart(band + trend_chart)
Esempio n. 7
0
def plot_vlines(x,y,y2,df,color="green"):
    'Generates simple altair rule chart'
    alt.Chart(df).mark_rule(color=color).encode(
            alt.X(x),
            alt.Y(y),
            alt.Y2(y2), 
    )
Esempio n. 8
0
def plot_regression(df):
    'Returns components to plot regression based on updated dataframe'

    min_x, max_x = df["Werbung"].min(), df["Werbung"].max()
    min_y, max_y = df[["Absatz",
                       "Prognose"]].min().min(), df[["Absatz",
                                                     "Prognose"]].max().max(),

    scatter = alt.Chart(df.reset_index()).mark_circle(
        size=100, color=colors["darkgrey"]).encode(
            alt.X("Werbung",
                  scale=alt.Scale(domain=(0.8 * min_x, 1.1 * max_x))),
            alt.Y("Absatz",
                  scale=alt.Scale(domain=(-20,
                                          120))),  #(0.9*min_y,1.1*max_y))),
            tooltip=[
                alt.Tooltip("index:Q", title="Datenpunkt"),
                alt.Tooltip("Absatz", format=".2f"),
                alt.Tooltip("Werbung", format=".2f")
            ])
    line = alt.Chart(df).mark_line(color=colors["pink"], clip=True).encode(
        alt.X("Werbung"), alt.Y("Prognose", title="Absatz"))

    error = alt.Chart(df).mark_rule(
        color=colors["darkgrey"], clip=True).encode(
            alt.X("Werbung"),
            alt.Y("Prognose", title="Absatz"),  #alt.Y2("Absatz_Prognose")
            alt.Y2("Absatz"),
        )
    return scatter, line, error
Esempio n. 9
0
File: Heatmap.py Progetto: ccubc/lux
	def initialize_chart(self):
		# return NotImplemented
		x_attr = self.vis.get_attr_by_channel("x")[0]
		y_attr = self.vis.get_attr_by_channel("y")[0]

		chart = alt.Chart(self.data).mark_rect().encode(
			x=alt.X('xBinStart', type='quantitative', axis=alt.Axis(title=x_attr.attribute), bin = alt.BinParams(binned=True)),
			x2=alt.X2('xBinEnd'),
			y=alt.Y('yBinStart', type='quantitative', axis=alt.Axis(title=y_attr.attribute), bin = alt.BinParams(binned=True)),
			y2=alt.Y2('yBinEnd'),
			opacity = alt.Opacity('count',type='quantitative',scale=alt.Scale(type="log"),legend=None)
		)
		chart = chart.configure_scale(minOpacity=0.1,maxOpacity=1) 
		chart = chart.configure_mark(tooltip=alt.TooltipContent('encoding')) # Setting tooltip as non-null
		chart = chart.interactive() # Enable Zooming and Panning

		####################################
		# Constructing Altair Code String ##
		####################################
		
		self.code += "import altair as alt\n"
		# self.code += f"visData = pd.DataFrame({str(self.data.to_dict(orient='records'))})\n"
		self.code += f"visData = pd.DataFrame({str(self.data.to_dict())})\n"
		self.code += f'''
		chart = alt.Chart(visData).mark_rect().encode(
			x=alt.X('xBinStart', type='quantitative', axis=alt.Axis(title='{x_attr.attribute}'), bin = alt.BinParams(binned=True)),
			x2=alt.X2('xBinEnd'),
			y=alt.Y('yBinStart', type='quantitative', axis=alt.Axis(title='{y_attr.attribute}'), bin = alt.BinParams(binned=True)),
			y2=alt.Y2('yBinEnd'),
			opacity = alt.Opacity('count',type='quantitative',scale=alt.Scale(type="log"),legend=None)
		)
		chart = chart.configure_mark(tooltip=alt.TooltipContent('encoding')) # Setting tooltip as non-null
		'''
		return chart 
Esempio n. 10
0
def plot_altair(business=None):
    df = df_no_nan.copy()
    df['IssuedDate'] = df['IssuedDate'].str[0:10]

    dat = df[(df['BusinessName'] == business)]
    dat = dat[["BusinessName", "ExpiredDate", "IssuedDate", "LicenceNumber"]]
    dat = dat.dropna()

    base = alt.Chart(dat).encode(alt.X("LicenceNumber:N",
                                       axis=alt.Axis(title="License Number")),
                                 tooltip="BusinessName")

    area = base.mark_circle(size=100, opacity=0.5, color="#57A44C").encode(
        alt.Y("IssuedDate",
              axis=alt.Axis(title="Issued Date", titleColor="#57A44C")),
        alt.Y2("IssuedDate"),
    )

    line = base.mark_line(stroke="#5276A7", interpolate="monotone").encode(
        alt.Y("ExpiredDate",
              axis=alt.Axis(title="Expired Date", titleColor="#5276A7")))

    chart = alt.layer(area, line).resolve_scale(y="independent").properties(
        width=200, height=300)

    return chart.to_html()
def plot_ginis(df, color_var=None, facet_var=None):

    line = alt.Chart(df).mark_line().encode(
        x=alt.X('x_vals', title='Gene'),
        y=alt.Y('mean_val', title='Gini'),
        color='{}:N'.format(color_var),
        tooltip='gene'
    )

    band = alt.Chart(df).mark_area().encode(
        x=alt.X('x_vals', title='Gene'),
        y=alt.Y('lower_cl', title='Gini'),
        y2=alt.Y2('upper_cl', title='Gini'),
        opacity=alt.value(0.35),
        fill='{}:N'.format(color_var),
        tooltip='gene'
    )

    if color_var is not None:
        plot = (line + band).encode(
            color='{}:N'.format(color_var)
        )
    else:
        plot = line + band

    if facet_var is not None:
        plot = plot.facet(
            row='{}:N'.format(facet_var)
        )

    return(plot)
Esempio n. 12
0
def graph_regression_graph(graph, freq_start, freq_end, withBands=True):

    # regression line
    reg = graph.transform_filter('datum.Freq>{0} & datum.Freq<{1}'.format(
        freq_start, freq_end)).transform_regression(method='log',
                                                    on='Freq',
                                                    regression='dB',
                                                    extent=[20, 20000])

    if withBands:
        # +/- 3dB
        reg3 = reg.transform_calculate(
            dBm3=alt.datum.dB - 3).transform_calculate(
                dBp3=alt.datum.dB + 3).transform_calculate(text='"Band ±3dB"')

        # +/- 1.5dB
        reg1 = reg.transform_calculate(
            dBm1=alt.datum.dB - 1.5).transform_calculate(
                dBp1=alt.datum.dB +
                1.5).transform_calculate(text='"Band ±1.5dB"')

        # band at +/- 3dB
        err3 = reg3.mark_area(opacity=0.06).encode(x=alt.X('Freq:Q'),
                                                   y=alt.Y('dBm3:Q'),
                                                   y2=alt.Y2('dBp3:Q'))

        # band at +/- 1.5dB
        err1 = reg1.mark_area(opacity=0.12).encode(x=alt.X('Freq:Q'),
                                                   y=alt.Y('dBm1:Q'),
                                                   y2=alt.Y2('dBp1:Q'))

    # line
    line = reg.transform_calculate(text='"Linear Regression"').mark_line(
        color='firebrick').encode(
            x=alt.X('Freq:Q'),
            y=alt.Y('dB:Q', axis=alt.Axis(title='dB (normalized)')),
            color=alt.Color(
                'text:O',
                scale=alt.Scale(
                    domain=['Linear Regression', 'Band ±3dB', 'Band ±1.5dB'],
                    range=['firebrick', 'blue', 'blue']),
                legend=alt.Legend(title='Regression')))

    if withBands:
        return (err3 + err1 + line)
    else:
        return line
Esempio n. 13
0
def _render_density(table: alt.Data,
                    *,
                    x_name: str,
                    levels: int,
                    alpha: float,
                    series_selection: alt.Selection = None,
                    selection: alt.Selection = None,
                    x_scale: alt.Scale = alt.Undefined,
                    y_scale: alt.Scale = alt.Undefined) -> alt.Chart:
    areas: List[alt.Chart] = []
    for i in range(1, levels):
        y = f"v{5 - i}:Q"
        y2 = f"v{5 + i}:Q"

        encode = dict(x=alt.X('step:Q', scale=x_scale),
                      y=alt.Y(y, scale=y_scale),
                      y2=alt.Y2(y2),
                      color=alt.Color('series:N',
                                      scale=alt.Scale(scheme='tableau10')))

        if series_selection:
            encode['opacity'] = alt.condition(series_selection,
                                              alt.value(alpha**i),
                                              alt.value(0.001))

        areas.append(
            alt.Chart(table).mark_area(opacity=alpha**i).encode(**encode))

    encode = dict(x=alt.X('step:Q', scale=x_scale, title=x_name),
                  y=alt.Y("v5:Q", scale=y_scale, title='Value'),
                  color=alt.Color('series:N',
                                  scale=alt.Scale(scheme='tableau10')))

    if series_selection:
        encode['opacity'] = alt.condition(series_selection, alt.value(1),
                                          alt.value(0.001))

    line: alt.Chart = (alt.Chart(table).mark_line().encode(**encode))
    if selection is not None:
        line = line.add_selection(selection)

    areas_sum = None
    for a in areas:
        if areas_sum is None:
            areas_sum = a
        else:
            areas_sum += a

    if areas_sum is not None:
        line = areas_sum + line

    if series_selection:
        line = line.add_selection(series_selection)

    return line
def plot_results_static():
    # the base chart
    base = alt.Chart(data).transform_calculate(
        x_jittered = '0.15*(random()-0.5)*datum.timeSeriesLength+datum.timeSeriesLength',
        ymin="datum.confIntLow",
        ymax="datum.confIntHigh",
        goal='0.95')

    #generate the scatter points:
    points = base.mark_point(filled=True).encode(
        x=alt.X('x_jittered:Q', scale=alt.Scale(type='log'), title='Length of Timeseries'),
        y=alt.Y('rate:Q', scale=alt.Scale(domain=[0,1.04]), title='Rate of correct SEM'),
        size=alt.value(80),
        #color=alt.Color('methodName', sort=sort, legend=alt.Legend(title="SEM method")))
        color=col)
    
    #generate the scatter points:
    line = base.mark_line().encode(
        x=alt.X('x_jittered:Q'),
        y=alt.Y('rate:Q'),
        color=col)
    
    #generate the 95% mark:
    rule = base.mark_rule(color='black').encode(
        alt.Y('goal:Q'))

    errorbars = base.mark_rule(strokeWidth=3).encode(
        alt.X("x_jittered:Q"),
        alt.Y("ymin:Q", title=''),
        alt.Y2("ymax:Q"),
        color=col)

    chart = alt.layer(errorbars,
                      points,
                      line,
                      rule,).properties(
        width=250,
        height=200).facet(facet=alt.Facet('trueRho:N',title='Autocorrelation parameter (ρ)'), columns=3)

    chart = chart.configure_header(titleColor='darkred',
                       titleFontSize=16,
                      labelColor='darkred',
                      labelFontSize=14)

    chart = chart.configure_legend(
        strokeColor='gray',
        fillColor='#EEEEEE',
        padding=10,
        cornerRadius=10,
        orient='top'
        )    
    return chart
Esempio n. 15
0
def chart_candlestick(source, cols=[]):
    """Candlestick chart."""
    base = alt.Chart(source).encode(
        alt.X("date:T"),
        color=alt.condition(
            "datum.open <= datum.close",
            alt.value("#06982d"),
            alt.value("#ae1325"),
        ),
    )
    rule = base.mark_rule().encode(
        alt.Y("low:Q", title="Price", scale=alt.Scale(zero=False)),
        alt.Y2("high:Q"))
    bar = base.mark_bar().encode(alt.Y("open:Q"), alt.Y2("close:Q"))
    chart = rule + bar
    for col in cols:
        line = alt.Chart(source).mark_line(color="gray").encode(
            alt.X("date:T"),
            alt.Y(col),
            tooltip=["date", col],
        )
        chart += line
    return chart
Esempio n. 16
0
    def plot_uniqueness_series(self, variable):
        if not super()._confirm_multiple_entries():
            print("Unable to locate multiple entries for", variable,
                  "variable.",
                  "Downgrading to single version of uniqueness plot.")
            self.plot_uniqueness(variable)

        filtered_data = []
        for prof in self.profiles:
            df_flat = prof.flat_summary()['summary']
            if len(df_flat) <= 0: continue
            df_flat.loc[:, 'date'] = prof.data_timestamp
            prof_data = df_flat[df_flat['column'] == variable]
            if len(prof_data) <= 0: continue
            filtered_data.append(prof_data)

        data = pd.concat(filtered_data)
        data.loc[:, "chart_label_area"] = "estimated error"  # \u00B1
        data.loc[:, "chart_label_line"] = "estimated value"

        line = _alt.Chart(
            data[['date', 'chart_label_line', 'mean',
                  'stddev']]).mark_line(strokeWidth=2).encode(
                      _alt.X('monthdate(date):T', title="date"),
                      _alt.Y('mean:Q',
                             scale=_alt.Scale(zero=False),
                             title="values"),
                      _alt.Color('chart_label_line:N',
                                 legend=_alt.Legend(symbolType='stroke')))

        error_bars = _alt.Chart(data[[
            'date', 'chart_label_area', 'mean', 'stddev'
        ]]).mark_area(opacity=0.5).encode(
            x=_alt.X('monthdate(date):T',
                     title="date",
                     axis=_alt.Axis(format="%m-%d")),
            y=_alt.Y('y:Q'),
            y2=_alt.Y2('y2:Q'),
            color=_alt.Color('chart_label_area:N',
                             legend=_alt.Legend(symbolType='stroke')),
            tooltip=_alt.Tooltip([
                'monthdate(date)', 'mean', 'stddev'
            ])).transform_calculate(
                y='max(0, datum.mean + datum.stddev)',
                y2='max(0, datum.mean - datum.stddev)').properties(height=350,
                                                                   width=800)

        chart = _alt.layer(error_bars, line)
        return chart
Esempio n. 17
0
def plot_immunity(data):
    df = data.data[[
        'Date', 'Immunity (Lower Bound)', 'Immunity (Upper Bound)'
    ]].copy()
    df = df.set_index('Date').rolling(window='14d').mean().reset_index()

    chart = alt.Chart(df).mark_area(opacity=0.5).encode(
        x='Date:T',
        y=alt.Y('Immunity (Lower Bound):Q',
                title='Immunity %',
                axis=alt.Axis(format='%')),
        y2=alt.Y2('Immunity (Upper Bound):Q', title=''),
        tooltip=alt.Tooltip('Date'))

    return chart
Esempio n. 18
0
def plot_ind_trade(df, trade_df, short_var, long_var):
    '''Returns a candlestick chart designed for trade on crossover analysis.
    Parameters:
        df: DataFrame
        trade_df: DataFrame
        short_var/long_var: str, indicator column names
    Returns:
        Altair Interactive Chart
    '''
    import pandas as pd
    threshold = pd.DataFrame([{'zero': 0}])
    scales = alt.selection_interval(bind='scales')
    width = 600
    move_color = alt.condition('datum.price_close - datum.price_open > 0',
                               alt.value("#047220"), alt.value("#910513"))
    price = alt.Chart(df).mark_line(size=0.8).encode(
        alt.X('date:T', title='Date'),
        alt.Y('price_mean_a:Q', title='Arithmetic Mean Price')).properties(
            width=width, height=400,
            title=df['base_asset_id'].iloc[0]).add_selection(scales)
    candles = alt.Chart(df).mark_bar(opacity=0.2).encode(alt.X('date:T',
                                                               title=None),
                                                         alt.Y('price_open:Q',
                                                               title=None),
                                                         alt.Y2(
                                                             'price_close:Q',
                                                             title=None),
                                                         color=move_color)
    ind1 = alt.Chart(df).mark_line(color='#1967e5', opacity=0.9).encode(
        alt.X('date:T', title='Date'),
        alt.Y('{}:Q'.format(short_var), title=None))
    ind2 = alt.Chart(df).mark_line(color='blue', opacity=0.9).encode(
        alt.X('date:T', title='Date'),
        alt.Y('{}:Q'.format(long_var), title=None))
    trade = alt.Chart(trade_df).mark_circle(size=100, opacity=1).encode(
        alt.X('date:T', title=None),
        alt.Y('price:Q', title=None),
        color=alt.Color('trade', title='Trade History'))

    portfolio = alt.Chart(trade_df).mark_line().encode(
        alt.X('date:T', title=None),
        alt.Y('profit:Q', title='Profit')).properties(height=100, width=width)
    baseline = alt.Chart(threshold).mark_rule(size=1.25, color='black').encode(
        alt.Y('zero:Q', title=None))

    price_collection = price + candles + ind1 + ind2 + trade
    portfolio_collection = portfolio + baseline
    return price_collection & portfolio_collection
def plot_immunity(data):
    df = data.data[[
        "Date", "Immunity (Lower Bound)", "Immunity (Upper Bound)"
    ]].copy()
    df = df.set_index("Date").rolling(window="14d").mean().reset_index()

    chart = (alt.Chart(df).mark_area(opacity=0.5).encode(
        x="Date:T",
        y=alt.Y(
            "Immunity (Lower Bound):Q",
            title="Immunity %",
            axis=alt.Axis(format="%"),
        ),
        y2=alt.Y2("Immunity (Upper Bound):Q", title=""),
        tooltip=alt.Tooltip("Date"),
    ))

    return chart
Esempio n. 20
0
def _render_density(table: alt.Data,
                    *,
                    name: str,
                    x_name: str,
                    line_color: str,
                    range_color: str,
                    levels: int,
                    alpha: float,
                    selection: alt.Selection = None,
                    x_scale: alt.Scale = alt.Undefined,
                    y_scale: alt.Scale = alt.Undefined) -> alt.Chart:
    areas: List[alt.Chart] = []
    for i in range(1, levels):
        y = f"v{5 - i}:Q"
        y2 = f"v{5 + i}:Q"

        areas.append(
            alt.Chart(table).mark_area(opacity=alpha**i).encode(
                x=alt.X('step:Q', scale=x_scale),
                y=alt.Y(y, scale=y_scale),
                y2=alt.Y2(y2),
                color=alt.value(range_color)))

    line: alt.Chart = (alt.Chart(table).mark_line().encode(
        x=alt.X('step:Q', scale=x_scale, title=x_name),
        y=alt.Y("v5:Q", scale=y_scale, title=name),
        color=alt.value(line_color)))
    if selection is not None:
        line = line.add_selection(selection)

    areas_sum = None
    for a in areas:
        if areas_sum is None:
            areas_sum = a
        else:
            areas_sum += a

    if areas_sum is None:
        return line
    else:
        return areas_sum + line
Esempio n. 21
0
 def get(self):
     val = self.__val()
     if not val:
         return None
     channel = self.channel
     if channel == 'x':
         return alt.X(val, **self.params['config'])
     elif channel == 'y':
         return alt.Y(val, **self.params['config'])
     elif channel == 'color':
         return alt.Color(val, **self.params['config'])
     elif channel == 'size':
         return alt.Size(val, **self.params['config'])
     elif channel == 'column':
         return alt.Column(val, **self.params['config'])
     elif channel == 'row':
         return alt.Row(val, **self.params['config'])
     elif channel == 'x2':
         return alt.X2(val, **self.params['config'])
     elif channel == 'y2':
         return alt.Y2(val, **self.params['config'])
     return None
Esempio n. 22
0
def plot_errb(pdf, ytitle="geomean", zero=True):
    color = "br"
    x = "date"
    y = "p50"

    lb = "p05"
    ub = "p95"

    h = (
        A.Chart(pdf)
        .mark_line()
        .encode(
            x=A.X(x, title=x),
            y=A.Y(y, title=ytitle, scale=A.Scale(zero=zero)),
            color=A.Color(color, title="Branch"),
            tooltip=[color, x, y],
        )
    )
    herr = h.mark_errorband().encode(
        y=A.Y(lb, title=ytitle), y2=A.Y2(ub, title=ytitle)
    )

    return (h + herr).interactive()
def build_candlestick_charts(
        eth_price: pd.DataFrame) -> Tuple[alt.Chart, alt.Chart, alt.Chart]:
    """Given coinmarketcap price table, build candlestick + volume chart."""

    # adapted from https://altair-viz.github.io/gallery/candlestick_chart.html

    base = alt.Chart(eth_price).encode(x='Date')

    rule = base.mark_rule().encode(y=alt.Y('Low',
                                           scale=alt.Scale(zero=False),
                                           axis=alt.Axis(title='Price')),
                                   y2=alt.Y2('High'),
                                   color=open_close_color)

    bar = base.mark_bar().encode(y='Open', y2='Close', color=open_close_color)

    volume: alt.Chart = base.properties(height=100).mark_bar().encode(y=alt.Y(
        'Volume',
        # scale: map from domain to range
        # zero=False: don't include 0 baseline value
        scale=alt.Scale(zero=False)))

    return rule, bar, volume
Esempio n. 24
0
    def make_graph(self):
        debug('new graph')
        get_element_size('graph_container', self.set_size)

        if self.xlabel is None or self.ylabel is None or self.mark is None:
            return

        mark = self.mark_options[self.mark][0]
        xlabel = self.columns[self.xlabel]
        ylabel = self.columns[self.ylabel]
        kwargs = {
            'x': alt.X(xlabel, type=self.guess_datatype(xlabel, mark)),
            'y': alt.Y(ylabel, type=self.guess_datatype(ylabel, mark))
        }

        if self.y2label is not None:
            y2label = self.columns[self.y2label]
            kwargs['y2'] = alt.Y2(y2label)

        if self.shape is not None:
            shape = self.columns[self.shape]
            kwargs['shape'] = alt.Shape(shape, type=self.guess_datatype(shape, mark))

        if self.colors is not None:
            colors = self.columns[self.colors]
            kwargs['color'] = alt.Color(colors, type=self.guess_datatype(colors, mark))

        mark_method = self.mark_options[self.mark][1]

        chart = mark_method(alt.Chart(self.data)).encode(
            **kwargs
        ).interactive().properties(
            width=self.width,
            height=self.height
        )

        set_attribute(self.graph_id, 'srcdoc', html.altair_plot(chart, with_iframe=False))
Esempio n. 25
0
def waterfall_chart(source, decimal=3):
    # set number of decimal places
    source = source.copy()
    for c in ["feature_value", "shap_value"]:
        source[c] = source[c].round(decimal).astype(str)
    source.loc[source["feature_value"] == "nan", "feature_value"] = ""

    bars = alt.Chart(source).mark_bar().encode(
        alt.X("feature:O", sort=source["feature"].tolist(), axis=alt.Axis(labelLimit=120)),
        alt.Y("open:Q", scale=alt.Scale(zero=False), title=""),
        alt.Y2("close:Q"),
        alt.Tooltip(["feature", "feature_value", "shap_value"]),
    )
    color1 = bars.encode(
        color=alt.condition(
            "datum.open <= datum.close",
            alt.value("#FF0D57"),
            alt.value("#1E88E5"),
        ),
    )
    color2 = bars.encode(
        color=alt.condition(
            "datum.feature == 'Average Model Output' || datum.feature == 'Individual Observation'",
            alt.value("#F7E0B6"),
            alt.value(""),
        ),
    )
    text = bars.mark_text(
        align='center',
        baseline='middle',
        dy=-5,
        color='black',
    ).encode(
        text='feature_value:N',
    )
    return bars + color1 + color2 + text
Esempio n. 26
0
def candlestick_chart(source, width=900, height=400):
    """
    Produces a candlestick chart from open, close, high,
    and low data.
    
    Args:
        source (pandas.DataFrame): Stock data with EMA columns.
        
        width (int): Chart width in pixels.
        
        height (int): Total chart height in pixels.
    
    Returns:
        (altair.vegalite.v4.api.Chart): Altair chart object.
    """
    open_close_color = alt.condition("datum.Open < datum.Close",
                                     alt.value("#06982d"),
                                     alt.value("#ae1325"))

    rule = alt.Chart(source).mark_rule().encode(
        alt.X(f'Date:T'),
        alt.Y(
            'Low',
            title='Price',
            scale=alt.Scale(zero=False),
        ),
        alt.Y2('High'),
        color=alt.value('#000000')).properties(
            width=width, height=height).interactive(bind_y=False)

    bar = alt.Chart(source).mark_bar().encode(x='Date:T',
                                              y='Open',
                                              y2='Close',
                                              color=open_close_color)

    return rule + bar
Esempio n. 27
0
          y=alt.Y("wheat:Q", axis=alt.Axis(zindex=1)),
          x2=alt.X2("year_end"))

area = base_wheat.mark_area(**{
    "color": "#a4cedb",
    "opacity": 0.7
}).encode(x=alt.X("year:Q"), y=alt.Y("wages:Q"))

area_line_1 = area.mark_line(**{"color": "#000", "opacity": 0.7})
area_line_2 = area.mark_line(**{"yOffset": -2, "color": "#EE8182"})

top_bars = base_monarchs.mark_bar(stroke="#000").encode(
    x=alt.X("start:Q"),
    x2=alt.X2("end"),
    y=alt.Y("y:Q"),
    y2=alt.Y2("offset"),
    fill=alt.Fill("commonwealth:N",
                  legend=None,
                  scale=alt.Scale(range=["black", "white"])))

top_text = base_monarchs.mark_text(**{
    "yOffset": 14,
    "fontSize": 9,
    "fontStyle": "italic"
}).encode(x=alt.X("x:Q"), y=alt.Y("off2:Q"), text=alt.Text("name:N"))

(bars + area + area_line_1 + area_line_2 + top_bars +
 top_text).properties(width=900,
                      height=400).configure_axis(
                          title=None,
                          gridColor="white",
Esempio n. 28
0
def _lineplot_altair_temp_advanced(data,
                                   x=None,
                                   scenario=None,
                                   climate=None,
                                   impact=None,
                                   shading=False,
                                   title='',
                                   xlabel='',
                                   ylabel=''):
    import pandas as pd
    import altair as alt

    df = pd.concat([pd.DataFrame(l) for l in data.filter_lines()])

    df["model"] = df.climate + " / " + df.impact

    # Divide by 100 so we can percent-format in the plot
    df.y = df.y / 100

    selection_climate = alt.selection_multi(fields=['climate'], bind='legend')

    nearest = alt.selection(type='single',
                            nearest=True,
                            on='mouseover',
                            fields=["x", 'y'],
                            empty='none')

    base = alt.Chart(df[(df.climate != "median")])

    color = alt.Color('climate',
                      scale=alt.Scale(scheme="dark2"),
                      title='Climate Model')

    area = base.mark_area(opacity=0.3).encode(
        x=alt.X("x", scale=alt.Scale(domain=[0, df['x'].max()])),
        color=color,
        y=alt.Y(field="y",
                type="quantitative",
                axis=alt.Axis(format='%'),
                aggregate="min"),
        y2=alt.Y2(field="y", aggregate="max"),
        opacity=alt.condition(selection_climate, alt.value(0.3), alt.value(0)),
    ).add_selection(selection_climate)

    lines = base.mark_line().encode(
        x=alt.X("x"),
        y=alt.Y("y", axis=alt.Axis(format='%')),
        detail=["climate", "impact"],
        color=color,
        opacity=alt.condition(selection_climate, alt.value(0.3), alt.value(0)),
        size=alt.condition("datum.impact == 'median'", alt.value(5),
                           alt.value(1)),
    )

    points = base.mark_point().encode(
        x=alt.X("x",
                axis=alt.Axis(
                    title=xlabel
                    or '{} ({})'.format(data.plot_label_x, data.plot_unit_x),
                    values=data.x)),
        y=alt.Y("y", axis=alt.Axis(title=data.plot_unit_y, format='%')),
        detail=["climate", "impact"],
        color=color,
        opacity=alt.condition(selection_climate, alt.value(0.3), alt.value(0)),
        size=alt.value(12))

    text_model = points.mark_text(align='left', dx=-5, dy=-6).encode(
        text=alt.condition(nearest, "model", alt.value(' ')),
        opacity=alt.condition(selection_climate, alt.value(1), alt.value(0)),
        color=alt.value("black")).add_selection(nearest)

    text_pct = points.mark_text(align='left', dx=-5, dy=6).encode(
        text=alt.condition(nearest, "y", alt.value(' '), format=".2p"),
        opacity=alt.condition(selection_climate, alt.value(1), alt.value(0)),
        color=alt.value("black"))

    chart = (area + lines + points + text_model + text_pct).properties(
        title=data.plot_title,
        width=800,
        autosize=alt.AutoSizeParams(contains="padding", type="fit-x"),
    )

    return configure_chart(chart).interactive()
Esempio n. 29
0
    "low": 25.02,
    "close": 26.35,
    "signal": "long",
    "ret": 6.73758865248228
}])
open_close_color = alt.condition("datum.open < datum.close",
                                 alt.value("#06982d"), alt.value("#ae1325"))

rule = alt.Chart(source).mark_rule().encode(
    alt.X('yearmonthdate(date):T',
          scale=alt.Scale(domain=[{
              "month": 5,
              "date": 31,
              "year": 2009
          }, {
              "month": 7,
              "date": 1,
              "year": 2009
          }]),
          axis=alt.Axis(format='%m/%d', title='Date in 2009')),
    alt.Y('low', scale=alt.Scale(zero=False), axis=alt.Axis(title='Price')),
    alt.Y2('high'),
    color=open_close_color)

bar = alt.Chart(source).mark_bar().encode(x='yearmonthdate(date):T',
                                          y='open',
                                          y2='close',
                                          color=open_close_color)

rule + bar
Esempio n. 30
0
def _lineplot_altair_temp(data,
                          x=None,
                          scenario=None,
                          climate=None,
                          impact=None,
                          shading=False,
                          title='',
                          xlabel='',
                          ylabel=''):

    # median data
    df = data.to_pandas().loc[scenario]
    lower = df.min(axis=0) / 100
    upper = df.max(axis=0) / 100
    median = df.loc['median', 'median'] / 100
    df2 = pd.DataFrame({
        'lower': lower,
        'upper': upper,
        'median': median,
        'climate': 'Median'
    }).reset_index()

    if not title:
        title = data.plot_title
    if not xlabel:
        xlabel = '{} ({})'.format(data.plot_label_x, data.plot_unit_x)
        # xlabel = data.plot_unit_x
    if not ylabel:
        # ylabel = '{} ({})'.format(data.plot_label_y, data.plot_unit_y)
        ylabel = data.plot_unit_y

    # if data.plot_type == 'indicator_vs_timeslices':
    #     x = [xx.split('-') for xx in df2['x']]
    #     df2['x'] = [(int(y1)+int(y2))/2 for y1, y2 in x]
    #     axisX = alt.X('x:Q', title=xlabel, scale=alt.Scale(domain=[1900, 2100]))
    # else:
    axisX = alt.X('x:Q',
                  title=xlabel,
                  scale=alt.Scale(domain=[0, df2['x'].max()]),
                  axis=alt.Axis(values=data.x))

    base = alt.Chart(df2)

    nearest = alt.selection(type='single',
                            nearest=True,
                            on='mouseover',
                            empty='none')
    #                             fields=["x", "median"], empty='none')

    # axisY = alt.Y('median:Q', title=ylabel, axis=alt.Y(format='%'))
    axisY = alt.Y('median:Q', title=ylabel, axis=alt.Axis(format='%'))

    color = 'orange'
    color2 = alt.Color(
        'climate',
        title='Climate Model',
        # scale=alt.Scale(scheme='tableau10'))
        scale=alt.Scale(domain=['Median'], range=[color]))

    area = base.mark_area(opacity=0.3, color=color).encode(
        x=axisX,
        y=alt.Y('lower:Q'),
        y2=alt.Y2('upper:Q'),
    )

    lines = base.mark_line(color=color).encode(
        x=axisX,
        y=axisY,
    )

    points = base.mark_point(size=60).encode(
        x=axisX,
        y=axisY,
        color=color2,
        tooltip=[
            alt.Tooltip('x:Q', title=xlabel),
            alt.Tooltip('median:Q', title=ylabel, format='.1%')
        ],
    )

    chart = (points + lines + area).properties(
        title=title,
        width=800,
        autosize=alt.AutoSizeParams(contains="padding", type="fit-x"),
    )

    return configure_chart(chart).interactive()