Converting Pine Script Indicators Into Python Daily Alerts Report

1 yr
6 Min Read
1124 words


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):
    end_date =
    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
        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:


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:

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?

Posted Using LeoFinance Beta

1 yr (edited)

Wow! You remembered!!

I am sorry...but I often feel when I talk or communicate, people just nod, and say “aah huh” but they are not really listening...they are just humoring me. Do you know the feeling?

So I get pleasantly surprised when people remember! Thank you!

I am so glad you are exploring the scripts and with python too! That cam be useful to you.

With that said let me say something that I have learned over 29 years of trading virtually anything under the sun :)

any indicators are, by definition, derivatives of price and/or volume; therefore they are always slower in giving signal than price and volume

At a given time price is always right and you try and predict prices at a future time which for a single sample size is impossible but for a large number of sample size... a game of probability! This is where any automation can be useful.


I do remember, sometimes.
But I also had to use my Librarian app to get the exact quote.

One thing I always fail to consider is the volume.
I will start paying more attention to it.

I really like automation. But scripts for large samples run long.
For example, to evaluate almost 7 thousand tickers it took this script an hour and a half.

Thank you for advices. I really appreciate them.
I will try to remember. :)

Posted Using LeoFinance Beta


Wow so good. I will go and try it out now. Thanks for the info. I’ve never really be able to explore trading view the way you just did tho I’ve only started using it.


In the past I have played with the mt4 and EAs. But I have only changed values and not programmed. That would also interest me again and then I automate my strategies 😁

Posted Using LeoFinance Beta


My "Square" indicator is superior to this one.


There is no doubt that traders all look for an edge when it comes to markets. It is the nature of the beast. Whether we are talking about stocks, bonds, commodities, or cryptocurrency, a slight edge could be the different between a gain or loss.

Automating the trade signals one gets is a worthwhile approach.

Posted Using LeoFinance Beta