SlideShare a Scribd company logo
Python Learning Outcomes
04 May 2021
Python packages
• Import package to use: import package_name_here as shortened_name_here
Example: import numpy as np
• Packages required:
• numpy: perform numerical functions
• Pandas: reading, importing, creating DataFrames
• matplotlib.pyplot: data visualisation
• seaborn: data visualisation for stats
• Talib: technical analysis
• bt: backtest trading strategy
The basics
• List: first item has an index value of 0
• Slicing: includes the start & up to (but not include) the end, can slice with step (must be integer)
• Mylist [startAt : endBefore : step]
• Methods: .sort(), .append(), .extend(), .index(x), .min(), .max()
• Array: faster in reading, storing, calculating items
• Create array: np.array()
• Functions: .shape, .size, .mean, np.std(), np.arange(start, end, step), np.transpose()
• Can subset array using Boolean array
• Visualistion: use matplotlib.pyplot or seaborn packages
• Boxplot for quantiles and outliers: sns.boxplot(x= ,y= , data= )
• Line plot: plt.plot()
• Scatter plot: plt.scatter()
• Histogram: plt.hist(x = , bins = ); normed = 1 to use %
• Plt.show() to show graphs, plt.legend() to show legends
• Miscellaneous: color = , linestyle = ’ ‘, legend =‘ ‘, subplot = True, plt.xlabel(’ ‘), plt.ylabel(‘ ‘)
• Add a vertical line on chart: ax.axvline()
• Other plot types ( kind = ‘ ‘): bar, barh, hist, box, kde, density, area, pie, scatter, hexbin
Intermediate Python
• Representing time: use datetime package
• Convert datetime from string, from string to datetime
• Formatting time: consult materials. Example: %A, %B $d,
%Y
• datetime.now (), .datetime(year, month, day, hour,
minute)
• Attributes: .year, .month, .day, .hour,…
• Time delta: how much time between 2
timestamps
• Create relative datetime using timedelta()
• Dictionary: store and lookup values using keys
• Create dictionary: {‘key 1’:’value 1’, ’key 2’:’value 2’, ‘key
3’:’value 3’}
• Add new keys: dictionary [‘key’] = ‘value’
• Access values: dictionary [‘key’] or use get method
• Delete: del(dictionary[‘key’])
• Comparison operators: ==, !=, >, <, <=, =>
• Boolean operators: and,, or, not
• If statements:
• If <expression/control statement> :
Statement 1
Statement 2
Statement 3
• Else: excute code when the control statement is False
• Elif: only excute when initial statement is False and the
Elif statement is satisfied
• Loops:
• For <variable> in <sequence>:
Statement
• While <expression>:
Statement
• Skipping loop: if <expression> :
continue
• Stopping loop: if <expression> :
break
Intermediate Python
• DataFrames: using pandas package, similar to
spreadsheets or tables
• Can create DataFrames from dictionary or list of lists
• Reading data: pd.read_<file type> (’ file name or
path to file’)
• File type: excel, csv, json, html, pickle, sql
• Access column:
• Use [] brackets, dot
• Or list of name for multiple columns
• Access rows:
• Use slicing []
• List of booleans
• Access columns and rows in small dataset:
• iloc (by name)
• loc (by index)
• Methods: .count(), .min(), .max(), .first(), .last(), .sum(),
.prod(), .mean(), .median(), .std(), .var(), .quantiles()
• Note: method runs across rows by default, run across
columns if axis = 1
• Manipulating data:
• Remove column: .drop(columns=[ ], axis = 1, inplace = True)
• Remove row: .drop() remove rows by default
• Add multiple rows: .append() or .concat()
• Operations on DataFrames:
• apply directly to column
• .map: apply the defined operation to the selected columns
• .apply: across rows and columns
• Checking data:
• .info(): to view data structure
• .head(): display first 5 rows
• .tail(): display last 5 rows
• .describe(): summary stats
• Include = …
• Percentiles = [.1, .5, .9]
• Exclude = …
• Filtering data:
• Apply comparison expression on selected column
 result: Boolean values for each row in that column
• .loc [boolean_result] to filter values that satisfy the
comparison expression
Importing and managing financial data
• Import and inspecting data:
• CSV: pd.read_csv(‘file_name.csv’, na_values=‘n/a’,
parse_dates =[‘label of the column containing date info’])
• Excel: pd.read_excel( )
• Import an entire worksheet or just 1 or 2 sheets
• Combine data from multiple worksheets:
pd.concat()
• Combine vertically and combine data based on columns
• Note: a reference column is needed
• Google Finance:
• 1st step is importing datetime functionality  define
start and end date using date ()
• Data source: ‘google’
• E.g. stock_date = DataReader(ticker, data_source, start, end)
• Fed Researve:
• Series code: available on the website
• E.g. data = DataReader (series_code, data_source, start)
• Dealing with missing values:
• Drop rows with missing values: .dropa (inplace = True)
• Replace missng value with mean: .filla
• Useful methods:
• .sort_values (‘column’, ascending = False)
• .set_index: assign a different data type/values to the index
• .idxmax(): find index of max value
• .unique(): unique values as numpy array
• .div(): divide the whole column
• . nlargest(n = ): find n largest values
• .index.to.list(): convert index to list
• .panel.to_frame(): convert panel to frame
• Why? 2D multiIndex is easier to work with than panel
• .unstack(): unstack data, move from a long format to wide
format
• Methods for categorical data
• .nunique(): identify unique values or categories
• .value_count(): how many times each value occurs
• .groupby(): group data
• .agg(): pass a list with names of stats metric
Financial Trading
• Packages needed: ta-lib and bt
• Plot interactive candle sticks:
• Use plotly.graph_objects package
• go.Candlestick(x=, open=, high= , low= ,close=)
• Resample data: hourly to daily, daily to weekly
• Important calculations:
• Daily return: .pct_change()*100
(calculate % change from preceding row by default)
• SMA: .rolling(window = n).mean()
talib.SMA(data, time period)
• EMA: talib.EMA(data, time period)
• ADX: talib.EDX(high, low, close, timeperiod)
• RSI: talib.RSI(data, time period)
• Bollinger Band: talib.BBANDS(data, nbdevup = , nddevdn
= , time period)
Construct trading signal:
1. Get historical price: bt.get(‘ticker’,start=,end=)
2. Calculate indicators
3. Create signal DataFrame
signal=indicator_long.copy()
signal=[indicator_long.isnull()]=0
Define strategy:
Signal[condition 1] = 1 (long signal)
Signal[condition 2] = -1 (short signal)
Plot signal, prices and indicators: create a combined dataframe
using bt.merge
4. Define signal-based strategy
Bt_strategy = bt.Strategy(‘strategy_name’,
[bt.algos.SelectWhere( condition),
bt.algos.WeighEqually(),
bt.algos.Rebalance()])
Or
Bt_strategy=bt.Strategy(‘strategy_name’,
[bt.algos.WeighTarget(signal),
bt.algos.Rebalance()])
Financial Trading
Backtest
Bt_backtest = bt.Backtest (bt_strategy, price_data)
Bt_result = bt.run(bt_backtest)
Plot the backtest PnL:
bt_result,plot(title= )
Strategy optimization: try a range of input
parameter values
Define function (to save time, don’t have to repeat code)
Def signal_strategy (ticker,period,name,start =,end = )
<get historical values, calculate indicators, define signal, define
signal-based strategy>
Return bt.Backtest(bt_strattegy, price_data)
Can call this function several times, run backtest to find the
optimal input
Benchmarking: can compared active trading
strategy with buy and hold strategy
Def buy_and_hold (ticker,name,start=,end=)
<get historical data>
bt_strategy = bt.Strategy(name,
[bt.algos.RunOnce(),
bt.algos.SelectAll(),
bt.algos.WeighEqually(),
bt.algos.Rebalance()])
return bt.Backtest (bt_strategy, price_data)
 Run backtest on strategies and benchmark and compare
Strategy return analysis:
• Backtest stats: resInfo = bt_result.stats
• View all stats index: print(resInfo.index)
• Stats: rate of returns, cagr, max drawdown, calmar
ratio, share ratio, sortino ratio (yearly, monthly, daily
data)
E.g. print(‘Compound annual growth rate: %.4f’% resInfo.loc[‘cagr’])
• Compare multiple strategy returns:
lookback_results = bt_result.display_lookback_returns()
print(lookback_result)
TO DO
• Convert Unix timestamp to GMT+7 (stack overflow)
• Calculate MA (course on DataCamp)
• Find sources to import crypto data
• Find sources to import liquidation data

More Related Content

What's hot

Arrays in python
Arrays in pythonArrays in python
Arrays in python
Lifna C.S
 
Collections Framework Begineers guide 2
Collections Framework Begineers guide 2Collections Framework Begineers guide 2
Collections Framework Begineers guide 2
Kenji HASUNUMA
 
9 python data structure-2
9 python data structure-29 python data structure-2
9 python data structure-2
Prof. Dr. K. Adisesha
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-strings
Princess Sam
 
C arrays
C arraysC arrays
How To Use Higher Order Functions in Scala
How To Use Higher Order Functions in ScalaHow To Use Higher Order Functions in Scala
How To Use Higher Order Functions in Scala
BoldRadius Solutions
 
Arrays
ArraysArrays
Array lecture
Array lectureArray lecture
Array lecture
Joan Saño
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
OXUS 20
 
Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional array
imtiazalijoono
 
Python programming : Arrays
Python programming : ArraysPython programming : Arrays
Python programming : Arrays
Emertxe Information Technologies Pvt Ltd
 
Java Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream APIJava Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream API
Svetlin Nakov
 
Collections
CollectionsCollections
Collections
Rajkattamuri
 
Python array
Python arrayPython array
Python array
Arnab Chakraborty
 
Arrays in java language
Arrays in java languageArrays in java language
Arrays in java language
Hareem Naz
 
The Ring programming language version 1.5.2 book - Part 21 of 181
The Ring programming language version 1.5.2 book - Part 21 of 181The Ring programming language version 1.5.2 book - Part 21 of 181
The Ring programming language version 1.5.2 book - Part 21 of 181
Mahmoud Samir Fayed
 
Java arrays
Java arraysJava arrays
Java arrays
BHUVIJAYAVELU
 
Practical cats
Practical catsPractical cats
Practical cats
Raymond Tay
 
One dimensional 2
One dimensional 2One dimensional 2
One dimensional 2
Rajendran
 
Templates
TemplatesTemplates
Templates
Nilesh Dalvi
 

What's hot (20)

Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
Collections Framework Begineers guide 2
Collections Framework Begineers guide 2Collections Framework Begineers guide 2
Collections Framework Begineers guide 2
 
9 python data structure-2
9 python data structure-29 python data structure-2
9 python data structure-2
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-strings
 
C arrays
C arraysC arrays
C arrays
 
How To Use Higher Order Functions in Scala
How To Use Higher Order Functions in ScalaHow To Use Higher Order Functions in Scala
How To Use Higher Order Functions in Scala
 
Arrays
ArraysArrays
Arrays
 
Array lecture
Array lectureArray lecture
Array lecture
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
 
Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional array
 
Python programming : Arrays
Python programming : ArraysPython programming : Arrays
Python programming : Arrays
 
Java Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream APIJava Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream API
 
Collections
CollectionsCollections
Collections
 
Python array
Python arrayPython array
Python array
 
Arrays in java language
Arrays in java languageArrays in java language
Arrays in java language
 
The Ring programming language version 1.5.2 book - Part 21 of 181
The Ring programming language version 1.5.2 book - Part 21 of 181The Ring programming language version 1.5.2 book - Part 21 of 181
The Ring programming language version 1.5.2 book - Part 21 of 181
 
Java arrays
Java arraysJava arrays
Java arrays
 
Practical cats
Practical catsPractical cats
Practical cats
 
One dimensional 2
One dimensional 2One dimensional 2
One dimensional 2
 
Templates
TemplatesTemplates
Templates
 

Similar to Python presentation

Pa1 session 5
Pa1 session 5Pa1 session 5
Pa1 session 5
aiclub_slides
 
Python-for-Data-Analysis.pdf
Python-for-Data-Analysis.pdfPython-for-Data-Analysis.pdf
Python-for-Data-Analysis.pdf
ssuser598883
 
Python for data analysis
Python for data analysisPython for data analysis
Python for data analysis
Savitribai Phule Pune University
 
Meetup Junio Data Analysis with python 2018
Meetup Junio Data Analysis with python 2018Meetup Junio Data Analysis with python 2018
Meetup Junio Data Analysis with python 2018
DataLab Community
 
Python-for-Data-Analysis.pptx
Python-for-Data-Analysis.pptxPython-for-Data-Analysis.pptx
Python-for-Data-Analysis.pptx
Sandeep Singh
 
Python for Data Analysis.pdf
Python for Data Analysis.pdfPython for Data Analysis.pdf
Python for Data Analysis.pdf
JulioRecaldeLara1
 
Python-for-Data-Analysis.pptx
Python-for-Data-Analysis.pptxPython-for-Data-Analysis.pptx
Python-for-Data-Analysis.pptx
tangadhurai
 
Python-for-Data-Analysis.pptx
Python-for-Data-Analysis.pptxPython-for-Data-Analysis.pptx
Python-for-Data-Analysis.pptx
ParveenShaik21
 
Lecture 9.pptx
Lecture 9.pptxLecture 9.pptx
Lecture 9.pptx
MathewJohnSinoCruz
 
Unit 3_Numpy_Vsp.pptx
Unit 3_Numpy_Vsp.pptxUnit 3_Numpy_Vsp.pptx
Unit 3_Numpy_Vsp.pptx
prakashvs7
 
Aggregate.pptx
Aggregate.pptxAggregate.pptx
Aggregate.pptx
Ramakrishna Reddy Bijjam
 
pandas directories on the python language.pptx
pandas directories on the python language.pptxpandas directories on the python language.pptx
pandas directories on the python language.pptx
SumitMajukar
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
Jim Roepcke
 
More on Pandas.pptx
More on Pandas.pptxMore on Pandas.pptx
More on Pandas.pptx
VirajPathania1
 
PPT on Data Science Using Python
PPT on Data Science Using PythonPPT on Data Science Using Python
PPT on Data Science Using Python
NishantKumar1179
 
What's new in pandas and the SciPy stack for financial users
What's new in pandas and the SciPy stack for financial usersWhat's new in pandas and the SciPy stack for financial users
What's new in pandas and the SciPy stack for financial users
Wes McKinney
 
Pa2 session 1
Pa2 session 1Pa2 session 1
Pa2 session 1
aiclub_slides
 
Julie Michelman - Pandas, Pipelines, and Custom Transformers
Julie Michelman - Pandas, Pipelines, and Custom TransformersJulie Michelman - Pandas, Pipelines, and Custom Transformers
Julie Michelman - Pandas, Pipelines, and Custom Transformers
PyData
 
Practical Predictive Modeling in Python
Practical Predictive Modeling in PythonPractical Predictive Modeling in Python
Practical Predictive Modeling in Python
Robert Dempsey
 
Lecture 01 variables scripts and operations
Lecture 01   variables scripts and operationsLecture 01   variables scripts and operations
Lecture 01 variables scripts and operations
Smee Kaem Chann
 

Similar to Python presentation (20)

Pa1 session 5
Pa1 session 5Pa1 session 5
Pa1 session 5
 
Python-for-Data-Analysis.pdf
Python-for-Data-Analysis.pdfPython-for-Data-Analysis.pdf
Python-for-Data-Analysis.pdf
 
Python for data analysis
Python for data analysisPython for data analysis
Python for data analysis
 
Meetup Junio Data Analysis with python 2018
Meetup Junio Data Analysis with python 2018Meetup Junio Data Analysis with python 2018
Meetup Junio Data Analysis with python 2018
 
Python-for-Data-Analysis.pptx
Python-for-Data-Analysis.pptxPython-for-Data-Analysis.pptx
Python-for-Data-Analysis.pptx
 
Python for Data Analysis.pdf
Python for Data Analysis.pdfPython for Data Analysis.pdf
Python for Data Analysis.pdf
 
Python-for-Data-Analysis.pptx
Python-for-Data-Analysis.pptxPython-for-Data-Analysis.pptx
Python-for-Data-Analysis.pptx
 
Python-for-Data-Analysis.pptx
Python-for-Data-Analysis.pptxPython-for-Data-Analysis.pptx
Python-for-Data-Analysis.pptx
 
Lecture 9.pptx
Lecture 9.pptxLecture 9.pptx
Lecture 9.pptx
 
Unit 3_Numpy_Vsp.pptx
Unit 3_Numpy_Vsp.pptxUnit 3_Numpy_Vsp.pptx
Unit 3_Numpy_Vsp.pptx
 
Aggregate.pptx
Aggregate.pptxAggregate.pptx
Aggregate.pptx
 
pandas directories on the python language.pptx
pandas directories on the python language.pptxpandas directories on the python language.pptx
pandas directories on the python language.pptx
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
More on Pandas.pptx
More on Pandas.pptxMore on Pandas.pptx
More on Pandas.pptx
 
PPT on Data Science Using Python
PPT on Data Science Using PythonPPT on Data Science Using Python
PPT on Data Science Using Python
 
What's new in pandas and the SciPy stack for financial users
What's new in pandas and the SciPy stack for financial usersWhat's new in pandas and the SciPy stack for financial users
What's new in pandas and the SciPy stack for financial users
 
Pa2 session 1
Pa2 session 1Pa2 session 1
Pa2 session 1
 
Julie Michelman - Pandas, Pipelines, and Custom Transformers
Julie Michelman - Pandas, Pipelines, and Custom TransformersJulie Michelman - Pandas, Pipelines, and Custom Transformers
Julie Michelman - Pandas, Pipelines, and Custom Transformers
 
Practical Predictive Modeling in Python
Practical Predictive Modeling in PythonPractical Predictive Modeling in Python
Practical Predictive Modeling in Python
 
Lecture 01 variables scripts and operations
Lecture 01   variables scripts and operationsLecture 01   variables scripts and operations
Lecture 01 variables scripts and operations
 

Recently uploaded

Best practices for project execution and delivery
Best practices for project execution and deliveryBest practices for project execution and delivery
Best practices for project execution and delivery
CLIVE MINCHIN
 
Structural Design Process: Step-by-Step Guide for Buildings
Structural Design Process: Step-by-Step Guide for BuildingsStructural Design Process: Step-by-Step Guide for Buildings
Structural Design Process: Step-by-Step Guide for Buildings
Chandresh Chudasama
 
The 10 Most Influential Leaders Guiding Corporate Evolution, 2024.pdf
The 10 Most Influential Leaders Guiding Corporate Evolution, 2024.pdfThe 10 Most Influential Leaders Guiding Corporate Evolution, 2024.pdf
The 10 Most Influential Leaders Guiding Corporate Evolution, 2024.pdf
thesiliconleaders
 
Business storytelling: key ingredients to a story
Business storytelling: key ingredients to a storyBusiness storytelling: key ingredients to a story
Business storytelling: key ingredients to a story
Alexandra Fulford
 
The Evolution and Impact of OTT Platforms: A Deep Dive into the Future of Ent...
The Evolution and Impact of OTT Platforms: A Deep Dive into the Future of Ent...The Evolution and Impact of OTT Platforms: A Deep Dive into the Future of Ent...
The Evolution and Impact of OTT Platforms: A Deep Dive into the Future of Ent...
ABHILASH DUTTA
 
Authentically Social Presented by Corey Perlman
Authentically Social Presented by Corey PerlmanAuthentically Social Presented by Corey Perlman
Authentically Social Presented by Corey Perlman
Corey Perlman, Social Media Speaker and Consultant
 
Zodiac Signs and Food Preferences_ What Your Sign Says About Your Taste
Zodiac Signs and Food Preferences_ What Your Sign Says About Your TasteZodiac Signs and Food Preferences_ What Your Sign Says About Your Taste
Zodiac Signs and Food Preferences_ What Your Sign Says About Your Taste
my Pandit
 
Authentically Social by Corey Perlman - EO Puerto Rico
Authentically Social by Corey Perlman - EO Puerto RicoAuthentically Social by Corey Perlman - EO Puerto Rico
Authentically Social by Corey Perlman - EO Puerto Rico
Corey Perlman, Social Media Speaker and Consultant
 
Understanding User Needs and Satisfying Them
Understanding User Needs and Satisfying ThemUnderstanding User Needs and Satisfying Them
Understanding User Needs and Satisfying Them
Aggregage
 
buy old yahoo accounts buy yahoo accounts
buy old yahoo accounts buy yahoo accountsbuy old yahoo accounts buy yahoo accounts
buy old yahoo accounts buy yahoo accounts
Susan Laney
 
Training my puppy and implementation in this story
Training my puppy and implementation in this storyTraining my puppy and implementation in this story
Training my puppy and implementation in this story
WilliamRodrigues148
 
Unveiling the Dynamic Personalities, Key Dates, and Horoscope Insights: Gemin...
Unveiling the Dynamic Personalities, Key Dates, and Horoscope Insights: Gemin...Unveiling the Dynamic Personalities, Key Dates, and Horoscope Insights: Gemin...
Unveiling the Dynamic Personalities, Key Dates, and Horoscope Insights: Gemin...
my Pandit
 
Creative Web Design Company in Singapore
Creative Web Design Company in SingaporeCreative Web Design Company in Singapore
Creative Web Design Company in Singapore
techboxsqauremedia
 
Industrial Tech SW: Category Renewal and Creation
Industrial Tech SW:  Category Renewal and CreationIndustrial Tech SW:  Category Renewal and Creation
Industrial Tech SW: Category Renewal and Creation
Christian Dahlen
 
Chapter 7 Final business management sciences .ppt
Chapter 7 Final business management sciences .pptChapter 7 Final business management sciences .ppt
Chapter 7 Final business management sciences .ppt
ssuser567e2d
 
Best Forex Brokers Comparison in INDIA 2024
Best Forex Brokers Comparison in INDIA 2024Best Forex Brokers Comparison in INDIA 2024
Best Forex Brokers Comparison in INDIA 2024
Top Forex Brokers Review
 
LA HUG - Video Testimonials with Chynna Morgan - June 2024
LA HUG - Video Testimonials with Chynna Morgan - June 2024LA HUG - Video Testimonials with Chynna Morgan - June 2024
LA HUG - Video Testimonials with Chynna Morgan - June 2024
Lital Barkan
 
2024-6-01-IMPACTSilver-Corp-Presentation.pdf
2024-6-01-IMPACTSilver-Corp-Presentation.pdf2024-6-01-IMPACTSilver-Corp-Presentation.pdf
2024-6-01-IMPACTSilver-Corp-Presentation.pdf
hartfordclub1
 
Mastering B2B Payments Webinar from BlueSnap
Mastering B2B Payments Webinar from BlueSnapMastering B2B Payments Webinar from BlueSnap
Mastering B2B Payments Webinar from BlueSnap
Norma Mushkat Gaffin
 
ikea_woodgreen_petscharity_dog-alogue_digital.pdf
ikea_woodgreen_petscharity_dog-alogue_digital.pdfikea_woodgreen_petscharity_dog-alogue_digital.pdf
ikea_woodgreen_petscharity_dog-alogue_digital.pdf
agatadrynko
 

Recently uploaded (20)

Best practices for project execution and delivery
Best practices for project execution and deliveryBest practices for project execution and delivery
Best practices for project execution and delivery
 
Structural Design Process: Step-by-Step Guide for Buildings
Structural Design Process: Step-by-Step Guide for BuildingsStructural Design Process: Step-by-Step Guide for Buildings
Structural Design Process: Step-by-Step Guide for Buildings
 
The 10 Most Influential Leaders Guiding Corporate Evolution, 2024.pdf
The 10 Most Influential Leaders Guiding Corporate Evolution, 2024.pdfThe 10 Most Influential Leaders Guiding Corporate Evolution, 2024.pdf
The 10 Most Influential Leaders Guiding Corporate Evolution, 2024.pdf
 
Business storytelling: key ingredients to a story
Business storytelling: key ingredients to a storyBusiness storytelling: key ingredients to a story
Business storytelling: key ingredients to a story
 
The Evolution and Impact of OTT Platforms: A Deep Dive into the Future of Ent...
The Evolution and Impact of OTT Platforms: A Deep Dive into the Future of Ent...The Evolution and Impact of OTT Platforms: A Deep Dive into the Future of Ent...
The Evolution and Impact of OTT Platforms: A Deep Dive into the Future of Ent...
 
Authentically Social Presented by Corey Perlman
Authentically Social Presented by Corey PerlmanAuthentically Social Presented by Corey Perlman
Authentically Social Presented by Corey Perlman
 
Zodiac Signs and Food Preferences_ What Your Sign Says About Your Taste
Zodiac Signs and Food Preferences_ What Your Sign Says About Your TasteZodiac Signs and Food Preferences_ What Your Sign Says About Your Taste
Zodiac Signs and Food Preferences_ What Your Sign Says About Your Taste
 
Authentically Social by Corey Perlman - EO Puerto Rico
Authentically Social by Corey Perlman - EO Puerto RicoAuthentically Social by Corey Perlman - EO Puerto Rico
Authentically Social by Corey Perlman - EO Puerto Rico
 
Understanding User Needs and Satisfying Them
Understanding User Needs and Satisfying ThemUnderstanding User Needs and Satisfying Them
Understanding User Needs and Satisfying Them
 
buy old yahoo accounts buy yahoo accounts
buy old yahoo accounts buy yahoo accountsbuy old yahoo accounts buy yahoo accounts
buy old yahoo accounts buy yahoo accounts
 
Training my puppy and implementation in this story
Training my puppy and implementation in this storyTraining my puppy and implementation in this story
Training my puppy and implementation in this story
 
Unveiling the Dynamic Personalities, Key Dates, and Horoscope Insights: Gemin...
Unveiling the Dynamic Personalities, Key Dates, and Horoscope Insights: Gemin...Unveiling the Dynamic Personalities, Key Dates, and Horoscope Insights: Gemin...
Unveiling the Dynamic Personalities, Key Dates, and Horoscope Insights: Gemin...
 
Creative Web Design Company in Singapore
Creative Web Design Company in SingaporeCreative Web Design Company in Singapore
Creative Web Design Company in Singapore
 
Industrial Tech SW: Category Renewal and Creation
Industrial Tech SW:  Category Renewal and CreationIndustrial Tech SW:  Category Renewal and Creation
Industrial Tech SW: Category Renewal and Creation
 
Chapter 7 Final business management sciences .ppt
Chapter 7 Final business management sciences .pptChapter 7 Final business management sciences .ppt
Chapter 7 Final business management sciences .ppt
 
Best Forex Brokers Comparison in INDIA 2024
Best Forex Brokers Comparison in INDIA 2024Best Forex Brokers Comparison in INDIA 2024
Best Forex Brokers Comparison in INDIA 2024
 
LA HUG - Video Testimonials with Chynna Morgan - June 2024
LA HUG - Video Testimonials with Chynna Morgan - June 2024LA HUG - Video Testimonials with Chynna Morgan - June 2024
LA HUG - Video Testimonials with Chynna Morgan - June 2024
 
2024-6-01-IMPACTSilver-Corp-Presentation.pdf
2024-6-01-IMPACTSilver-Corp-Presentation.pdf2024-6-01-IMPACTSilver-Corp-Presentation.pdf
2024-6-01-IMPACTSilver-Corp-Presentation.pdf
 
Mastering B2B Payments Webinar from BlueSnap
Mastering B2B Payments Webinar from BlueSnapMastering B2B Payments Webinar from BlueSnap
Mastering B2B Payments Webinar from BlueSnap
 
ikea_woodgreen_petscharity_dog-alogue_digital.pdf
ikea_woodgreen_petscharity_dog-alogue_digital.pdfikea_woodgreen_petscharity_dog-alogue_digital.pdf
ikea_woodgreen_petscharity_dog-alogue_digital.pdf
 

Python presentation

  • 2. Python packages • Import package to use: import package_name_here as shortened_name_here Example: import numpy as np • Packages required: • numpy: perform numerical functions • Pandas: reading, importing, creating DataFrames • matplotlib.pyplot: data visualisation • seaborn: data visualisation for stats • Talib: technical analysis • bt: backtest trading strategy
  • 3. The basics • List: first item has an index value of 0 • Slicing: includes the start & up to (but not include) the end, can slice with step (must be integer) • Mylist [startAt : endBefore : step] • Methods: .sort(), .append(), .extend(), .index(x), .min(), .max() • Array: faster in reading, storing, calculating items • Create array: np.array() • Functions: .shape, .size, .mean, np.std(), np.arange(start, end, step), np.transpose() • Can subset array using Boolean array • Visualistion: use matplotlib.pyplot or seaborn packages • Boxplot for quantiles and outliers: sns.boxplot(x= ,y= , data= ) • Line plot: plt.plot() • Scatter plot: plt.scatter() • Histogram: plt.hist(x = , bins = ); normed = 1 to use % • Plt.show() to show graphs, plt.legend() to show legends • Miscellaneous: color = , linestyle = ’ ‘, legend =‘ ‘, subplot = True, plt.xlabel(’ ‘), plt.ylabel(‘ ‘) • Add a vertical line on chart: ax.axvline() • Other plot types ( kind = ‘ ‘): bar, barh, hist, box, kde, density, area, pie, scatter, hexbin
  • 4. Intermediate Python • Representing time: use datetime package • Convert datetime from string, from string to datetime • Formatting time: consult materials. Example: %A, %B $d, %Y • datetime.now (), .datetime(year, month, day, hour, minute) • Attributes: .year, .month, .day, .hour,… • Time delta: how much time between 2 timestamps • Create relative datetime using timedelta() • Dictionary: store and lookup values using keys • Create dictionary: {‘key 1’:’value 1’, ’key 2’:’value 2’, ‘key 3’:’value 3’} • Add new keys: dictionary [‘key’] = ‘value’ • Access values: dictionary [‘key’] or use get method • Delete: del(dictionary[‘key’]) • Comparison operators: ==, !=, >, <, <=, => • Boolean operators: and,, or, not • If statements: • If <expression/control statement> : Statement 1 Statement 2 Statement 3 • Else: excute code when the control statement is False • Elif: only excute when initial statement is False and the Elif statement is satisfied • Loops: • For <variable> in <sequence>: Statement • While <expression>: Statement • Skipping loop: if <expression> : continue • Stopping loop: if <expression> : break
  • 5. Intermediate Python • DataFrames: using pandas package, similar to spreadsheets or tables • Can create DataFrames from dictionary or list of lists • Reading data: pd.read_<file type> (’ file name or path to file’) • File type: excel, csv, json, html, pickle, sql • Access column: • Use [] brackets, dot • Or list of name for multiple columns • Access rows: • Use slicing [] • List of booleans • Access columns and rows in small dataset: • iloc (by name) • loc (by index) • Methods: .count(), .min(), .max(), .first(), .last(), .sum(), .prod(), .mean(), .median(), .std(), .var(), .quantiles() • Note: method runs across rows by default, run across columns if axis = 1 • Manipulating data: • Remove column: .drop(columns=[ ], axis = 1, inplace = True) • Remove row: .drop() remove rows by default • Add multiple rows: .append() or .concat() • Operations on DataFrames: • apply directly to column • .map: apply the defined operation to the selected columns • .apply: across rows and columns • Checking data: • .info(): to view data structure • .head(): display first 5 rows • .tail(): display last 5 rows • .describe(): summary stats • Include = … • Percentiles = [.1, .5, .9] • Exclude = … • Filtering data: • Apply comparison expression on selected column  result: Boolean values for each row in that column • .loc [boolean_result] to filter values that satisfy the comparison expression
  • 6. Importing and managing financial data • Import and inspecting data: • CSV: pd.read_csv(‘file_name.csv’, na_values=‘n/a’, parse_dates =[‘label of the column containing date info’]) • Excel: pd.read_excel( ) • Import an entire worksheet or just 1 or 2 sheets • Combine data from multiple worksheets: pd.concat() • Combine vertically and combine data based on columns • Note: a reference column is needed • Google Finance: • 1st step is importing datetime functionality  define start and end date using date () • Data source: ‘google’ • E.g. stock_date = DataReader(ticker, data_source, start, end) • Fed Researve: • Series code: available on the website • E.g. data = DataReader (series_code, data_source, start) • Dealing with missing values: • Drop rows with missing values: .dropa (inplace = True) • Replace missng value with mean: .filla • Useful methods: • .sort_values (‘column’, ascending = False) • .set_index: assign a different data type/values to the index • .idxmax(): find index of max value • .unique(): unique values as numpy array • .div(): divide the whole column • . nlargest(n = ): find n largest values • .index.to.list(): convert index to list • .panel.to_frame(): convert panel to frame • Why? 2D multiIndex is easier to work with than panel • .unstack(): unstack data, move from a long format to wide format • Methods for categorical data • .nunique(): identify unique values or categories • .value_count(): how many times each value occurs • .groupby(): group data • .agg(): pass a list with names of stats metric
  • 7. Financial Trading • Packages needed: ta-lib and bt • Plot interactive candle sticks: • Use plotly.graph_objects package • go.Candlestick(x=, open=, high= , low= ,close=) • Resample data: hourly to daily, daily to weekly • Important calculations: • Daily return: .pct_change()*100 (calculate % change from preceding row by default) • SMA: .rolling(window = n).mean() talib.SMA(data, time period) • EMA: talib.EMA(data, time period) • ADX: talib.EDX(high, low, close, timeperiod) • RSI: talib.RSI(data, time period) • Bollinger Band: talib.BBANDS(data, nbdevup = , nddevdn = , time period) Construct trading signal: 1. Get historical price: bt.get(‘ticker’,start=,end=) 2. Calculate indicators 3. Create signal DataFrame signal=indicator_long.copy() signal=[indicator_long.isnull()]=0 Define strategy: Signal[condition 1] = 1 (long signal) Signal[condition 2] = -1 (short signal) Plot signal, prices and indicators: create a combined dataframe using bt.merge 4. Define signal-based strategy Bt_strategy = bt.Strategy(‘strategy_name’, [bt.algos.SelectWhere( condition), bt.algos.WeighEqually(), bt.algos.Rebalance()]) Or Bt_strategy=bt.Strategy(‘strategy_name’, [bt.algos.WeighTarget(signal), bt.algos.Rebalance()])
  • 8. Financial Trading Backtest Bt_backtest = bt.Backtest (bt_strategy, price_data) Bt_result = bt.run(bt_backtest) Plot the backtest PnL: bt_result,plot(title= ) Strategy optimization: try a range of input parameter values Define function (to save time, don’t have to repeat code) Def signal_strategy (ticker,period,name,start =,end = ) <get historical values, calculate indicators, define signal, define signal-based strategy> Return bt.Backtest(bt_strattegy, price_data) Can call this function several times, run backtest to find the optimal input Benchmarking: can compared active trading strategy with buy and hold strategy Def buy_and_hold (ticker,name,start=,end=) <get historical data> bt_strategy = bt.Strategy(name, [bt.algos.RunOnce(), bt.algos.SelectAll(), bt.algos.WeighEqually(), bt.algos.Rebalance()]) return bt.Backtest (bt_strategy, price_data)  Run backtest on strategies and benchmark and compare Strategy return analysis: • Backtest stats: resInfo = bt_result.stats • View all stats index: print(resInfo.index) • Stats: rate of returns, cagr, max drawdown, calmar ratio, share ratio, sortino ratio (yearly, monthly, daily data) E.g. print(‘Compound annual growth rate: %.4f’% resInfo.loc[‘cagr’]) • Compare multiple strategy returns: lookback_results = bt_result.display_lookback_returns() print(lookback_result)
  • 9. TO DO • Convert Unix timestamp to GMT+7 (stack overflow) • Calculate MA (course on DataCamp) • Find sources to import crypto data • Find sources to import liquidation data