Back to Community
view buy and sell signals on the chart and table

Hi,

How can I see buy and sell signals on the chart and table, can I draw a forward looking chart with this signals ?

Thanks,

4 responses

Hi Joe,

You can create a custom signal to indicate when the algorithm buys/sells positions by track the length of your portfolio. You can then draw it on the custom graph using the record() function.

For example,

record(pos = len(context.portfolio.positions))  
Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

Alisa, do you have any example of a video of how it looks like? I was trying to search for any kind of an example, but failed to find any.

I mean an example, where I can see a chart with buy and sell entries for a backtesting strategy, even the simplest one.

There isn't a video of how to record signals that I am aware of. However, attached is a backtest which records both a buy and a sell signal. The specific code is

def record_vars(context, data):  
    """  
    Plot variables at the end of each day.  
    Here we record the buy and sell signals returned from our pipeline  
    Record only supports single numeric values.  
    If a signal is a boolean value convert to integer first  
    """  
    pipe_results = algo.pipeline_output('pipeline')  
    record(buy=int(pipe_results.buy_signal), sell=int(pipe_results.sell_signal))

The plot of the signals appears in the bottom of the IDE graph when running 'build algorithm' and labeled 'custom data' (which can be seen in the attached algo below). The signals can also be viewed in the full backtest results by clicking on the activity tab and then clicking custom data.

A few things to note about using the record function.

  • One is limited to 5 variables.
  • One can use multiple record statements within a program (all the variables do not need to be defined at one time).
  • If multiple values are assigned to a record variable, only the last value is recorded each day.
  • In both the IDE and the full backtest windows, individual variables can be toggled on or off by clicking the variable in the legend. This is helpful to hide some of the variables for easier viewing.
  • Finally, in the IDE as the scale gets larger, the plot will automatically shift from daily values to a weekly average. This can be confusing at times. In the case of a 1 or 0 signal, the weekly average may be displayed as a decimal (eg .3).

Hope that helps.

Clone Algorithm
1
Loading...
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
"""
Algo showing how to record a buy/sell signal.
"""
# imports needed for basic algo methods, optimizer, and pipeline
import quantopian.algorithm as algo
import quantopian.optimize as opt
from quantopian.pipeline import Pipeline

# import any needed datasets
from quantopian.pipeline.data.builtin import USEquityPricing

# import any needed built-in factors and filters
from quantopian.pipeline.factors import SimpleMovingAverage
from quantopian.pipeline.filters import QTradableStocksUS, StaticAssets

# import pandas and numpy just in case we need them
import pandas as pd
import numpy as np

def initialize(context):
    """
    Called once at the start of the algorithm.
    """
    # Rebalance every day, 1 hour after market open.
    algo.schedule_function(
        rebalance,
        algo.date_rules.every_day(),
        algo.time_rules.market_open(hours=1),
    )

    # Record tracking variables at the end of each day.
    algo.schedule_function(
        record_vars,
        algo.date_rules.every_day(),
        algo.time_rules.market_close(),
    )

    # Create our dynamic stock selector.
    algo.attach_pipeline(make_pipeline(), 'pipeline')

def make_pipeline():
    # Base universe set to the QTradableStocksUS
    universe = StaticAssets(symbols('SPY'))

    # Factor of yesterday's close price.
    yesterday_close = USEquityPricing.close.latest
    sma_20 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=20)
    sma_200 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=200)
    
    # Rules for our signals
    buy_signal = (yesterday_close > sma_20) & (yesterday_close > sma_200)
    sell_signal = yesterday_close < sma_200

    pipe = Pipeline(
        columns={
            'close': yesterday_close,
            'buy_signal': buy_signal,
            'sell_signal': sell_signal,
        },
        screen=universe
    )
    return pipe

def rebalance(context, data):
   # Gets our pipeline output.
    pipe_results = algo.pipeline_output('pipeline')
 
    # Get the current positions, stocks we want to go long, and exits
    # Use sets for ease in combining using boolean logic
    in_current_positions = set(context.portfolio.positions.keys())
    buys = set(pipe_results.query('buy_signal').index)
    sells = set(pipe_results.query('sell_signal').index)
    
    # Hold anything we want to buy
    # Hold anything we have already bought and still in our current universe,
    # Don't hold anything we have but want to sell.
    # Sell if held too long even if in buy list
    holds = buys | (in_current_positions - sells)
        
    # Make a series of equal weights for anything we want to hold
    # If qty of holds is zero then set weight to zero (avoid divide by 0)
    qty_of_holds = len(holds) 
    weight = 1.0 / qty_of_holds if qty_of_holds else 0 
    target_weights = pd.Series(weight, index=holds)
        
    # Place orders to get to our target_weights
    # Anything not in holds will be closed
    order_optimal_portfolio(
            objective=opt.TargetWeights(target_weights),
            constraints=[],
        )

def record_vars(context, data):
    """
    Plot variables at the end of each day.
    Here we record the buy and sell signals returned from our pipeline
    Record only supports single numeric values.
    If a signal is a boolean value convert to integer first
    """
    pipe_results = algo.pipeline_output('pipeline')
    record(buy=int(pipe_results.buy_signal), sell=int(pipe_results.sell_signal))
 


There was a runtime error.
Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

Thank you, Dan. Is there any ability to plot on the graph itself? E.g. to create a short horizontal line (lenth = from date of entry to predious day) and a down/up arrow for short/long entry.