100% found this document useful (6 votes)
2K views47 pages

Python For Trading

The document provides an overview of Python concepts and data structures for trading including functions, loops, variables, data types, lists, tuples, dictionaries and modules. It also discusses Python libraries for finance and algorithms for trading strategies.

Uploaded by

dzavkec
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (6 votes)
2K views47 pages

Python For Trading

The document provides an overview of Python concepts and data structures for trading including functions, loops, variables, data types, lists, tuples, dictionaries and modules. It also discusses Python libraries for finance and algorithms for trading strategies.

Uploaded by

dzavkec
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

PYTHON for TRADING

2
PYTHON for TRADING

Contents
Part – 1 PYTHON CONCEPTS .................................................................................................................. 5
................................................................................................................................. 6
................................................................................................................................ 7
........................................................................................................................................ 8
........................................................................................................................................ 9
......................................................................................................................... 9
............................................................................................................................ 10
......................................................................................................................... 10
................................................................................................................................... 11
................................................................................................................................ 11
....................................................... 13
.......................................................................................................................................... 14
......................................................................................................................................... 16
................................................................................................................................. 16
........................................................................................................ 18
.................................................................................................................................... 18
...................................................................................................................................... 21
Part -2 DATA STRUCTURE ..................................................................................................................... 22
............................................................................................................................... 23
................................................................................................................................ 23
......................................................................................................................................... 23
2.4 Dictionaries { } ............................................................................................................................. 25
...................................................................................................................................... 26
.............................................................................................................................................. 28
.................................................................................................................................. 29
.................................................................................................................................... 29
Part - 3................................................................................................................................................... 30
................................................................................................................................ 31
................................................................................................................................ 31
............................................................................................................... 31
..................................................................................................................................... 31
........................................................................................................................... 32
........................................................................................................... 34

3
PYTHON for TRADING

..................................................................................................................................... 35
..................................................................................................................... 35
......................................................................................................... 36
........................................................................................................................................ 39
............................................................................................................................... 39
........................................................................................................... 40
......................................................................................................................... 40
................................................................................................................................... 40
............................................................................................................................ 40
.......................................................................................................................... 41
.................................................................................................. 41
................................................................. 41
........................................................................................................................ 41
…..…………………..……………………………………………………………………... 44

4
PYTHON for TRADING

Part – 1 PYTHON CONCEPTS

5
PYTHON for TRADING

6
PYTHON for TRADING

7
PYTHON for TRADING

length = 2
breadth = 3
area = length*breadth
print(area)

Output
>>>
6

# defining a function
def ex_loop():
#The loop starts with an indentation
for i in [1, ‘Gold’, ‘Silver’]:
# The statement in the loop starts with an indentation as
well
print i

# calling the function


ex_loop()

Output
1
Gold
Silver

a = 3.25

b = 3.20

8
PYTHON for TRADING

#defining a function to calculate the bid-ask spread


def calc_spread(bid,ask): #function takes bid and ask prices as
input arguments
spd = ?ask - bid
return spd #function returns spd (bid-ask
spread)

#defining a function to calculate mid price


def calc_midPrice(?,?): bid,ask
mid_price = (bid+ask)/2
return ?mid_price

#defining a function to print values, takes no input arguments


? print_all():def
#name "s" refers to the function to calculate bid-ask spread
s = calc_spread(b,a)
p = ? calc_midPrice(b,a)
for i in [s,p]: #using for loop to print spread and mid-
price
print ? i

#calling the print function


print_all()

9
PYTHON for TRADING



10
PYTHON for TRADING



11
PYTHON for TRADING

x = 10
x = {1,2,3}
x = ‘Hello QuantInsti’

def func():
print(‘Buy Gold’)

x = func
x()

output
>>>
Buy Gold

12
PYTHON for TRADING

 o
o
o
o

o o

o o
o o

o o

o o
o o

13
PYTHON for TRADING

Input

i=1
def foo():

14
PYTHON for TRADING

i=5
print(i, 'in foo()')
print(i, 'global')
foo()

Output

1 global
5 in foo()



15
PYTHON for TRADING

<statement-1>

. . .

<statement-N>

16
PYTHON for TRADING

17
PYTHON for TRADING

18
PYTHON for TRADING

19
PYTHON for TRADING

20
PYTHON for TRADING

21
PYTHON for TRADING

Part -2 Data Structure

22
PYTHON for TRADING

MUTABLE IMMUTABLE
Lists Strings
Sets Tuples
Frozen Sets

Let us now look at each in detail:

List a mutable object, is like a one dimensional array. There are several methods associated
with, some of them are listed below:

append(): Items can be added to the list simply by using append()

23
PYTHON for TRADING

remove(): Items can be deleted from the list using remove()

for loop: Iterate through the list using “for” loop.

If: Searching for an item in a list is also very simple, you can check if an item is present in a
list by using the keyword “if” as shown.

list[:] Lists can be sliced using the below command

list[first index:last index:step]

Index(): searches for an element in the list and returns the “index”

24
PYTHON for TRADING

Insert(): inserts an element at the desired position/index in a list

Pop(): removes the last element of the list

Similarly you can try out functions like ‘sort’, ‘count’, ‘reverse’ etc. and see the results.

2.4 Dictionaries { }

25
PYTHON for TRADING

26
PYTHON for TRADING

Use len(), to find the “length” of a tuple

27
PYTHON for TRADING

28
PYTHON for TRADING

29
PYTHON for TRADING

Part - 3

30
PYTHON for TRADING

Data Analysis (handling & manipulation) Libraries

31
PYTHON for TRADING

s = pd.Series(data, index=index)







32
PYTHON for TRADING

Viewing data frames:

Transposing values:

33
PYTHON for TRADING

Sorting by value/index:

# drops rows with NA

34
PYTHON for TRADING

# fills NA with a particular value, ‘2’ in this case

Code

35
PYTHON for TRADING

Output

36
PYTHON for TRADING

37
PYTHON for TRADING

38
PYTHON for TRADING



39
PYTHON for TRADING

40
PYTHON for TRADING

41
PYTHON for TRADING

42
PYTHON for TRADING

43
PYTHON for TRADING

44
PYTHON for TRADING

45
PYTHON for TRADING

46
PYTHON for TRADING

47

Common questions

Powered by AI

Python namespaces determine which variable references will be accessible from a certain segment of code, governed by the LEGB hierarchy: Local, Enclosed, Global, and Built-in . Local namespaces pertain to variables within a function or block code. If a variable with the same name resides in an enclosing function (where a function is wrapped inside another function), it falls under the Enclosed namespace. The Global namespace applies to top-level script variables, which consist of module-wide variables and constants. Lastly, Built-in namespaces are reserved for Python and contain built-in functions and exceptions . For example, in function foo(), when printing a variable, Python follows this order unless specified otherwise. If the search for a name-object mapping fails in all scopes, a NameError is raised . This hierarchy ensures variable name conflicts are managed efficiently.

In Python, variables are treated as 'names' that are associated with objects, unlike many other languages where a variable name represents a 'box' containing actual data. For instance, when you assign a variable in Python (x = 20), the name 'x' is linked to the object 20 in memory, and both share the same address . This dynamic association allows for efficient memory management because Python reuses objects with the same value rather than creating duplicate ones . In contrast, other languages like C use boxes that need new storage space for reassignment even if the value is the same. Furthermore, assigning one name to another just binds the new name to the existing object (e.g., b = a makes 'b' a tag bound to the same object as 'a'). This behavior facilitates memory efficiency since each variable does not require a unique copy of the object's memory space.

Coding a Moving Average Crossover Strategy in Python is advantageous because it leverages Python's rich ecosystem of data manipulation libraries like Pandas to calculate and analyze moving averages efficiently . This strategy involves calculating short-term and long-term moving averages, where the crossover signals potential trade opportunities (e.g., buy signals when the short-term average crosses above the long-term one and sell signals when it crosses below). The use of Pandas simplifies operations with large datasets, offering functions for smooth data handling and computation . However, a potential pitfall in executing this strategy could be the lag inherent to moving averages as they are calculated on past data, possibly missing quick market shifts. Another challenge could involve managing transaction costs and slippage, which, if not carefully modeled, might negate any theoretical returns depicted by the strategy simulation itself .

Python's data structures, particularly DataFrame and Series, form the backbone of its capabilities in handling large and complex datasets, crucial for effective data analysis. A Series is a one-dimensional labeled array that can hold any data type. Its labeling capability with a collective index directly supports operations such as selection, filtering, and scalar operations with great efficiency . A DataFrame, on the other hand, offers a two-dimensional labeled data structure akin to a spreadsheet or SQL table, facilitating intricate data alignment and transformation across a variety of input data types, allowing for robust data manipulation processes like grouping and merging . These structures inherently support handling missing data seamlessly using methods like fillna() and dropna(), which ensure data integrity throughout the analysis process . Their integration features with libraries including NumPy and SciPy further enable comprehensive computational functionality, thus greatly enhancing Python's effectiveness in advanced data analytics tasks .

The LEGB rule is a Python variable lookup hierarchy that determines the sequence in which namespaces are searched for variable names. It stands for Local, Enclosed, Global, and Built-in. Local refers to variables within a function, Enclosed includes any enclosing functions in which the variable is nested, Global is the top-level space of the script, and Built-in consists of Python's special reserved names . This rule is essential in Python's variable naming system as it systematically narrows down where a variable can be found, blurring potential conflicts in naming by establishing a clear precedence order . As Python evaluates expressions, it follows this order, checking each namespace until it finds the variable. Should it not find it in any of these, a NameError is raised . This hierarchy provides an efficient method to resolve variable references, supporting Python’s dynamic typing system and memory management capabilities.

PyAlgoTrade holds significance in the context of algo-trading libraries due to its focus on providing an event-driven environment for backtesting along with features to support paper-trading and live trading . Its ability to evaluate trading strategies using historical data with minimal setup offers a quick entry into the automated trading domain. The library is known for its speed and flexibility over other Python alternatives as it supports integrations with TA-Lib for technical analysis and can access data from multiple sources like Yahoo Finance and Google Finance . PyAlgoTrade stands out for its documentation quality and community support, making it an attractive option for developers testing new trading strategies without the requirement of complex overheads . However, its lack of support for Pandas, a limitation for some users requiring extensive data manipulation capabilities, remains a notable drawback .

Inheritance in Python allows a new class, known as a derived or child class, to inherit attributes and methods from an existing class, known as the base or parent class, with little or no modification . This concept promotes code reuse as the derived class can utilize the functionalities of the base class directly, extending or overriding them as needed without rewriting code. This enables developers to build upon existing structures to create more complex functionalities efficiently while maintaining consistency with previous implementations .

In Python, class definitions play a crucial role in defining classes and their namespaces. When a class definition is executed, it creates a new, isolated namespace that serves as the local scope, meaning assignments to local variables within the class go into this new namespace . This design encapsulates the class's data and behaviors, ensuring that attributes and methods are accessible via the class object. Upon leaving the class definition, a class object is created, effectively wrapping the namespace's contents, which can then be referenced using the class name . This process supports attribute references and instantiation, allowing class attributes to be modified and reused across instances and the creation of Python objects through a constructor method (__init__) for specific initial states . This setup facilitates organization, reusability, and clear modularity in code.

NumPy is a pivotal Python library designed for scientific computing, offering a powerful N-dimensional array object, among other capabilities . Its core utility lies in providing support for matrices, linear algebra, and sophisticated (broadcasting) functions, making it an essential tool for mathematical operations and data analysis . Unlike lists, NumPy arrays consume less memory and provide faster computation speed due to data being stored in contiguous blocks of memory . This efficiency optimizes operations like element-wise and matrix computations, crucial for large-scale scientific data processing. Furthermore, NumPy’s integration features allow it to work seamlessly with other Python libraries such as SciPy and Pandas, effectively extending Python’s usability and performance in scientific and analytical computing . These enhancements make Python a competitive option in data-heavy domains traditionally dominated by other programming languages specialized in scientific computing.

Pandas is considered a powerful tool for data analysis in Python due to its ability to provide high-performance, easy-to-use data structures like the Series (1D), DataFrame (2D), and Panel (3D). These structures accommodate various data types and are comparable to data behavior in tables or spreadsheets. Particularly, DataFrame, which can handle diverse and complex datasets efficiently, allows for operations like grouping, merging, and pivoting to be executed quickly . Pandas also include optimized data access methods to facilitate fast data retrieval and manipulation . Additionally, its integration with NumPy further extends its usability for handling mathematical data operations, making it invaluable for data analysis tasks .

You might also like