Professional Documents
Culture Documents
Introduction
1.1 Introduction To Python
Python is a modern day programming language. It is the most simplified
version of human-machine interaction.
Python’s official description:
It has efficient high-level data structures and a simple but effective
approach to object-oriented programming. Python's elegant syntax and
dynamic typing, together with its interpreted nature, make it an ideal
language for scripting and rapid application development in many areas on
most platforms.
Features of python
● Simple
● Open Source
● Easy syntax
● Powerful Looping
● High-Level Language
● Object-Oriented
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
1.2 Installing & Setting Up Python
Visit https://www.python.org/downloads/ and download the latest version.
The current version of python is 3.8.2 and it gets updated pretty fast.
Double click on exe to install.
Please make sure you check the option Add Python 3.8.2 to the PATH.If
you forget to add python 3.8.2 to path, go to environment variables in
windows and add python to PATH. This will enable you to access it from
the command prompt.
The default interface which will be installed along with python is called
IDLE. It runs the code line by line and is the least preferred option to work
with. There are various IDEs which support python. The simplest and the
most powerful being Jupyter notebook, which will be discussed further.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
1.3 Installing PIP
PIP is the package installer for python. By using pip you can install any
library you need. The library is a collection of pre-coded files which serves
a purpose, they are built for specific purposes and can be used within our
code.
The module PIP comes pre-installed in most of the python installations. If it
is not there, you can install it by following the below mentioned steps.
To install PIP, you need to download the get-pip.py file from
https://bootstrap.pypa.io/get-pip.py .
Open this link in any browser and save it by pressing Ctrl+S . The
directory in which you are saving this file should be the same as the one in
which python is installed.
After saving the file, go to command prompt and write the following code
python get-pip.py
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
1.4 Installing Jupyter Notebook
It is a web-based interpreter, used to run python code. It holds the title of
being the simplest interpreter.Installing a Jupyter notebook is pretty simple.
Go to command prompt and run the following code:
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
1.5 Working With Jupyter Notebook
Working with a Jupyter notebook is pretty easy. Just open the command
prompt and type Jupyter notebook. Surprisingly, it will open in a browser
window.
To create a new notebook, click New on the top right corner and select
python3 from there.This will open up a new file.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 2
Variables
2.1 Input Variables
Variables in Python are used to store data or collections of data. Python uses
dynamic casting to store data which means unlike languages like C, C++,
etc. There is no need to initialize variables with data type in python.
Example:
stoploss = 5
target=50
stock_name = ‘Reliance’
exchange = “NFO”
Rules for variable declarations in python -
● A variable name must start with a letter or the underscore character
● A variable name cannot start with a number
● A variable name can only contain alpha-numeric characters and
underscores
● Variable names are case-sensitive
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
2.2 User Input
Input can be provided to the program in python using the “input” function.
We can ask the user to input values if they aren’t pre-defined
Example:
stoploss = input()
A predefined message can also be outputted while taking the input by
putting that message as a function parameter.
Example:
a = input(“What is your stop loss?”)
Python always takes inputs as a string. Hence to use the input as a number,
i.e. to perform addition, subtraction, multiplication, etc, you need to convert
the input to a number, using an appropriate function like int(), float(), etc.
Depending on the type of variable you want.
Example
a = int(input()) #for integers
b = float(input()) #for numbers with
decimal point
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
2.3 Types Of Variables
There are various types of variables:
1. Integer:
Example: ‘Nifty’,’Banknifty’.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
2.4 Printing A Variable
The print function gives a standard output. The output is displayed on the
screen which helps us to verify our input.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
2.5 Identify Variable Type
The type of variable you have entered.How it works:
quantity = 1
print(type(quantity))
Output :
<class int>
Example 1:
price=52.35
print(type(price) )
Output:
<class float>
Example 2:
stock_name =’Reliance’ ’
print(type(stock_name))
Output:
<class str>
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
2.6 Type Casting
We can convert one data type into another by using typecasting. Below
shown is how it works
price = 50.50
print(type(price))
Output:
<class float>
We can convert this price which is in float to an integer by using the
following command
print(int(price))
Output:
50
In a similar way, int, float, string can be converted from one to another. The
only exception is strings formed using characters cannot be converted to int
or float.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 3
Strings
3.1 Introduction
A string is a sequence of characters. Strings are basically just a bunch of
words.Strings form an integral part of every program. Whenever we define
any variable, we have to use strings. Strings are defined in quotes. There are
3 types of quotes in python.
Single quotes
Writing your string in single quotes is like ‘What is your stoploss’
Double quotes
Strings in double quotes work exactly the same way as strings in single
quotes.
Example: “What is your stoploss”
Triple Quotes
Strings in triple quotes are used as comments. Comments basically mean
you don’t want to include them in the program. They are in simple english
and placed above almost every line of code. They help us understand how
the code is structured and what the code is doing.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
Indentation:
Indentation refers to the spaces at the beginning of a code line. Indentation
is very important in python. Python uses indentation to indicate a block of
code. Indentation is used by clicking either one tab or four spaces and using
only one of them at a time for better code management.
Example-
if 10>5:
print (‘Ten is greater than five’)
Python will give you an error if you skip the indentation.
Example-
if 10>5:
print (‘Ten is greater than five’)
In this example, it will show you a Syntax error.
Alias:
In python, Alias is an alternate name for referring to the same thing.
Create an alias with the ‘as’ keyword while importing:
import numpy as np
import pandas as pd
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
3.2 Splitting A String
We can split the string into various parts. The splitting can be done using
any character or special character.
Example:
stock_name=”Reliance-NFO”
print(stock_name.split(“-”))
Output:
['Reliance', 'NFO']
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
3.3 Slicing A String
We can slice the string using the length function. The first step in slicing a
string is finding its length.
How it works:
stock_name=”Reliance-NFO’
print(len(stock_name))
Output:
12
If we want to slice string, we can do it
Example 1:
string=”Price of Reliance is 1400”
print(string[9:17])
Output:
Reliance
Example 2:
print(string[21:])
Output:
1400
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
3.4 Concatenate String
String concatenation means merging 2 strings into one string. How it works:
stock_name = "Reliance"
exchange="NFO"
Combined_name=print(stock_name+exchange)
Output:
RelianceNFO
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
3.5 String Formatting
We use it to format a string in a manner we want.
price = 1400
stock_name = “Reliance”
print('{0} is trading at Rs
{1}'.format(stock_name, price ))
Output:
Reliance is trading at Rs 1400.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 4
Operators
4.1 Arithmetic, Assignment, Comparison Operators
Arithmetic operators in python are used with numeric values to perform common mathematical
operations.
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
== Equal x == y
!= Not equal x != y
and Returns True if both statements are true x < 5 and x < 10
not Reverse the result, returns False if the not(x < 5 and x < 10)
result is true
Identity operators in python are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
Conditional Statements
5.1 If
If statements are conditional statements in python which roughly translates
to english as - if the condition is true then execute this code block. If the
condition of an if returns a boolean True then the code block of that if is
executed.
Example-
stock_price = 5
if (stock_price>2):
print(“greater”)
Output-
greater
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
5.2 IF Else
If Else are one of the most common keywords in any language which
describe the conditional changes during the execution of the code. The code
block of if is executed if the condition of if is true but if it is not true then
the code block of else is executed.
Example:
stock_price = 5
if(stock_price=4):
print("stock_price is 4")
else:
print("stock_price is not equal to 4")
Output:
stock_price is not equal to 4
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
5.3 ElIf
Mostly the if statement cannot hold all the possible conditions of an
outcome. Hence the elif or as we speak elseif; condition is checked. The
number of elif can be more than one for an if statement.
Example:
stock_price = 4
if(stock_price>5):
print("Big")
elif(stock_price<5):
print("Small")
else:
print("Match")
Output:
Small
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
5.4 Nested If
If statements are used for conditional executions in python. If-elif-elif- -else
is the basic structure of any Nested If statements. It basically follows a top
down approach, first the if condition is tested, if that is true then the if block
statements are executed but if not then the first elif statement is tested and
executions are performed based on its truth value. After all if and elif are
tested and none are true then at last the else statement is executed.
Example:
x = 4
if(x>4):
print(“greater”)
if(x<4):
print(“less”)
else:
print(“equal”)
Output:
Equal
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 6
Loops
6.1 For Loop
For loop is used for iterations in python. It is used to iterate over lists,
tuples, generators etc.Unlike other languages like C, C++ etc, python does
not support numeric for loops by default. To iterate over a range of numbers
one has to create a range generator by specifying starting, ending, and jump
value to the range function.
Example :
for x in range(1,5,2):
print(x)
Output :
1
3
For loops can also iterate over predefined arrays and tuples by using the
“in” keyword.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
Example:
a = [“a”,”b”,”c”]
for x in a:
print(x)
Output:
a
b
c
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
6.2 While
While loops are similar to for loops in the manner that they repeat the same
code lines over and over again but different in the sense that they are not
statically driven. It means that the looping condition of while loops can
change during the execution of the loop unlike in the case of for loops
where the driving condition remains same during the entire execution.
Example -
x = 4
while x>1:
print(x)
x-=1
Output-
4
3
2
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
6.3 Continue & Pass
Just like any other programming language the “continue” statement is used
to skip the current loop state in a python for or while loop.
Example-
for x in range(8):
if(x%2):
continue
else:
print(x)
Output-
1
3
5
7
Execution blocks in python whether they belong to if, elif, else, try, except,
function, class, etc can never be empty. But due to certain conditions we
need to keep them empty for say, testing, development or code requirement.
Hence to keep an execution statement from performing any execution
“pass” keyword is used to tell the compiler to do nothing if this keyword is
encountered.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
Example-
A = 10
if(A>10 or A<10):
pass
else:
print(“A is 10”)
Output-
A is 10
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
6.4 Break
Break statement is executed when they meet a condition, which is checked
in the loop during every iteration. Break statement ends the loop and
executes the code, written after the loop.
Simply known as coming out of the loop.
Example of Break-
i=1
while(i<10):
print(i)
If (i==5):
break
i=i+1
Output-
1
2
3
4
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 7
Lists
7.1 Introduction To List
Lists in python contain one or more than types of data at linear indices
starting from 0. In Python lists can be defined by using the keyword “list”
or by directly placing the data of the list into square brackets “[ ]” .
Example-
a = [1,2,3,4]
print(type(a))
Output-
<class 'list'>
The data inside a list can be accessed by providing the index of the data to
the list inside square brackets or by iterating over it inside a for loop.
Example-
a = [1,2,3,4]
print(a[-1])
Output-
4
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
Example-
a = [1,2,3]
for x in a:
print(x)
Output-
1
2
3
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
7.2 Add & Remove Items In List
Items can be added to a list using the append function. Append function
adds an item to the list by increasing it length then inserting it at the end.
Example -
a = [1,2,3,4]
print(a)
a.append(0)
print(a)
Output -
[1, 2, 3, 4]
[1, 2, 3, 4, 0]
Data can also be added to the list by assigning data to a pre existing index
of a list.
Example-
a = [1,2,3,4]
print(a)
a[2] = 7
print(a)
Output-
[1, 2, 3, 4]
[1, 2, 7, 4]
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 8
Tuple
8.1 What Is Tuple
A tuple is an immutable sequence of Python objects. Tuples are sequences,
just like lists. The differences between tuples and lists are, the tuples cannot
be changed unlike lists and tuples use parentheses “( )”, whereas lists use
square brackets “[ ]”.
Tuples are statically created hence they cannot be mutated once they are
created and this makes using them faster than lists. They can be created
using parentheses and commas for separating objects.
Example -
a = ('a',1,"hello")
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
8.2 Operation In Tuple
Python Expression Results Description
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 9
Dictionary
9.1 Loop Through Dictionary
Dictionary is similar to a list in the manner that it stores data at indices too
but different in the sense that in a dictionary we have to define the index at
which we need to place data, there is no function like append, for a
dictionary and indices can be string too.
A dictionary has two variables per entry - a key and a value. They can be
accessed using the items function over a dictionary object. The items
function returns a list of tuples containing key value pairs which can be
iterated over using a for loop.
Example-
a = {'one':1,"apple":"banana",8:9}
for k,v in a.items():
print(f"{k} -> {v}")
Output-
one -> 1
apple -> banana
8 -> 9
_________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
9.2 Add/Remove Items In Dictionary
Adding data to a dictionary is similar to adding data to a list at an index, but
there is a small difference that in a dictionary you can create any index
irrespective of its order or data type.
Example-
a = {'one':1,"apple":"banana",8:9}
a['newData'] = 4
print(a)
Output-
{'one': 1, 'apple': 'banana', 8: 9, 'newData':
4}
Deletion operation in dictionaries is also very simple. It is done using the
“del” keyword.
Example-
a = {'one':1,"apple":"banana",8:9}
del a['one']
print(a)
Output-
{'apple': 'banana', 8: 9}
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 10
Functions
10.1 Introduction To Function
Function is a block of code that performs a specific task. We can do many
things using functions. Some of the advantages of using functions are listed
below:
1. Code Reusability: We are writing an application in Python where we
need to perform a specific task in several places of our code, assuming that
we need to write 10 lines of code to do that specific task. It would be better
to write those 10 lines of code in a function and just call the function
wherever needed.
2. Improves Readability: By using functions for frequent tasks you make
your code structured and readable. It would be easier for anyone to look at
the code, and helps us in making tidier code.
3. Avoid redundancy: When you no longer repeat the same lines of code
throughout the code.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
10.3 Lambda Functions/ Anonymous Functions
Anonymous functions are functions without names. Lambda keyword is
used to create anonymous functions. Lambda function does not include a
“return” statem-ent, it always contains an expression which is returned.
Example-
g=lambda x: x*x*x # here x is the argument
and x*x*x is the expression
g(2)
Output:
8
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 11
Classes & Objects
11.1 Object Oriented Programming
Python as a language supports Object Oriented Programming (hereafter
called as OOP). OOP is an approach for writing programs in which data and
behaviour are blinded together as classes and the instances of these classes
are defined objects. The OOP is based on certain concepts which are briefly
defined as below.
1. Data Abstraction – It is the way of representing the essential features
without including the background details and explanations.
Example:
Your car is a great example of abstraction. You can start a car by turning the
key or pressing the start button. You don't need to know how the engine is
getting started, what all components your car has. The car internal
implementation and complex logic is completely hidden from the user.
2. Data Hiding – Data hiding ensures exclusive data access to class
members and protects object integrity by preventing unintended or intended
changes .Data hiding insulates the data from the straight access by the
program.
Example:
You have an account in a XYZ Bank.You can only transfer or check money
in your account.You can’t edit the money in your account. This is called
Data Hiding.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
11.2 Class
A Class is a way to bind the data and its associated functions together. For
instance, consider a fruit having characteristics, taste, colour and its size.
When a class is defined, memory is allocated for its member functions and
they are stored in the memory. When an object is created, separate memory
space is allocated for its data members. All objects work with one copy of
the member function shared by all. The declaration of a class involves three
things:
1. Data members which are the data type properties to describe the
characteristics of a class.
2. Member functions are the set of operations to be carried out to objects
of that class. They are referred to as class interfaces.
3. Access levels that control access to members from within the program.
These access levels are private, public or protected. Depending upon the
access level of a class member, access to it is allowed or denied.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
11.3 Implementation Of Objects In Python
The objects are implemented through member functions called as methods
and it is given a unique name to make it identifiable in a unique manner.
Once a class has been defined, its objects can be created like any other
variable, using the class name as type specifier.
Example-
class data:
def __init__(self, symbolName, market):
self.symbol = symbolName
self.market = market
self.ltp = []
def newLtp(ltp):
self.ltp.append(ltp)
nifty = data(‘Nifty’,’NSE’)
bankNifty = data(‘Nifty Bank’,
’NSE’)
gold = data(‘GOLD APR FUT’, ’
NFO’)
nifty.newLtp(51341.12)
nifty.newLtp(51341.45)
nifty.newLtp(51341.44)
gold.newLtp(37920.14)
gold.newLtp(37921.55)
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
Here data is the class and nifty, bankNifty, gold are the objects of that class.
The class stores the symbols’ name, its market and list to store all its ltp
values.
_____________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 12
NumPy
12.1 NumPy
NumPy is an inbuilt library, which is used for numerical computations. It is
basically used because of its computational efficiency in terms of speed.
Numerical python (NumPy) supports multidimensional arrays over which
you can easily apply mathematical operations. It is a single (homogeneous)
data type. NumPy’s arrays class is “ndarray,” also referred to as
“numpy.array”
Installing NumPy-
!pip install numpy
Once NumPy is installed, import it into your application by adding the
“import” keyword.
Example-
a=[1,2,3,4,5]
b=[2,4,6,6,8]
npa_array=np.array(a)
npb_array=np.array(b)
npa_array+npb_array
Output-
array([3,6,9,10,13])
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
Where
This function returns elements chosen from x or y depending on condition.
numpy.where(condition[, x, y])
here,
condition : Where True, yield x, otherwise yield y.
x : yielded when condition is True
y : yielded when condition is False
If the yielding elements x and y are not provided the True and False are
yielded as the placeholders.
Example -
a = np.array(range(10))
np.where(a < 5, a, 10*a)
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
Output -
array([ 0, 1, 2, 3, 4, 50, 60, 70, 80, 90])
Random
This function returns random integers from low (inclusive) to high
(exclusive). It returns random integers from the “discrete uniform”
distribution of the specified dtype in the “half-open” interval [low, high). If
high is None (the default), then results are from [0, low).
numpy.random.randint(low,high=None, size= None ,
dtype=int)
here,
low : range starting
high : range ending
size : size of output array
dtype : data type of output
Example -
np.random.randint(5,10,(3,4))
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
Output -
array([[6, 8, 7, 9],
[5, 5, 5, 9],
[9, 8, 6, 7]])
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 13
Pandas
13.1 Data Frame & Series
Pandas is a fast, powerful, flexible and easy to use open source data
analysis and manipulation tool, built on top of the Python programming
language.
A Data frame is a two-dimensional data structure, in which data is aligned
in a tabular fashion in rows and columns.
Pandas Series is a one-dimensional labeled array capable of holding data of
any type. The axis labels are collectively called indexes. Pandas Series is
nothing but a column in an excel sheet.
Installing Pandas-
pip install pandas
Series and DataFrames can be created with different data inputs :-
1.list
2.dictionary
3.scalar
4.ndarrays (Import NumPy while working with ndarray)
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
Series Example of ndarray:-
import pandas as pd
import numpy as np
np_name=np.array([‘abc’,’xyz’,’lmn’,’pqr’])
s_name=pd.Series(np_name)
print(s_name)
Output-
1 Abc
2 xyz
3 lmn
4 pqr
DataFrame example of ndarray-
import pandas as pd
import numpy as np
np_name=np.array([‘abc’,’xyz’,’lmn’,’pqr’])
df_name=pd.Dataframe(np_name)
print(df_name)
Output-
0 abc
1 xyz
2 lmn
3 pqr
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
Dataframe Example -
import pandas as pd
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
print(df)
Output-
col1 col2
0 1 3
1 2 4
Series Example-
import pandas as pd
data = ['g','e','e','k','s']
ser = pd.Series(data)
print(ser)
Output-
0 g
1 e
2 e
3 k
4 s
dtype: object
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
13.2 Indexing
A pandas series is a simple array and can be indexed similarly. Each row
and column in a pandas dataframe is a seperate pandas series hence they
can be indexed like an array too.
Pandas Series Indexing-
import pandas as pd
a = [4,5,6]
s = pd.Series(a)
print(s[1])
Output-
5
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
Example-
import pandas as pd
data = {'Name':['Tommy', 'nicky', 'krishna', 'jacky'], 'Age':
[23, 21, 18, 28], 'Qualification':['Msc', 'MA', 'MCA', 'Phd']}
df=pd.DataFrame(data, index= ['a', 'b', 'c', 'd'])
print(df['Name'])
Output-
a Tommy
b nicky
c krishna
d jacky
Name: Name, dtype: object
Example-
import pandas as pd
data={'Name':['Tommy','nicky', 'krishna', 'jacky'], 'Age':[23,
21, 18, 28],'Qualification':['Msc', 'MA', 'MCA', 'Phd']}
df=pd.DataFrame(data, index= ['a', 'b', 'c', 'd'])
print(df.iloc[2])
Out put -
Name krishna
Age 18
Qualification MCA
Name: c, dtype: object
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
Example-
import pandas as pd
data={'Name':['Tommy','nicky','krishna',
'jacky'],'Age':[23, 21, 18, 28],'Qualification':
['Msc', 'MA', 'MCA', 'Phd']}
df=pd.DataFrame(data,index=['a','b','c','d'])
print(df.loc['d'])
Output-
Name jacky
Age 28
Qualification Phd
Name: d, dtype: object
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 14
Data Visualization
Line graph
plt.plot()
plt.title() - show the title
Bar graph
plt.bar() - vertical bar graph
plt.barh() - Horizontal bar graph
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
Histogram
plt.hist()
Scatter Plot
plt.scatter()
Pie Chart
plt.pie()
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
14.2 Seaborn:
Seaborn library in python is used for data visualization. It is a high level
interface for drawing/plotting graphs.
Installation:
pip install seaborn
Import:
import seaborn as sns
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
14.3 Plotting:
A) Statistical Relationship (Numerical vs Numerical):
Understanding the relationship between the numerical variables and how, in
turn, these relationships depend on other variables is called Statistical
Analysis.
Function used - sns.replot()
By default it is scatter plot
Example-
sns.replot(x=’col1’,y=’col2’,data=dataframe,hue=’‘
,size=’‘,row=’‘,col=’‘)
Hue is for color, size is for number of size.
C) Distribution of data:
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 15
API
15.1 Application Program Interface
An application program interface (API) is a set of routines, protocols, and
tools for building software applications. Basically, an API specifies how we
interact with other computers over the internet. A good API makes it easier
to develop a program by providing all the building blocks. A programmer
then puts the blocks together.
Popular API Examples
1. Google Maps API
2. YouTube APIs
3. Flickr API
4. Twitter APIs
5. Amazon Product Advertising API
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
15.2 How To Interact With API
Most modern API’s are HTTP based and can be accessed using a GET or
PUT request to the base url of the API website. Generally these APIs
require a secret token for user authentication and input data with correct
variable name and value. In python this data can be serialised using python
dictionaries.
These requests are sent in python using the requests library.
Installing requests-
!pip install requests
Importing the library-
import requests
Sending request-
response = requests.<GET|POST>
(url_name,data_dictionary)
Extracting Data-
data = response.text
jsonData = response.json()
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 16
Zerodha API
16.1 Getting Started With Kite Connect
Kite Connect is Zerodha’s API for web based trading. It is used to automate
trading strategies based on user’s requirements. Zerodha is one of the
pioneers in API trading in India. Kite connect is a general API which can be
manipulated using various languages like Python, Java, Ruby etc. But in
this course we will be working on python to implement our strategies using
Zerodha’s Kite Connect API.
To start working with Kite Connect we have to first create a developers
account on Zerodha’s platform - https://developers.kite.trade/signup
We also have a list of classes which are present in KiteConnect SDK, they
can be used as a reference while building any trading code. The link for
KiteConnect python SDK is https://kite.trade/docs/pykiteconnect/v3/
Although we don't need to go through the entire documentation right now
because that is what we will be covering in the further chapters but, to have
a full knowledge of what is possible through this API one can always refer
to it.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
16.2 Create A Trading Application
Kite connect offers a feature to have multiple sets of strategies being
implemented at the same time through the same account but in isolation
from each other. Hence to start building one of them we need to create a
Trading Application on Kite Connect.
Before you can start building the Trading Application you need to have a
developer account first. If you don't have one then refer the earlier modules
as to how to create one. After creating a developer account you need to log
in to it.
Once it is done and you are on the Kite Connect Dashboard, you will see a
“Create New App button on the top right part of your screen (Click it).
Then you will have an option to create a Connect account and a Publisher
(Free account). For trading you have to go with the paid Connect Account.
Next fill in your App Name, Zerodha Client ID, App Icon(optional) and a
Description.
Redirect URL is the website where once you authenticate, Zerodha will
send your request token. If you are a developer and know how to configure
it then that's good. But if you don't then you don't need to worry. Just put
https://127.0.0.1 in it.
Postback URL is simply a tracking mechanism to get information about the
requests you make to the Kite Server. So if you don't know how to
configure it then leave it empty for now.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
Once the App is created, you can click on it to edit it’s settings and to
retrieve your API key and API secret which is important for the next part.
Also you can enable the Historical API from there if it isn’t already enabled
to get Historical data from Kite Connect API.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
16.3 Installing KiteConnect Library
kiteconnect is the python wrapper of Kite Connect API. You can install by
running this code in you command line -
pip install --upgrade kiteconnect
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
16.4 Access Token Generation
Access token is used to authenticate requests made to the Kite Connect API.
Retrieving an access token is a multi step process. It requires several other
inputs to be retrieved, which include -
1. api_key
2. api_secret
3. user_id
4. password
5. pin
6. request_token
Api Key and Api Secret are retrieved from the edit section of the Zerodha
app after you have signed in, as we did in the previous modules. User
Id,password and PIN are the ones which you use for logging into your
developers account.
Request Token is generated using the first five elements and using it along
with the others we will then generate the Access Token. Although you can
keep using the request token for all your request authentications, the
problem with it is that it expires very quickly and then you have to
complete the entire tedious procedure of retrieving the new request token
for your requests to
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
the Kite Connect API. Hence to solve this problem, as soon as you get your
request token you must generate your access token using it which doesn't
expire for a long time.
Importing Libraries -
from kiteconnect import KiteConnect
from selenium import webdriver from
kiteconnect import KiteConnect
from selenium import webdriver
import time
import os
Selenium is the library which we will be using to automate our work like
authentication, key retrieval etc. The time library as the name suggests is
used for manipulating time processes using python.
Os library is used to manipulate the operating system using python.
def autologin():
token_path = "api_key.txt"
key_secret =
open(token_path,'r').read().split()
kite = KiteConnect(api_key=key_secret[0])
service =
webdriver.chrome.service.Service('./chromedriver')
service.start()
options = webdriver.ChromeOptions()
options.add_argument('--headless')
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
options = options.to_capabilities()
driver =
webdriver.Remote(service.service_url, options)
driver.get(kite.login_url())
driver.implicitly_wait(10)
username=driver.find_element_by_xpath('/html/
body/div[1]/div/div[2]
/div[1]/div/div/div[2]/form/div[1]/input')
password=driver.find_element_by_xpath('/html/
body/div[1]/div/div[2]
/div[1]/div/div/div[2]/form/div[2]/input')
username.send_keys(key_secret[2])
password.send_keys(key_secret[3])
driver.find_element_by_xpath('/html/body/div[
1]/div/div[2]/div[1]/d
iv/div/div[2]/form/div[4]/button').click()
pin=driver.find_element_by_xpath('/html/body/
div[1]/div/div[2]/div[
1]/div/div/div[2]/form/div[2]/div/input')
pin.send_keys(key_secret[4])
driver.find_element_by_xpath('/html/body/div[
1]/div/div[2]/div[1]/d
iv/div/div[2]/form/div[3]/button').click()
time.sleep(10)
request_token=driver.current_url.split('=')
[1].split('&action')[0]
with open('request_token.txt', 'w') as
the_file:
the_file.write(request_token)
driver.quit()
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
This code is used to automate the authentication process and to retrieve the
request token. We start by retrieving the key secret which you have saved
inside api_token.txt file in the same folder as this code. We then create a
KiteConnect object which we will use to interact with the kite connect API.
To start the authentication process we create a selenium webdriver object
for chrome, pass the location of the webdriver file, set it to be headless
(which means that the entire process will take place in the background) and
begin it’s service. Once the service is up and running, we request the login
url from the KiteConnect object, redirect to that url and the username and
password field on that page. Once this is done, selenium passes your
username and password to it, finds the submit button, clicks it and redirects
to the page asking for the pin. This process is then repeated for PIN. Once
the authentication is complete, your Request Token comes as a part of your
redirect url which is then retrieved from it and saved to a file name
'request_token.txt'.
Although this process takes place in the background, knowing these steps is
important so that in case one day Zerodha changes some aspects of the
login procedure then you can adjust your code accordingly. But for now you
can use this code to retrieve your Request Token.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
def instrumentLookup(symbol):
return
instrument_df[instrument_df.tradingsymbol==symb
ol].instrument_token.values[0]
instrumentLookup(‘RELIANCE’)
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
Output:
11577090
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
16.7 Streaming Tick Data
Kite Connect uses a KiteTicker object to connect to zerodha’s socket under
the hood. We need to initialize the KiteTicker objects using API_KEY and
ACCESS_TOKEN. After initialization we need to set various functions
with predefined number of inputs to the object to be executed at various
events, during and after socket connection. These functions include -
1.
on_ticks(ws, ticks) - It is executed when the live data is
fetched by the socket.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
try:
print(f'Server Error {code} : {reason}')
time.sleep(2)
except KeyboardInterrupt:
ws.stop()
# Assign the callbacks.
kws.on_ticks = on_ticks
kws.on_connect = on_connect
kws.on_close = on_close
# Infinite loop on the main thread.
# Nothing after this will run.
kws.connect()
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
16.8 Placing Order
Orders can be placed using the KiteConnect object using the place_order
function. The place_order function takes several inputs based on the order
you want to place and returns an order id, if the order has been placed. The
syntax of place_order is -
place_order( variety, exchange, tradingsymbol, transaction_type, quantity,
product, order_type, price=None, validity=None, disclosed_quantity=None,
trigger_price=None, squareoff=None, stoploss=None,
trailing_stoploss=None, tag=None)
Variety
VARIETY_AMO
VARIETY_BO
VARIETY_CO
VARIETY_REGULAR
Exchange
EXCHANGE_BFO
EXCHANGE_BSE
EXCHANGE_CDS
EXCHANGE_MCX
EXCHANGE_NFO
EXCHANGE_NSE
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
16.10 Order History
Order history of all orders can be retrieved using the orders function which
contains the status including order id, order status etc for all your orders of
the day.
kite.orders()
Order details of a specific order can be retrieved using the order_history
function which takes the order id of which you want the details for in this
function.
kite.order_history(‘order_id’)
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 17
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
17.2 Coding Technical Indicators
17.2.1 MACD
The Moving Average Convergence/Divergence oscillator (MACD) is one of
the simplest and most effective momentum indicators. The MACD turns
two trend-following indicators, moving averages into a momentum
oscillator by subtracting the longer moving average(26) from the shorter
one(12).
A signal line is also calculated, which is again a moving average (typically
9 periods) of the MACD line calculated as per the above step.
The MACD line cutting signal line from below signals a bullish period and
the former cutting the latter from above signals a bearish period. This is
called a crossover strategy.
In python:
#using talib module
from talib import MACD
macd,macdsignal,macdhist= MACD(df['close'],
fastperiod=12, slowperiod=26,signalperiod=9)
# another implementation
def MACD(DF,a,b,c):
"""function to calculate MACD
typical values a(fast
MA)=12;b(slow A)=26;c(si
gnal line MA window) =9
"""
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
df = DF.copy()
df["MA_Fast"]=df["close"].ewm(span=a,
min_periods=a).mean()
df["MA_Slow"]=df["close"].ewm(span=b,
min_periods=b).mean()
df["MACD"]=df["MA_Fast"]-df["MA_Slow"]
df["Signal"]=df["MACD"].ewm(span=c,min_peri
ods=c).mean()
df.dropna(inplace=True)
return df
df["BB_up"]=df["MA"]+2*
df['close'].rolling(n).std(ddof=0)
#ddof=0 is required since we want to take
the standard deviation of the population and not
sample
df["BB_dn"]=df["MA"]-2*df['close'].
rolling(n).std(ddof=0)
#ddof=0 is required since we want to take
the standard deviation of the population and not
sample
df["BB_width"] = df["BB_up"] - df["BB_dn"]
df.dropna(inplace=True)
return df
bollBnd(df,10)
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
In python:
#using talib module
from talib import ATR
real = ATR(df['high'], df['low'],
df['close'], timeperiod=14)
# another implementation
def atr(DF,n):
"""
function to calculate True Range and
Average True Range
"""
df = DF.copy()
df['H-L']=abs(df['high']-df['low'])
df['H-PC']=abs(df['high']-
df['close'].shift(1))
df['L-PC']=abs(df['low']-
df['close'].shift(1))
df['TR']=df[['H-L','H-PC','L-
PC']].max(axis=1,skipna=False)
df['ATR'] =
df['TR'].ewm(com=n,min_periods=n).mean()
return df['ATR']
atr(df,10)
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
df2['L-PC']=abs(df2['low']-
df2['close'].shift(1))
df2['TR']=df2[['H-L','H-PC','L-
PC']].max(axis=1,skipna=False)
df2['DMplus']=np.where((df2['high']-
df2['high'].shift(1))>(df2['low'].shift(1)-
df2['low']), df2['high'] -
df2['high'].shift(1),0)
df2['D
Mplus']=np.where(df2['DMplus']
<0,0,df2['DMplus'])
df2['DMminus']=np.where((df2['low'].shif
t(1)-df2['low'])>(df2['high']-
df2['high'].shift(1)),df2['low'].shift(1
)-df2['low'],0)
df2['DMminus']=np.where(df2['DMminus']
<0,0,df2['DMminus'])
TRn = []
DMplusN = []
DMminusN = []
TR = df2['TR'].tolist()
DMplus = df2['DMplus'].tolist()
DMminus = df2['DMminus'].tolist()
for i in range(len(df2)):
if i < n:
TRn.append(np.NaN)
DMplusN.append(np.NaN)
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
DMminusN.append(np.NaN)
if i == n:
Rn.append(df2['TR'].rolling(n).sum().tol
ist()[n])
DMplusN.append(df2['DMplus'].rolling
(n).sum().tolist()[n])
DMminusN.append(df2['DMminus'].rolli
ng(n).sum().tolist()[n])
elif i > n:
TRn.append(TRn[i-1]- (TRn[i-
1]/n) + TR[i])
DMplusN.append(DMplusN[i-1] -
(DMplusN[i-1]/n) +DMplus[i])
DMminusN.append(DMminusN[i-1] -
(DMminusN[i-1]/n) + DMminus[i])
df2['TRn'] = np.array(TRn)
df2['DMplusN']=np.array(DMplusN)
df2['DMminusN']=np.array(DMminusN)
df2['DIplusN']=100*
(df2['DMplusN']/df2['TRn'])
df2['DIminusN']=100*
(df2['DMminusN']/df2['TRn'])
df2['DIdiff']=abs(d2['DIplusN']-
df2['DIminusN'])
df2['DIsum']=df2['DIplusN']+df2['DIminusN']
df2['DX']=100*
(df2['DIdiff']/df2['DIsum'])
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
ADX = []
DX = df2['DX'].tolist()
for j in range(len(df2)):
if j < 2*n-1:
ADX.append(np.NaN)
elif j == 2*n-1:
ADX.append(df2['DX'][j-
n+1:j+1].mean())
elif j > 2*n-1:
ADX.append(((n-1)*ADX[j-1]
+ DX[j])/n)
df2['ADX']=np.array(ADX)
return df2['ADX']
adx(df,10)
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
17.2.6 Supertrend
As the name suggests, ‘Supertrend’ is a trend-following indicator just like
moving averages and MACD (moving average convergence divergence). It
is plotted on prices and their placement indicates the current trend.
The indicator is easy to use and gives an accurate reading about an ongoing
trend. It is constructed with two parameters, namely period and multiplier.
The default values used while constructing a super-indicator are 10 for
average true range or trading period and three for its multiplier.
The code consists of 3 modules the first two being EMA and ATR which
are required to compute Supertrend values.
In python:
def EMA(df, base, target, period,
alpha=False):
con= pd.concat([df[:period]
[base].rolling(window=period).mean(),
df[period:][base]])
if (alpha == True):
df[target] = con.ewm(alpha=1 / period,
adjust=False).mean()
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
else:
df[target] = con.ewm(span=period,
adjust=False).mean()
df[target].fillna(0, inplace=True)
return df
def ATR(df, period, ohlc=['open', 'high',
'low', 'close']):
atr = 'ATR_' + str(period)
if not 'TR' in df.columns:
df['h-l'] = df[ohlc[1]] - df[ohlc[2]]
df['h-yc'] = abs(df[ohlc[1]] -
df[ohlc[3]].shift())
df['l-yc'] = abs(df[ohlc[2]] -
df[ohlc[3]].shift())
df['TR'] = df[['h-l', 'h-yc', 'l-
yc']].max(axis=1)
df.drop(['h-l', 'h-yc', 'l-yc'],
inplace=True, axis=1)
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
SuperTrend(df,7,3)
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
close_data = np.array(close_data)
high_data = np.array(high_data)
low_data = np.array(low_data)
volume = np.array(volume)
cmf=[sum((((close_data[idx+1-period:idx+1]-
low_data[idx+1-period:idx+1])-(high_data[idx+1-
period:idx+1]-
close_data[idx+1- period:idx+1]))/(hi
gh_data[idx+1-period:idx+1]-low_data[idx+1-
period:idx+1]))*volume[idx+1-
period:idx+1])/sum(volume[idx+1- peri
od:idx+1])for idx in range(period-1,
len(close_data))]
cmf=fill_for_noncomputable_vals(close_data,
cmf)
return cmf
def chiku_span(data):
"""
Chiku Span (Lagging Span)
Formula: Close shifted back 26 bars
"""
cs = data[25::]
return cs
def senkou_a(data):
"""
Senkou A (Leading Span A) Formula:
(TenkanSen + KijunSen) / 2 :: Shift Forward
26 bars
"""
sa = (tenkansen(data) + kijunsen(data)) / 2
# shift forward
shift_by = np.repeat(np.nan, 26)
sa = np.append(shift_by, sa)
return sa
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
def senkou_b(data, period=52):
"""
Senkou B (Leading Span B)
Formula: (H + L) / 2 :: default period=52
:: shifted forward 26 bars
"""
sb = conversion_base_line_helper(data,
period)
shift_by = np.repeat(np.nan, 26)
sb = np.append(shift_by, sb)
return sb
#another implementation
def doji(ohlc_df):
"""
returns dataframe with doji candle col
umn
"""
df = ohlc_df.copy()
avg_candle_size = abs(df["close"] -
df["open"]).median()
df["doji"] = abs(df["close"] - df["open"])
<= (0.05 * avg_candle_size)
return df
17.3.2 Hammer
A candle in which the lower wick is at least twice the size of the body.
Body can be red or green (bearish or bullish). Upper wick should be small
or non-existent.
This candle is viewed as a bullish reversal candlestick when occurring
during a downtrend.
In python:
#using talib module
from talib import CDLHAMMER
integer = CDLHAMMER(open, high, low, close)
def hammer(ohlc_df):
df = ohlc_df.copy()
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
df["hammer"]=(((df["high"]- df["low"]) >3*
(df["open"]-df["close"]))&((df["close"] -
df["low"])/(0.001+df["high"]-df["low"])>0.6) &
((df["open"]-df["low"])/(.001 + df["high"] -
df["low"])>0.6))&(abs(df["close"]- df["open"] ) >
0.1* (df["high"] - df["low"]))
return df
hammer(df)
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
df["sstar"] = (((df["high"] - df["low"])>3*
(df["open"] - df["close"])) & ((df["high"] -
df["close"])/(.001 + df["high"] - df["low"]) >
0.6) & ((df["high"] -
df["open"])/(.001 + df["high"] - df["low"]) >
0.6)) & (abs(df["close"] -
df["open"]) > 0.1* (df["high"] - df["low"]))
return df
shooting_star(df)
17.3.4 Marubozu
A candle which is long and sturdy with a very small or non existent wick.
Body can be red or green with green signifying bulls in complete control
whereas red signifies bears to have complete control.
This candle can signal both breakout or trend reversal depending on where
it occurs in the chart.
In python:
#using talib module
#using talib module
from talib import CDLMARUBOZU
integer = CDLMARUBOZU(df['open'],
df['high'], df['low'], df['close'])
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
#another implementation
def maru_bozu(ohlc_df):
"""returns dataframe with maru bozu candle
column"""
df = ohlc_df.copy()
avg_candle_size = abs(df["close"] -
df["open"]).median()
df["h-c"] = df["high"]-df["close"]
df["l-o"] = df["low"]-df["open"]
df["h-o"] = df["high"]-df["open"]
df["l-c"] = df["low"]-df["close"]
df["maru_bozu"] = np.where((df["close"] -
df["open"]>2*avg_candle_size)&(df[["h-c","l-
o"]].max(axis=1)
<0.005*avg_candle_size),"maru_bozu_green",np.where
((df["open"]- df[" close "] >
2*avg_candle_size) & (abs(df[["h-o","l-
c"]]).max(axis=1)<0.005* avg_candle_size
),"maru_bozu_red",False))
df.drop(["h-c","l-o","h-o","l-
c"],axis=1,inplace=True)
return df
maru_bozu(df)
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
CHAPTER 18
What we receive from any broker is tick data. Tick data basically
corresponds to any transaction made by buyer and seller.
Zerodha generally streams 1-2 ticks per second. These ticks are useful when
we are into HFT, but we need to re-sample it for our use.
Re-sampling is the process of converting granular data into a higher time
frame by storing them in a database and converting it into the timeframe we
require.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
18.1 Streaming Data To CSV
Live data for any stock is retrieved from zerodha using sockets. We can
stream live data using Zerodha’s KiteTicker object. While streaming the
data we can store all ticks for all tokens and store it in a dictionary. After
the market closes or when the current time exceeds the endtime of the code
then we can convert this dictionary into pandas DataFrame and save them
into separate csv files containing time stamps and their corresponding last
traded price at that moment.
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
self.timeStamp.append(datetime.datetime.now()
)
self.open.append(self.ltp[0])
self.high.append(max(self.ltp))
self.low.append(min(self.ltp))
self.close.append(self.ltp[-1])
self.ltp = []
# Function to set ltp value
def setLtp(self,ltp):
self.ltp.append(ltp)
# Function to get candles
dataframe
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
def getOhlc(self):
data = pd.DataFrame(data={
'timeStamp' : self.timeStamp,
'Open' : self.open,
'High' : self.high,
'Low' : self.low,
'Close' : self.close,
},columns=[
'timeStamp','Open','High','Low','Close'] )
data = data.set_index('timeStamp')
return data
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
if(datetime.datetime.now()>self.execution):
self.execution += self.delay
for token in self.pockets:
self.pockets[token].ohlc()
# Set the new candle to be
available
self.pockets[token].newData
= 1
# Function to get candles dataframe of token
def getOhlc(self,token):
return
self.getPocket(token).getOhlc()
# Function to print dataframe of token
pocket
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
request_token=furl(driver.current_url).args['re
quest_token'].strip()
break
except:
time.sleep(1)
kite = KiteConnect(api_key=api_key)
data =
kite.generate_session(request_token,
api_secret=api_secret)
with open('access_token.txt', 'w') as
file:
file.write(data["access_token"])
driver.quit()
autologin()
# retrieving access token from saved file
access_token_zerodha =
open("access_token.txt",'r').read()
# Tokens to subscribe
# (RELIANCE and ACC here)
TOKENS = [738561, 5633]
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
DATABASE.setVal(x['instrument_token'],x['last_pric
e'])
DATABASE.newCandle(x['instrument_token'])
#if current time is greater than
ENDTIME the stop the code
if(datetime.datetime.now()>ENDTIME):
print("Market is closed now...")
ws.stop()
#function to run when connection is
established to zerodha
def on_connect(ws, response):
# Callback on successful connect.
ws.subscribe(TOKENS)
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
# Reconnection will not happen after
executing `ws.stop()`
print(code)
print(reason)
ws.stop()
# Assign the callbacks.
kws.on_ticks = on_ticks
kws.on_connect = on_connect
kws.on_close = on_close
# Infinite loop on the main thread. Nothing
after this will run.
# You have to use the pre-defined callbacks
to manage subscriptions.
kws.connect()
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
18.3 Place Order Based On Strategy
This code is used to place orders based on a simple strategy. The strategy
here is that if we get 3 continuous increasing highs then we buy that stock
and if we get 3 continuous decreasing lows then we sell that stock.
# importing necessary modules
from selenium import webdriver
from selenium.webdriver.support.ui import
WebDriverWait
from selenium.common.exceptions import
TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import
expected_conditions as EC
import datetime
from kiteconnect import KiteTicker
from kiteconnect import KiteConnect
import pandas as pd
import time
from furl import furl
# class for single instrument data
class pocket:
def __init__(self,instrumentToken):
self.instrumentToken = instrumentToken
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
self.ltp = []
self.open = []
self.high = []
self.low = []
self.close = []
self.timeStamp = []
self.newData = 0
# Function to convert ltp data to ohlc
def ohlc(self):
if(self.ltp):
self.timeStamp.append(datetime.datetime.now())
self.open.append(self.ltp[0])
self.high.append(max(self.ltp))
self.low.append(min(self.ltp))
self.close.append(self.ltp[-1])
self.ltp = []
# Function to set ltp value
def setLtp(self,ltp):
self.ltp.append(ltp)
# Function to get candles dataframe
def getOhlc(self):
data = pd.DataFrame(
data={
'timeStamp' : self.timeStamp,
'Open' : self.open,
'High' : self.high,
'Low' : self.low,
'Close' : self.close,
},
columns=
['timeStamp','Open','High','Low','Close']
)
data = data.set_index('timeStamp')
return data
# class to store all pocket data
class database:
def __init__(self,tokens,startTime,delay):
self.pockets = {}
self.startTime = startTime
self.delay = delay
self.execution = startTime + delay
for token in tokens:
self.pockets[token] = pocket(token)
# Function to get pocket object by
token number
def getPocket(self,token):
return self.pockets[token]
# Setting ltp value based on token
def setVal(self,token,ltp):
self.getPocket(token).setLtp(ltp)
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
def checkCandle(self):
if(datetime.datetime.now()>self.executio
n):
self.execution += self.delay
for token in self.pockets:
self.pockets[token].ohlc()
# Set the new candle to be
available
self.pockets[token].newData = 1
# Function to get candles dataframe of
token
def getOhlc(self,token):
return
self.getPocket(token).getOhlc()
# Function to print dataframe of token
pocket
# if new candle is formed
def newCandle(self,token):
if(self.getPocket(token).newData):
self.getPocket(token).newData = 0
print('\n',token)
print(self.getOhlc(token))
# zerodha credentials
api_key = "your api_key"
api_secret = "your api_secret"
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
file.write(data["access_token"])
driver.quit()
autologin()
# retrieving access token from saved file
access_token_zerodha =
open("access_token.txt",'r').read()
# Tokens to subscribe
# (RELIANCE and ACC here)
TOKENS = [738561, 5633]
# #creating kite connect object
kite = KiteConnect(api_key=api_key)
# # setting access token ti kite connect
object
kite.set_access_token(access_token_zerodha)
# time at which code starts
STARTTIME = datetime.datetime.now()
#time at which code ends
ENDTIME =
datetime.datetime.now().replace(hour=15,minute=30,
second=0)
#duration of a candle
DELAY =
datetime.timedelta(hours=0,minutes=1,seconds=0)
# Initiating Database
DATABASE = database(TOKENS,STARTTIME,DELAY)
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
DATABASE.setVal(x['instrument_token'],x['last_pr
ice'])
DATABASE.newCandle(x['instrument_token'])
# Strategy to buy after 3 continuous
increasing
# highs and sell after 3 continuous
decreasing lows
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
if
len(DATABASE.getOhlc(x['instrument_token']))>3:
tempDb =
DATABASE.getOhlc(x['instrument_token'])
if(tempDb.iloc[-1]
['High']>tempDb.iloc[-2]['High'] and
tempDb.iloc[-2]['High']>tempDb.iloc[-3]
['High']):
order_id=
kite.place_order(tradingsymbol=x['instrument_token
'],
exchange=kite.EXCHANGE_NSE,
transaction_type=kite.TRANSACTION_TYPE_BUY,
quantity=1,
order_type=kite.ORDER_TYPE_MARKET,
product=kite.PRODUCT_NRML)
print(oid)
elif(tempDb.iloc[-1]['Low']
<tempDb.iloc[-2]['Low'] and
tempDb.iloc[-2]['Low']>tempDb.iloc[-3]['Low']):
order_id =
kite.place_order(tradingsymbol=x['instrument_token
'],exchange=kite.EXCHANGE_NSE,
transaction_type=kite.TRANSACTION_TYPE_
SELL,quantity=1,
order_type=kite.ORDER_TYPE_MARKET,produ
ct=kite.PRODUCT_NRML)
print(oid)
#if current time is greater than
ENDTIME the stop the code
if(datetime.datetime.now()>ENDTIME):
print("Market is closed now...")
ws.stop()
#function to run when connection is
established to zerodha
def on_connect(ws, response):
# Callback on successful connect.
ws.subscribe(TOKENS)
#funcion to run on connection close
def on_close(ws, code, reason):
# On connection close stop the main
loop
# Reconnection will not happen after
executing `ws.stop()`
print(code)
print(reason)
ws.stop()
#Assign the callbacks.
kws.on_ticks = on_ticks
kws.on_connect = on_connect
kws.on_close = on_close
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
__________________________________________________
Fox Trading Solutions Repository:www.https://github.com/FoxTradingSolutions/
Appendix
print: python function used to output data
function:A function is a block of code which only runs when it is called.
You can pass data known as a parameter as a function. A function can
return data as a result.
api: An application program interface (API) is a set of routines, protocols,
and tools for building software applications.
import: python keyword used to get external function into current code
object: an instance of a class
class: A Class is like an object constructor, or a "blueprint" for creating
objects.
type: python function used to find the data type of a variable
requests: python library to create get, post, delete etc. requests.
kiteconnect: Zerodha’s python api for retrieving data, placing orders etc.
input: python function to take input in python
pandas: python library to manage data
def : python keyword to define functions
stock : underlying instrument available for sale or purchase over exchange
zerodha : Indian financial service company, that offers retail and
institutional broking, currencies and commodities trading, mutual funds,
and bonds.
time : python library to handle time
ticks : dictionary object containing data for a single stock for a single
transaction live data
ltp : last traded price of a stock
pip : python library installation and management software
dictionary: python data type which stores data as key value pair
list : python data type to store data at continuous indices
dataframe: data type of pandas library in python to store data as a table of
indices and headers
kiteticker : kite connect object for live data
datetime : python library to handle date and time
numpy : python library to handle complex arithmetic operations as a group
(array, vector etc.)
series : pandas data type which represents a row or a column which
combine to become a data frame
selenium : python library for browser automation
webdriver : selenium object to handle various browsers like chrome,
Firefox etc
socket : A network socket is a software structure within a network node of
a computer network that serves as an endpoint for sending and receiving
data across the network.
trading : Trade in stock markets means the transfer (in exchange for money)
of a stock or security from a seller to a buyer.
library : a collection of predefined function, classes, and variable to be used
in other codes
exchange : A stock exchange is a facility where stockbrokers and traders
can buy and sell securities, such as shares of stock and bonds and other
financial instruments.
Jupyter-notebook: The Jupyter Notebook is an open-source web application
that allows you to create and share documents that contain live code,
equations, visualizations and narrative text.
stoploss : A stop-loss order is an order placed with a broker to buy or sell
once the stock reaches a certain price. A stop-loss is designed to limit an
investor's loss on security position.
float : python data type representing numbers containing decimal
append : function to insert elements in python list
set: python data type which stores only unique elements
streaming : Streaming data is data that is continuously generated by
different sources. Such data should be processed incrementally using
Stream Processing technique without having access to all of the data
keyword : Keywords are the reserved words in Python. We cannot use a
keyword as a variable name, function name or any other identifier.
break : python keyword to exit a loop
candle : A candlestick chart is a style of financial chart used to describe
price movements of a security, derivative, or currency.
tuple : A tuple is a collection of objects which are ordered and immutable.
Tuples are sequences, just like lists. The differences between tuples and lists
are, the tuples cannot be changed unlike lists and tuples use parentheses,
whereas lists use square brackets.
indicators: Technical Indicator is essentially a mathematical representation
based on data sets such as price (high, low, open, close, etc.) or volume of
security to forecast price trends.
split : python function to split a string based on input string
timestamp : a string representation of datetime object
lambda : python keyword to generate single line functions
matplotlib : python library to generate graphs
seaborn : python library to create graphs based on matplotlib
range : python function to create generators for numbers
ohlc : shart for for -> open high low and close
arrays : python numpy data type to represent mathematical arrays
try-except: python keyword to catch and handle errors
sleep : python function to delay execution of further lines
pprint : python library to print data types in readable form
comments : python statements which are not actually executed but are
written for human readability of code
len : python function to determine the length of a string
strip : python function to remove white spaces before and after a string
pyplot : matplotlib.pyplot is a collection of functions that make matplotlib
work like MATLAB. Each pyplot function makes some change to a figure:
e.g., creates a figure, creates a plotting area in a figure, plots some lines in a
plotting area, decorates the plot with labels, etc.
os : This module provides a portable way of using operating system
dependent functionality.
github : GitHub is a Git repository hosting service, but it adds many of its
own features. While Git is a command line tool, GitHub provides a Web-
based graphical interface. It also provides access control and several
collaboration features, such as a wikis and basic task management tools for
every project.
csv : comma separated values (csv) is a file type to store data like in excel
sql : SQL is a domain-specific language used in programming and
designed for managing data held in a relational database management
system, or for stream processing in a relational data stream management
system.
io : The io module provides Python’s main facilities for dealing with
various types of I/O.
str : python representation of string (set of characters)
immutable : unchanging over time or unable to be changed.
json : JavaScript Object Notation is an open standard file format, and data
interchange format, that uses human-readable text to store and transmit data
objects consisting of attribute–value pairs and array data types.
logging : python library used to log outputs
squareoff : Squaring off is a trading style used by investors/traders mostly
in day trading, in which a trader buys or sells a particular quantity of an
asset (mostly stocks) and later in the day reverses the transaction, in the
hope of earning a profit (price difference net of broker charges and tax
asynchronous: Asynchronous programming is a means of parallel
programming in which a unit of work runs separately from the main
application thread and notifies the calling thread of its completion, failure
or progress.
timedelta : python datetime object to define time duration
global : keyword to declare variables to be used in and out of every
variable