Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Help with Back test Algorithm coding

Hello everyone,

I am new to using Quantopian's back testing function.
I'm currently trying to write a code that:
1.) Purchases the stock with P% of my capital when the stochastic value is below X
2.) Sells all my positions of the stock when the stochastic value is above Y

I looked into some of the posts that use stochastics to write a strategy, however they didn't quite answer the questions I had.
How should I change the code so that it would apply #1 and #2?

Also:
3.) Is it possible to use Yahoo Finance pricing instead of the builtin price data?
4.) Is it possible to redefine the stochastic equation so that the stochastic value is closer to that of other sources (e.g. Yahoo, Tradingview, etc.)?

Thanks in advance!

Original code from : https://www.quantopian.com/posts/trading-on-stochastic-indicators

3 responses

This may help:

# Talib Stochastic  
import talib  
# ---------------------------------------------------------------------------  
STOCK = symbol('HUYA'); FK = 14; SK = 3; SD = 3; MID = 50; UB = 80; LB = 20;  
# ---------------------------------------------------------------------------  
def initialize(context):  
    schedule_function(trade, date_rules.every_day(), time_rules.market_close(minutes = 1))  
    set_benchmark(STOCK)

def trade(context, data):  
    if get_open_orders(): return  
    bars = FK + SK + SD

    H = data.history(STOCK, 'high',  bars, '1d')  
    L = data.history(STOCK, 'low',   bars, '1d')  
    C = data.history(STOCK, 'close', bars, '1d')

    slowk, slowd = talib.STOCH(H, L, C, FK, SK, SD)  
    k_val = slowk[-1]; d_val = slowd[-1];    

    if k_val >= UB:  
        order_target(STOCK, 0)  
    elif k_val <= LB:  
        order_target_percent(STOCK, 1.0)

    record(K = k_val, D = d_val, mid = MID, top = UB, btm = LB)  

Remember to set your initial capital at $ 50,000.

Hi Vladimir,

Thank you for the prompt response.
It actually worked out pretty well.
I just have one concern. The K value of managed to go past 100. I don't think that's supposed to happen.
Is that an error with talib.stoch?

Also,

Blockquote
if k_val >= UB:
order_target(STOCK, 0)
elif k_val <= LB:
order_target_percent(STOCK, 1.0)

Does this include the conditions that if cash = 0, don't purchase stock.
stock holdings = 0, don't sell stock?

@Frank,

1.Knowing that slowk == fastd, you may use talib fast stochastic:

    fastk, fastd = talib.STOCHF(H, L, C, FK, SK)  
    k_val = fastd[-1];  

2.Run full backtest -> Activity -> Positions -> Load Positions and check if the code meet your intentions.

https://www.quantopian.com/help
order_target
order_target_percent