NbShare
  • Nbshare Notebooks

  • Table of Contents

  • Python Utilities

    • How To Install Jupyter Notebook
    • How to Upgrade Python Pip
    • How To Use Python Pip
  • Python

    • Python Datetime
    • Python Dictionary
    • Python Generators
    • Python Iterators and Generators
    • Python Lambda
    • Python Sort List
    • String And Literal In Python 3
    • Strftime and Strptime In Python
    • Python Tkinter
    • Python Underscore
    • Python Yield
  • Pandas

    • Aggregating and Grouping
    • DataFrame to CSV
    • DF to Numpy Array
    • Drop Columns of DF
    • Handle Json Data
    • Iterate Over Rows of DataFrame
    • Merge and Join DataFrame
    • Pivot Tables
    • Python List to DataFrame
    • Rename Columns of DataFrame
    • Select Rows and Columns Using iloc, loc and ix
    • Sort DataFrame
  • PySpark

    • Data Analysis With Pyspark
    • Read CSV
    • RDD Basics
  • Data Science

    • Confusion Matrix
    • Decision Tree Regression
    • Logistic Regression
    • Regularization Techniques
    • SVM Sklearn
    • Time Series Analysis Using ARIMA
  • Machine Learning

    • How To Code RNN and LSTM Neural Networks in Python
    • PyTorch Beginner Tutorial Tensors
    • Rectified Linear Unit For Artificial Neural Networks Part 1 Regression
    • Stock Sentiment Analysis Using Autoencoders
  • Natural Language
    Processing

    • Opinion Mining Aspect Level Sentiment Analysis
    • Sentiment Analysis using Autoencoders
    • Understanding Autoencoders With Examples
    • Word Embeddings Transformers In SVM Classifier
  • R

    • DataFrame to CSV
    • How to Create DataFrame in R
    • How To Use Grep In R
    • How To Use R Dplyr Package
    • Introduction To R DataFrames
    • Tidy Data In R
NbShare Notebooks
  • Publish Your Post On nbshare.io

  • R Python Pandas Data Science Excel NLP Numpy Pyspark Finance

TTM Squeeze Stocks Scanner Using Python

In this tutorial, I will build a TTM Squeeze scanner using Python and Mongodb

Let us first import the necessary packages for pandas and pymongo.

In [1]:
import pymongo
from pymongo import MongoClient
import datetime
import pandas as pd

I have stocks data for all stocks in mongodb.
Let us initiate the mongo DB Connection.

In [ ]:
client = MongoClient('mongodb://localhost:27017')
db = client['stocksdb']

Let us look at our stock document. Document is similar to a row in MySQL.

In [4]:
db.stock_data.find_one()
Out[4]:
{'_id': ObjectId('6202f99a80d4ed2d9c536156'),
 'date': datetime.datetime(2020, 1, 2, 0, 0),
 'open': 21.86,
 'high': 21.86,
 'low': 21.315,
 'close': 21.42,
 'adjusted_close': 21.3733,
 'volume': 3062541,
 'ticker': 'AA',
 'perchange': None}

From the collection/table in mongodb, we can retrieve the data by date. For that we need to provide from and to date.

Let us get the data for the last 100 days. To get this data, we will filter the data by date from "today" to 100 days back.

Let us get the today's date in Python datetime format.

In [59]:
today = datetime.datetime.strptime(datetime.datetime.today().strftime('%Y-%m-%d'),'%Y-%m-%d')

Below, i am extracting the date which is 100 days ago from mongoDB.

In [22]:
ticker='AAPL'
date_100_days_ago = db.stock_data.find({'ticker':ticker,'date':{"$lte":today}}).sort([('date',pymongo.DESCENDING)]).limit(100)[99]['date']

Let us get the data for the ticker 'AAPL' using above dates.

In [54]:
fdocs = db.stock_data.find({'ticker':ticker,"$and": [ { 'date': {"$lte": today} }, { 'date': { "$gte": date_100_days_ago } } ] },{'_id':0,'adjusted_close':0,'volume':0,'ticker':0,'perchange':0}).sort([('_id',pymongo.DESCENDING)])
df = pd.DataFrame(list(fdocs))
df = df[::-1]
In [55]:
df.head(1)
Out[55]:
date open high low close
0 2022-11-16 149.13 149.87 147.29 148.79

(Optional) - Let us rename the columns to make first lettter upper case.

In [12]:
df.rename(columns = {'date':'Date','open':'Open','high':'High','low':'Low','close':'Close'},inplace=True)

Let us wrap the above code inside a function so that we can run it for any stock.

In [28]:
def get_stocks_dataframe(ticker):
    fdocs = db.stock_data.find({'ticker':ticker,"$and": [ { 'date': {"$lte": today} }, { 'date': { "$gte": date_100_days_ago } } ] },{'_id':0,'adjusted_close':0,'volume':0,'ticker':0,'perchange':0}).sort([('_id',pymongo.DESCENDING)])
    df = pd.DataFrame(list(fdocs))
    df.rename(columns = {'date':'Date','open':'Open','high':'High','low':'Low','close':'Close'},inplace=True)
    df = df[::-1]
    return(df)

Lastly, the below snippet of code will calculate the bollinger band, keltner channel and prints the stocks which are in and out of ttm squeeze.
Note the criteria to find "out of squeeze" stocks can be changed in the following code...
df.iloc[-2]['squeeze_on'] and not df.iloc[-1]['squeeze_on'].
In above code snippet, I am checking whether the previous day, stock was in "in squeeze".

In [ ]:
def in_squeeze(df):
    return df['lband'] > df['lkeltner'] and df['uband'] < df['ukeltner']

dataframes = {}

#loop through all the stocks
for doc in db.stock_data.find():
    symbol = doc['symbol']
    #get dataframe from mongoDB
    df = get_stocks_dataframe(symbol)
    try:
        df['20sma'] = df['Close'].rolling(window=20).mean()
        df['stddev'] = df['Close'].rolling(window=20).std()
        #lower band
        df['lband'] = df['20sma'] - (2 * df['stddev'])
        #upper band
        df['uband'] = df['20sma'] + (2 * df['stddev'])

        df['TR'] = abs(df['High'] - df['Low'])
        df['ATR'] = df['TR'].rolling(window=20).mean()

        #lower keltner channel
        df['lkeltner'] = df['20sma'] - (df['ATR'] * 1.5)
        #upper keltner channel
        df['ukeltner'] = df['20sma'] + (df['ATR'] * 1.5)

        df['squeeze_on'] = df.apply(in_squeeze, axis=1)
        
        if df.iloc[-2]['squeeze_on'] and not df.iloc[-1]['squeeze_on']:
            print(symbol,"out of squeeze")
        if df.iloc[-1]['squeeze_on']:
            print(symbol,"in squeeze")
    except:
        continue
        
    dataframes[symbol] = df

Related Notebooks

  • How To Calculate Stocks Support And Resistance Using Clustering
  • Pandas Datareader To Download Stocks Data From Google And Yahoo Finance
  • Crawl Websites Using Python
  • Understanding Logistic Regression Using Python
  • Understanding Word Embeddings Using Spacy Python
  • Demystifying Stock Options Vega Using Python
  • How to Visualize Data Using Python - Matplotlib
  • How To Read CSV File Using Python PySpark
  • How To Read JSON Data Using Python Pandas

Register

User Already registered.


Login

Login

We didn't find you! Please Register

Wrong Password!


Register
    Top Notebooks:
  • Data Analysis With Pyspark Dataframe
  • Strftime and Strptime In Python
  • Python If Not
  • Python Is Integer
  • Dictionaries in Python
  • How To install Python3.9 With Conda
  • String And Literal In Python 3
  • Privacy Policy
©