A code for trading ultra-volatile stocks

Hello there:



As you probably know, US  Stocks generally move faster  right after the market open, that is the case for example of tickers APDN, REV,  PGY and others …  if you watch the charts of those tickers, You'll see that they spiked  very very fast in the morning.



So taking this into account, I was wondering about using 2 technical indicators (SMA and EMA) and a suceesive  higher mediums ( understanding here the mediums are the average between the High and the low of a candle). in order to do so, I used the OCHLV Data fetched in my algorithm.



Once the trading signals are met,  a market order should be sent to  buy it inmediatly, I also use the LOW OF THE DAY (LOD) as my initial risk level (In case the price goes below this level a market order is send to close the position),  this risk level  is going to be changed 1% higher every certain time (30 seconds let's say).  Once this thare is closed,  the program  ends.





  To do all of that I wrote the following code:







 







  import numpy as np

import pandas as pd

import datetime

from datetime import datetime

import pytz

import time

import os

import talib as tb

from time import sleep

 



def initialize(context):

    

    ticker = 'APDN'



    context.security = superSymbol(secType='STK', symbol=ticker, currency='USD', exchange='SMART')

    

def handle_data(context, data):

       



    executed = False

    orders = False

    money = 1000

    while (not executed):

        

        # request OCLHV DATA

        data = request_historical_data(context.security, '30 secs', '750 S', useRTH=0)

        del data['index']

        

        # Adding technical indicators to the data

        data['medium'] = (data['high'] + data['low'])/2    

        data['SMA_9_medium'] = data['medium'].rolling(9).mean()

        data["EMA_20_close"] = tb.EMA(data["close"], timeperiod = 20)

        print(data)

        

        # Define trading signals if conditions are satisfied

        Ma_entry = (data['medium'].iloc[-1] > data['SMA_9_medium'].iloc[-1]) and ( data['medium'].iloc[-1] > data["EMA_20_close"].iloc[-1])

        Med_entry = (data['medium'].iloc[-1] >= data['medium'].iloc[-2]) and (data['medium'].iloc[-2] >= data['medium'].iloc[-3])  

        Entry_signal = Ma_entry and Med_entry 

        

        # Place limit order and stoploss if entry signals are true and wait 30 seconds otherwise

        # Once arders have been placed, wait 10 seconds to verify if they are filled

        if (Entry_signal and (not orders) ):

            entry_price = show_real_time_price(context.security, 'last_price')

            day_candle = request_historical_data(context.security, '1 day', '1 D', useRTH=1)

            LOD = day_candle['low'].iloc[-1]

            order(context.security, (money/entry_price))

            position = get_position(context.security)

            i=0

            while (position.amount >0):

                if show_real_time_price(context.security, 'last_price') <= (1+ i/100)*LOD:

                    order(context.security, -(position.amount))

                i = i +1

                sleep(30)    

            orders = True

        else:

            sleep(30)

             

       

    end()





So what do you think about this code??  could this be profitable ??   Will the code do what I want to do???  Is that a good strategy??  What do you think??

 Is that a good strategy??  What do you think??



Do you Check below strategy matrix

  1. annual returns
  2. maximum drawdown
  3. sharpe ratio

    4) risk and reward ratio

You asked if that was a good strategy… And I think it is… Not for every single ticker… But there are tickers like the ones mentioned before… ( like APDN)… In wich the strategy is indeed profitable… ( now how to identify those tickers is another issue)…



I don't believe anual returns of the stocks are relevante here, since for example like a year and a half ago… Tickers like AMC and GME  had this kind of movements when their fundamentals were bad…  





Now concerning the maximun drawdown of the strategy… How probable is it for a very volatile stock that is trending upwarzs  above the SMA Above the EMA with higher l

Mediums in the 30 se ond intrady chart to fall down very fast  ( in less than 30 se ondas) below the low of the day? ( I don't know how to even begin to answer this… Question if you know  please tell me… But take into account that these stocks that I am referíng to. Move really really fast, they are not like Apple or KO… They move faster than Tesla) 



Concerning the sharpe ratio… It is indeed high… Since the returns of the stocks are of the order  of 10, 15 even 20% or more in less than half hour… (sometimes even a few minutes) 



How do you evaluate the risk reward ratio here?? I dont know…  But it may have to do with the stop loss, if I have initially  my stop loss at the low oof the day… Initially the risk has a certain value… But if the stop loss is increased every certain a Mount of time… The risk will eventually decrease… 

Hello Ghery, 

The code looks fine and it does what you wanted to do as per your trading logic. However, you need to backtest the logic and study the performance over the historical timeframe to understand its profitability. 



As mentioned by Shirish, please study the backtest using the performance metrics. Please check this blog to know all about backtesting, performance metrics, and interpreting and analysing backtesting results. 



Sharpe ratio and maximum drawdown are the two most important performance metrics to analyse the performance of a trading strategy. Please go through the following practice modules to learn the concept, application and python code of Sharpe ratio and maximum drawdown.



Practice module 1: Sharpe Ratio

Practice module 2: Maximum Drawdown



Hope this helps!

 

Thanks a lot, neverteless… I have an issue concerning Sharpe ratio…  But that will be the subject of another post… 

Hello Ghery, your query on the Sharpe ratio has been attended.

Thank you

Thanks to you