Converting Pine Script Indicators Into Python Daily Alerts Report

ltc.png

There is something interesting about candlestick charts. It has to do with patterns, lines, and repetition or an appearance of repetition of similar events. Many traders and investors stare at these charts and try to find an edge, try to get some information that may help them with trades or investments, try to figure out probability of what might happen next at hard right edge. Hard right edge, is what makes these charts interesting.

This is how @azircon explained me once what the hard right edge is:

Hard right edge simply means the right-hand or the last candle on the chart. It is on the extreme right... you can't see any more price after the last candle at the right edge of the chart. But you want to :) You are trying to make a decision, a prediction for the future, which is unknown. It is very hard to make that call.

I mainly use Tradingview for charts. My favorite feature in Tradingview is its native Pine Script programming language and its Pine Editor that allows all users to create their own indicators and display them on charts with few lines of code. If you look at the screenshot above, at the very bottom there are some tabs. One of them is "Pine Editor". By clicking that we open the pine editor and can type in our own pine script code or even used publicly shared ones by others.

When I was experimenting with various indicators I accidentally ended up with this completely useless indicator, I call "Triangle". This super original name is derived from the shape I plotted it with on the chart.

If you look at the daily LTC chart above, you can see two green triangles. If you are me, you would be excited to see what a genius you are to figure out the secret to the markets. Now all you have to do is see when this triangle shows up at the hard right edge to enter into a trade. Unfortunately, the triangles on the screenshot above are deceiving. I have looked at many charts, they work sometimes, they don't work half of the time. So betting on these triangles equal to tossing a coin in making a trade decisions.

The point of this post is not these triangles, but rather the tools we have available to experiment with, come up with our own indicators and then backtest them.

To have those triangles appear on the chart we an write following lines of code in Pine Editor, save the file and apply to chart.

study(title='Triangle', shorttitle='Triangle', overlay = true)
ema5 = ema(close, 5)
ema33 = ema(close, 33)
sma50 = sma(close, 50)
ema5xsma50 = crossover(ema5, sma50) and (ema33 > sma50)
plotshape(ema5xsma50, style=shape.triangleup, size=size.normal, color=green, location=location.belowbar)

If you have tradingview account you can try it yourself. Tradingview allows basic free accounts to use pine script editor. There is no need to subscribe to paid plans to use this feature.

As you can see there is nothing magical about those triangles. They appear when two conditions are met.

  1. EMA-5 crosses over above SMA-50. And,
  2. EMA-33 is higher than SMA-50.

Let's say we have an indicator that we like and we wanted to scan through hundreds of thousands of stocks or crypto tickers and find the ones that have charts that meet the conditions of the indicator. Tradingview is great in displaying charts and indicators and many more things. But for automating and filtering out a list of tickers we may need to consider something else like python.

We can convert the above conditions and logic into python script and runs it as needed. In this case, we probably would want to run the script on daily basis after markets close and see if this would help us make trading decisions for the following market days.

The following code will help us achieve that:

import yfinance as yf
import datetime as dt 
import pandas as pd 
import numpy as np 
from pandas_datareader import data as pdr 
import os 

def get_sma(ser, days):
    sma = ser.rolling(window=days).mean()
    return sma

def get_ema(ser, days):
    sma =  ser.rolling(window=days, min_periods=days).mean()[:days]
    rest = ser[days:]
    ema = pd.concat([sma, rest]).ewm(span=days, adjust=False).mean()
    return ema

def check_triangle(stock):
    yf.pdr_override()
    end_date = dt.datetime.today()
    start_date = end_date - dt.timedelta(days=365*2)

    df = pdr.get_data_yahoo(stock, start_date, end_date)

    df['sma25'] = get_sma(df['Adj Close'], 25)
    df['sma50'] = get_sma(df['Adj Close'], 50)
    df['sma200'] = get_sma(df['Adj Close'], 200)
    df['ema5'] = get_ema(df['Adj Close'], 5)
    df['ema33'] = get_ema(df['Adj Close'], 33)

    df['test1'] = np.where((df['ema5'] > df['sma50']), 1, -1)
    df['test2'] = df['test1'].shift(periods=1)
    df['test3'] = df['test1'] - df['test2']
    df['test4'] = np.where((df['test3'] == 2) & (df['ema33'] > df['sma50']),-1,0)
    
    if df['test4'][-1] == -1:
        return stock
    else:
        return 0

stocks = ['BTC-USD','LTC-USD','A', 'AA', 'AAAU', 'AACG', 'AADR', 'AAIC']

picks = []

for stock in stocks:
    pick = check_triangle(stock)
    if pick != 0:
        picks.append(pick)

print(picks)

The code takes a list of stock/crypto ticker, gets all the historical price data for each ticker from Yahoo Finance, applies all the needed calculations based on the logic described above, and returns a list of tickers that meed the conditions.

Above python code only has eight ticker symbols. My original code has 6992 tickers. That is a lot of stock tickers to go through. We wouldn't have enough time to manually check them all. That's why automating with python is the best.

If you are curious how I have so many tickers, I used python again to get them from Finviz. You can read more on that topic here:

@geekgirl/scraping-ticker-symbols-from-finviz-screener-with-selenium-in-python

Back to the python code above. It is not very complicated. There are two helper functions that calculate SMA and EMA. The main function check_tirangle(stock) does the computing to see if the conditions are met. By changing the logic and conditions within this main function we can reuse this same code for any other indicators.

Another advantage of this code is, we can repurpose it for backtesting.

The if df['test4'][-1] == -1: is checking if we have a triangle for the last candle. By changing [-1] to [-10], we can get the tickers where condition is met 10 days ago. By doing this, we can compare suck results with current price and see if such trade would be in a positive or negative.

As I already mentioned, this "Triangle" indicator is useless. Do not try to use it. Lol. In fact, a couple of days ago, I ran this script and out of 6992 tickers it returned 7 picks - AEHR, IGC, KIDS, MWK, PCYG, TCX, TRT. They all failed.

Most importantly, having tools like Pine Script and Python we can backtest and verify if probabilities of our how our trading ideas may play out.

Do you use any indicators and tools? What are they and how do they help?

H2
H3
H4
3 columns
2 columns
1 column
8 Comments
Ecency