Back to Community
Seeking Help to Check if Strategy is Correctly Coded

Hi All,

I've recently been experimenting with a trading strategy and discovered Quantopian and decided it'd be a good opportunity to try out the platform but I'm having a really tough time trying to code out the strategy. My only coding experience is with VBA and despite searching around the internet, I can't really find the answers to my questions below and would appreciate any help at all! I have a decent amount of experience with trading but none with Algo Trading.

Main points of the strategy:
-Plot 3 SMAs of 4 , 9 , 18
-Buy/sell when all SMAs point in the same direction (e.g. when they all point up, buy. Sell when they all point in the same direction)
-Close out the trade after 1 period (if Taking profit)
-Set a stop loss just below the previous day low (if buying. reverse for selling)

Difficulties in coding:
-Firstly, I've spent 2 days thinking about it but I can't figure out how I would code something to execute when all 3 SMAs point in the same direction. I suppose I could attempt to code it by attempting to calculate the gradient and buying if all of it > 0 and selling if all < 0 but I couldn't get it to work. [I'm fully aware that the method I tried to execute in the attached code is not what I described. I couldn't get it to work so I was just experimenting with other methods]
-Secondly, the strategy works best on a 30-minutes time frame based off my manual testing, but I can't figure out how to code it to execute on a 30-minute time frame on Quantopian.
-Thirdly, I'm having trouble determining if my strategy is actually doing what I think it is doing. It doesn't seem to me like the stop loss I coded is actually working.

I would GREATLY appreciate it if anyone could help me with any of the 3 points I've raised above.

Thanks!

Clone Algorithm
1
Loading...
Backtest from to with initial capital
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
# Put any initialization logic here.  The context object will be passed to
# the other methods in your algorithm.
def initialize(context):
    context.security = symbol('SBUX')

    schedule_function(rebalance,
                      date_rule = date_rules.every_day(),
                      time_rule = time_rules.market_close())
    
def rebalance(context,data):
    for stock in context.portfolio.positions:
        order_target_percent(stock,0)
                      
# Will be called on every trade event for the securities you specify. 
def handle_data(context, data):
    print(data)
    
    MA1 = data[context.security].mavg(3)
    MA2 = data[context.security].mavg(4)
    MA3 = data[context.security].mavg(8)
    MA4 = data[context.security].mavg(9)
    MA5 = data[context.security].mavg(17)
    MA6 = data[context.security].mavg(18)
    stoploss = history(2, '1d', 'close_price') 
    
    cash = context.portfolio.cash
    current_position = context.portfolio.positions
    todayprice = data[context.security].price
    
    for stock in data:
        current_position = context.portfolio.positions[stock].amount
       
        try:
            if current_position == 0:
                 if (MA2 < MA1) and (MA4 < MA3) and (MA6 < MA5):
                      order_percent(stock, -.3)
                    
                 elif (MA2 > MA1) and (MA4 > MA3) and (MA6 > MA5):
                    order_percent(stock, .3)
                 
            if current_position < 0:
                if todayprice > stoploss:
                            order_target(stock, 0)
            
            if current_position > 0:
                if todayprice < stoploss:
                            order_target(stock, 0)
            
        except Exception as e:
                    print(str(e))
                    

                    
    
    
    
There was a runtime error.
3 responses

some help:
- pointing up means today > yesterday
- check out the example that uses 'record', so you can see what is going on.
- get it working with 1 moving average, then expand

good luck

To retrieve past price (and volume) data, you need to use the history function correctly. It returns a pandas.DataFrame with columns representing securities and rows representing time bars. Read the online manuals about both.

Hi Steve,

Here's a video tutorial that gives a quick explanation of the history() function!

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.