Back to Community
Simple system

I'm new here and looking forward to doing some serious testing. To get me started I would like to see the code for a simple system. for example:

If close of today > high of yesterday and low of today < low of yesterday and RSI(14) < 25 then buy 1 share at the next open.

If anyone can provide a link to an example to get me started I would appreciate.

5 responses

Hi Sol,

I don't have a specific example for what you're looking for but we have a number of different sample algorithms here:
https://www.quantopian.com/help#sample-algos

And taken straight from there is this RSI example algorithm:

# This example algorithm uses the Relative Strength Index indicator as a buy/sell signal.  
# When the RSI is over 70, a stock can be seen as overbought and it's time to sell.  
# When the RSI is below 30, a stock can be seen as oversold and it's time to buy.

# Because this algorithm uses the history function, it will only run in minute mode.  
# We will constrain the trading to once per day at market open in this example.

import talib


# Setup our variables  
def initialize(context):  
    context.stocks = symbols('MMM', 'SPY', 'GE')  
    context.max_cash_per_stock = 100000.0 / len(context.stocks)  
    context.LOW_RSI = 30  
    context.HIGH_RSI = 70  
    # Create a variable to track the date change  
    context.date = None

def handle_data(context, data):  
    todays_date = get_datetime().date()  
    # Do nothing unless the date has changed  
    if todays_date == context.date:  
        return  
    # Set the new date  
    context.date = todays_date

    cash = context.portfolio.cash  
    # Load historical data for the stocks  
    prices = history(15, '1d', 'price')  
    # Use pandas dataframe.apply to get the last RSI value  
    # for for each stock in our basket  
    rsi = prices.apply(talib.RSI, timeperiod=14).iloc[-1]  
    # Loop through our list of stocks  
    for stock in context.stocks:  
        current_position = context.portfolio.positions[stock].amount  
        # RSI is above 70 and we own shares, time to sell  
        if rsi[stock] > context.HIGH_RSI and current_position > 0:  
            order_target(stock, 0)  
            log.info('{0}: RSI is at {1}, selling {2} shares'.format(  
                stock.symbol, rsi[stock], current_position  
            ))  
        # RSI is below 30 and we don't have any shares, time to buy  
        elif rsi[stock] < context.LOW_RSI and current_position == 0:  
            # Use floor division to get a whole number of shares  
            target_shares = cash // data[stock].price  
            order_target(stock, target_shares)  
            log.info('{0}: RSI is at {1}, buying {2} shares.'.format(  
                stock.symbol, rsi[stock], target_shares  
            ))

    # record the current RSI values of each stock  
    record(ge_rsi=rsi[symbol('GE')],  
           spy_rsi=rsi[symbol('SPY')],  
           mmm_rsi=rsi[symbol('MMM')])  

Take a look and see if you can modify those to fit your needs!

Thanks,
Seong

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.

Thanks. Do you have to always specify the price series like in

context.stocks = symbols('MMM', 'SPY', 'GE')

Code cannot be made general and independent on price series?

There are several ways to add securities to your algorithm. You can do it manually, where you create a list of securities (as Seong showed). Other options are:

  • use set_universe() to create an unbiased bundle of stocks based on their DollerVolume traded
  • use Fundamental data to screen stocks and select your universe
  • use Fetcher to import external data

Take a look at the help doc for the full description: https://www.quantopian.com/help#ide-sid-lookup

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.

Hello Alisa,
So if i have a list of stock symbols in a CSV or text file, I can load those in using Fetcher?

Thanks!

Sure! You can use the universe_func parameter to create a dynamically changing universe with Fetcher. Take a look at this example and the API docs under the section "Using Fetcher to create a custom universe".