Algorithmic Trading with Python and Quantopian p. 1

sentdex · Beginner ·🛠️ AI Tools & Apps ·9y ago

Key Takeaways

The video demonstrates the use of Quantopian, a backtesting platform, and Python to create and test algorithmic trading strategies, with a focus on strategy back-testing and the requirements to do it right.

Full Transcript

what is going on everybody and welcome to part 13 of our python for finance tutorial series as well as kind of the introduction to quantopian so the purpose of quantopian is uh manyfold so initially quantopian in my eyes was really just a back testing platform which at the time was still super valuable because first of all they provide you um stock pricing data down to the minute for any company but then also they were providing fun FAL data on companies again for free um and also the pricing data was for free and so you were able to actually leverage data and do back testing on first of all just data that was normal otherwise paid data also the back tests themselves were immensely useful because they visualized trading as it happened for you they tracked other statistics like uh Alpha and beta and sharp ratio and all these kinds of things also it shows your transactions over time really simply and anybody who ever tried to code something that just does that um knows how challenging that really is and how timec consuming I mean honestly to to just do the back testing is is like thousands and thousands of hours in my opinion so um so yeah so there was that now quantopian changed a lot over time and I would call quantopian now more of of a like a research platform that you just so happen to be able to also back test on so so it's kind of changed now the other thing you can do with quantopian so first of all some people have expressed concern that if you write a really good strategy on quantopian that quantopian will steal it uh so first of all they just wouldn't probably do that but also quantopian is actually interested in working with anybody who comes up with a good strategy so you can get capital allocations from quantopian the target is to pay you out 10% I don't know if that's negotiable at all but um 10% is a a pretty good starting point it's a very low barrier to entry anyways um and what they want from you is a beta between you know negative .3 and positive3 but if you could be like zero beta that's like that's that's good for them um they're not so interested you don't have to beat the S&P 500 you need like low volatility you need a very uh I guess the best word maybe is Diversified they used to require that you long in short companies but that's not a requirement anymore it appears but you it probably is is kind of just because you want to be able to have a a a neutral beta so anyway you you can get capital allocations from quantopian now they are going to um someone like if you try to get a capital allocation they're just like handing out money so so if you try to get a capital allocation actually like a professional analyst is going to look at your strategy and your performance and the um the underline kind of statistics of your strategy and what's interesting is um it would appear to me that that probably the exact same tools that that strategist is using to or analyst rather is looking to analyze your strategy uh are available to you as well so the bigger things that I just have kind of caught my eye since I kind of just started looking back into quantopian is Alpha lens and pfolio probably especially Alpha lens uh which gives you access to things that again would take you probably like thousands of hours okay so so the the tools that are being thrown at you here are tools that you would probably get if you were like an actual Quant at you know some big Investment Bank so you have like tons of tools at your disposal here so um and and trust me the whole point of quantopian is they they're trying to find people who can make good strategies and work for them because not only are they looking to give you Capital they also have other people that want to give them Capital because they want to invest in that business model so anyway that's that uh the last thing I'll kind of say on capital is just because maybe they decline to give you Capital doesn't mean your strategy sucks it just means like possibly almost certainly especially because quantopian has been around for a while there there's a high chance that you your strategy is very similar to someone else's strategy that already exists so if that's the case they're not going to just do another one that's basically the same anyway moving along from there um when you get uh basically go to quantopian make an account um I will just point out the community real quick so go to community and forums um when you come here you can immediately see um lot like you know these posts but then over here you'll see these red things little squiggly lines are back test this little thing is a notebook so the back test like for example if I just open this one up real quick um there's some information on this doesn't look like this is actually doing anything I'm not really sure what it does here this one does something so so you can you know you can look at it's embedded so you can check the risk metrics and stuff and you can see the source code that generated this um but you can also literally click clone out algorithm and it will take it and and let you it'll add it to your algorithms and you can play with it so um so yeah there's that now anyway that's the community so you can learn a lot of good things from the community so definitely check that out also um we'll probably come here from time to time but there actual documentation for quantopian is really useful so there's no way I could possibly cover everything you can do with quantopian especially because quantopian has a lot of what I would describe as like helper functions that will just make your life easier for doing specifically trading strategy type stuff so to learn more about what's available to you I would just from time at time come over here and just read like you don't have to read word for word but just I would scroll down this sidebar and look at words that appear interesting to you so um and in fact I was kind of interested on logging a second ago um because I was interested to know if you could change it like you can on python normally with like the logging I don't see it anyway not going to waste too much time on that um anyway their docs are great so definitely check those out too and then we'll probably visit them when I have some questions on things so the next thing is basically where you're probably going to spend most of your time here is going to be under my code notebooks is as you mature um that's probably where you're going to spend most of your time that's more of like the research environment part of quantopian and then algorithms is where you'll run back test but you can also sort of back test code in notebooks so I'm going to click on algorithms for now just so I can show a really quick example of working with quantopian but pretty quickly we're going to actually transition to working more so in the notebooks section and I'll explain why um because we're going to start with algorithms first and show some of the pitfalls of starting here so anyways uh we'll click on algorithms and when you come here chances are you might have some starting ones if you just created your account maybe you've got some already because you've already had an account but if you don't have anything here uh you can click clone sample algorithm and you end up with three fascinating i' say that's a typo uh anyway so you can look at these I think they're maybe a little much for someone who's just getting started um so yeah you can kind of look through them if you'd like uh but we're going to write our own because I think starting with like a totally Clean Slate is the easiest way to understand what each thing is doing so I'm going to actually delete these and hit new algorithm and I'm going to call this I don't know pance 13 quantopian intro nice long title and I'm going to just highlight and delete everything I'm going to move this out of the way and I'm going to zoom in a little bit at least and we're going to get started so uh the first thing that we're going to do is we're going to create this initialize function so Define initialize and this just runs once when the script uh start up it takes one parameter which is context context is a python dictionary that stores a bunch of information on your strategy if you are new to python this is going to be hard on you and if you're not new to python this will be just something you have to understand but the quantopian kind of uh environment here is going to do some things behind the scenes so context was never defined nothing was imported we're never going to call initialized we're never going to call the next function we write it's just going to happen and actually these were at least in zipline which is what quantopian to my knowledge I'm pretty sure it's still built on top of zipline um was built on top of and these were actually methods in a much larger class and you would but you still have to run it but anyways some magic is happening here and you don't have to call these functions so anyway if you're new to Python and you start here and then you go somewhere else that's going to be really hard but anyway um just understand and that's happening anyway context is a python dictionary and it contains information on your um your portfolio basically it's it's about you so your portfolio the performance things like your your leverage your account stuff like that that's contained in context now we're going to add something new to context and we're going to say context. AAPL so it's a dictionary we're defining a new element basically in this dictionary we're going to say context at Apple is equal to Sid and now we're going to search for AAP and there's Apple we click it and suddenly it becomes 24 seems kind of arbitrary uh it's not so Sid actually it kind of is but anyway Sid uh to my knowledge is it's a jet flying over sorry if you hear that Sid is stock ID I'm pretty sure I'm kind of making that up on the Fly I'm pretty I'm going to guess it's stock ID and what it does is basically over time like Apple has been around uh for the duration of I think pricing goes from like 2001 to current and I'm pretty sure Apple's been that ticker since 2001 I think Apple was like 1999 or something so anyway Apple has has held the the AAPL ticker that whole time but other companies have not other companies have had tickers maybe they went out of business and then like another business came in and actually was able to acquire that ticker so tickers change over time but the actual company name doesn't so you can search with Sid and this is your way of ensuring that you're actually investing in the right company so you could have also said like apple here maybe yeah and still found Apple Inc Okay so we've got that now what we're going to do is that's basically the end of our initialized function for now I mean normally you'd have other things in here you might schedule some functions or something like that but for now we're just defining um this single you know what is Apple so now what we're going to do is we're going to Define a handle data function and it's going to take context and it's going to take data now data is your Universe of information so this is like your world it's your environment okay it's your universe so this is going to contain things like stock prices now um to access it super simple we're going to say hist for history equals data Dot and you've got a bunch of information here but we're looking for history um and then already pops up to it says okay you've got asset Fields bar count and frequency well the asset that we're interested in is context. AAPL the um Fields Fields is like what kind of data like price volume stuff like that we are interested in price bar count how many fields of these things are we interested in we're going to say 50 and frequency is going to be 1 D for one day you can also do 1 M for one minute but we want day and then we'll we'll close this off and there's our history so so we've got 50 periods of one day data history prices for Apple okay so cool now that we've got that we're going to generate some simple moving averages if you do not if you're not familiar with simple moving averages and like a simple moving average crossover strategy first of all we're not going to make any money with this but it's going to be a good example so this is a stock of some kind I'm not sure whose stock price this is but anyways there's a 20 ma and a 5050 Ma so the 20 ma is the red line the 50 ma is the Gold Line or yellow whatever um and basically the the whole point of a simple moving average crossover strategy is to detect when a price might be trending and invest in the trend so for example wouldn't it be nice if you bought right here and you sold here or bought right here I guess you would have sold here but that's okay bought right here and then sold up here right wouldn't that be ideal or started to short here and bought back here wouldn't that be great all right so that's kind of the whole point of simple moving average crossover strategy let's see if it actually works though so once we've got that um we need to basically from history generate the basically simple moving averages so we're going to say sma50 and that's going to be equal to hist mean so I guess it might be unclear what hist is so let's go ahead and do a loginfo ht. head so history is a pandas data frame and basically everything when you get data um at least a lot of things are going to be Panda data frame so if you know how to work with pandas you'll know how to work uh with this data if you don't know how to work with pandas don't worry there's a tutorial for that python proget data analysis data analysis pandas and you can learn all about lovely pandas so anyway pandas uh now we've got sma50 that's h mean now we can do the SMA 20 that can be hiss the last 20 days of the history do me perfect so now with this information we've got the simple moving averages defined um now we're ready to actually Place orders with that and I think I'm actually going to stop it here and in the next tutorial we'll actually Place orders and kind of see see where we're at at that point um cuz we're going to learn we're going to learn some good good lessons in the next one so uh if you have any questions comments concerns whatever up to this point if anything appears magical or black boxy or whatever uh let me know also I guess what I could do is let me zoom out and I can just build this algorithm and also I guess while we're building it I'll explain how what all this stuff is too um I thought I could pull this up let's do this okay so when you're in the screen you can hit build algorithm and it's kind of like a it'll just run it real quickly to the side here um and let's go to logs hopefully we'll start getting them okay so then you can cancel here if you want I'm going to say cancel and sure enough you can see this is the um log. info his. head so as you can see it isn't indeed in chronological order so the the last 20 would be the latest 20 days of prices that's the only column here and it's the average super simple um so anyways there's that now you can pick the days or the dates basically that you want to test against this is how much money you're playing with um and then finally you can hit run full back test but we're not trading right now so I'm not going to click that but normally you can click that but you'll see that in the next tutorial so anyways yeah questions comments concerns below if anything's not making sense to you at this point uh let me know I'll do my best to help you out otherwise I'll see you in the next tutorial

Original Description

In this tutorial, we're going to begin talking about strategy back-testing. The field of back testing, and the requirements to do it right are pretty massive. Basically, what's required for us is to create a system that will take historical pricing data and simulate trading in that environment, and then gives us the results. https://pythonprogramming.net https://twitter.com/sentdex https://www.facebook.com/pythonprogramming.net/ https://plus.google.com/+sentdex
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from sentdex · sentdex · 0 of 60

← Previous Next →
1 Matplotlib Python Tutorial Part 1: Basics and your first Graph!
Matplotlib Python Tutorial Part 1: Basics and your first Graph!
sentdex
2 Python Encryption Tutorial with PyCrypto
Python Encryption Tutorial with PyCrypto
sentdex
3 Python's Logging Function
Python's Logging Function
sentdex
4 wxPython Tutorials 1: Making Windows GUIs with Python : Installing + 1st window!
wxPython Tutorials 1: Making Windows GUIs with Python : Installing + 1st window!
sentdex
5 wxPython Tutorials 2: Making Windows GUIs with Python: Customizing Window Parameters
wxPython Tutorials 2: Making Windows GUIs with Python: Customizing Window Parameters
sentdex
6 wxPython Programming Tutorial 3: Menu Bar and Menu Button
wxPython Programming Tutorial 3: Menu Bar and Menu Button
sentdex
7 wxPython Programming Tutorial 4: Panels
wxPython Programming Tutorial 4: Panels
sentdex
8 wxPython Programming Tutorial 5: User Input Saved To Variables
wxPython Programming Tutorial 5: User Input Saved To Variables
sentdex
9 wxPython Programming Tutorial 6: Multiple Choice Input
wxPython Programming Tutorial 6: Multiple Choice Input
sentdex
10 wxPython Programming Tutorial 7: Adding Static Text and Colors
wxPython Programming Tutorial 7: Adding Static Text and Colors
sentdex
11 wxPython Programming Tutorial 8: Custom Button Images
wxPython Programming Tutorial 8: Custom Button Images
sentdex
12 wxPython Programming Tutorial 9: Tool Bar Items and Sub Menus!
wxPython Programming Tutorial 9: Tool Bar Items and Sub Menus!
sentdex
13 Basic PHP Tutorial 13: Multi-dimensional Array
Basic PHP Tutorial 13: Multi-dimensional Array
sentdex
14 Basic PHP Tutorial 15: Functions and Global Variables
Basic PHP Tutorial 15: Functions and Global Variables
sentdex
15 Basic PHP Tutorial 12: Associative Array
Basic PHP Tutorial 12: Associative Array
sentdex
16 Basic PHP Tutorial 14: Foreach loop
Basic PHP Tutorial 14: Foreach loop
sentdex
17 Basic PHP Tutorial 16: Include and Require
Basic PHP Tutorial 16: Include and Require
sentdex
18 Basic PHP Tutorial 7: Assignment, comparison and Logical operators
Basic PHP Tutorial 7: Assignment, comparison and Logical operators
sentdex
19 Basic PHP Tutorial 4: Variables and Comments
Basic PHP Tutorial 4: Variables and Comments
sentdex
20 Basic PHP Tutorial 11: Arrays part 1, basic array
Basic PHP Tutorial 11: Arrays part 1, basic array
sentdex
21 Basic PHP Tutorial 6: If else and else if conditionals cont'd
Basic PHP Tutorial 6: If else and else if conditionals cont'd
sentdex
22 Basic PHP Tutorial 1: Intro to PHP
Basic PHP Tutorial 1: Intro to PHP
sentdex
23 Basic PHP Tutorial 3: HTML with PHP
Basic PHP Tutorial 3: HTML with PHP
sentdex
24 Basic PHP Tutorial 9: While Loop
Basic PHP Tutorial 9: While Loop
sentdex
25 Basic PHP Tutorial 10: Switch Statement
Basic PHP Tutorial 10: Switch Statement
sentdex
26 Basic PHP Tutorial 2: Print and Echo
Basic PHP Tutorial 2: Print and Echo
sentdex
27 Basic PHP Tutorial 5: If else and else if conditional statements
Basic PHP Tutorial 5: If else and else if conditional statements
sentdex
28 Basic PHP Tutorial 8: Arithmatic Operators: Doing math with php
Basic PHP Tutorial 8: Arithmatic Operators: Doing math with php
sentdex
29 Basic PHP Tutorial 17: User Input Form Example / String Manipulation
Basic PHP Tutorial 17: User Input Form Example / String Manipulation
sentdex
30 Basic PHP Tutorial 18: HTML Entities and forms cont'd
Basic PHP Tutorial 18: HTML Entities and forms cont'd
sentdex
31 Basic PHP Tutorial 19: Finding words in strings
Basic PHP Tutorial 19: Finding words in strings
sentdex
32 Basic PHP Programming Tutorial 20: Saving to a File / writing and appending
Basic PHP Programming Tutorial 20: Saving to a File / writing and appending
sentdex
33 Basic PHP Programming Tutorial 22: Hashing part 2: salting
Basic PHP Programming Tutorial 22: Hashing part 2: salting
sentdex
34 Basic PHP Programming Tutorial 23: Variables in Strings and tokenizing
Basic PHP Programming Tutorial 23: Variables in Strings and tokenizing
sentdex
35 Basic PHP Programming Tutorial 21: MD5 Hashing For Security
Basic PHP Programming Tutorial 21: MD5 Hashing For Security
sentdex
36 Basic PHP Programming Tutorial 24: String similarity
Basic PHP Programming Tutorial 24: String similarity
sentdex
37 Basic PHP Programming Tutorial 25: Time and Time stamps
Basic PHP Programming Tutorial 25: Time and Time stamps
sentdex
38 Basic PHP Programming Tutorial 26: Die and Exit
Basic PHP Programming Tutorial 26: Die and Exit
sentdex
39 Basic PHP Programming Tutorial 27: MySQL Databases Part 1
Basic PHP Programming Tutorial 27: MySQL Databases Part 1
sentdex
40 Basic PHP Programming Tutorial 28: MySQL Database Part 2: Reading From Database
Basic PHP Programming Tutorial 28: MySQL Database Part 2: Reading From Database
sentdex
41 Basic PHP Programming Tutorial 29: MySQL Database Part 3: Inputting Data
Basic PHP Programming Tutorial 29: MySQL Database Part 3: Inputting Data
sentdex
42 Basic PHP Programming Tutorial 30: MySQL database in Use
Basic PHP Programming Tutorial 30: MySQL database in Use
sentdex
43 Django Tutorial Web Development with Python Part 1: Installing Django
Django Tutorial Web Development with Python Part 1: Installing Django
sentdex
44 Python Tutorial: File Deletion and Folder Deletion / directory deletion
Python Tutorial: File Deletion and Folder Deletion / directory deletion
sentdex
45 Python Tutorial: How to Rename Files and Move Files with Python
Python Tutorial: How to Rename Files and Move Files with Python
sentdex
46 3D Graphs in Matplotlib for Python: Basic 3D Line
3D Graphs in Matplotlib for Python: Basic 3D Line
sentdex
47 3D Plotting in Matplotlib for Python: 3D Scatter Plot
3D Plotting in Matplotlib for Python: 3D Scatter Plot
sentdex
48 3D Charts in Matplotlib for Python: Multiple datasets scatter plot
3D Charts in Matplotlib for Python: Multiple datasets scatter plot
sentdex
49 Sikuli Tutorial 1: Visually programming in python!
Sikuli Tutorial 1: Visually programming in python!
sentdex
50 Sikuli Tutorial 2: Program visually in python!
Sikuli Tutorial 2: Program visually in python!
sentdex
51 Sikuli Tutorial 3: Program visually in python!
Sikuli Tutorial 3: Program visually in python!
sentdex
52 3D Bar Charts in Python and Matplotlib
3D Bar Charts in Python and Matplotlib
sentdex
53 3D Plane wire frame Graph Chart in Python
3D Plane wire frame Graph Chart in Python
sentdex
54 Raspberry Pi Part 1 Introduction
Raspberry Pi Part 1 Introduction
sentdex
55 Raspberry Pi Part 8: First Download and Update! (Firmware)
Raspberry Pi Part 8: First Download and Update! (Firmware)
sentdex
56 Raspberry Pi Part 10: How to set up a Linux Web Server on your Pi
Raspberry Pi Part 10: How to set up a Linux Web Server on your Pi
sentdex
57 Raspberry Pi Part 11: Remote Desktop
Raspberry Pi Part 11: Remote Desktop
sentdex
58 Twitter Analysis: How to rank a user's influence
Twitter Analysis: How to rank a user's influence
sentdex
59 GPIO Tutorial for Pi Part 2 - Programming the GPIO
GPIO Tutorial for Pi Part 2 - Programming the GPIO
sentdex
60 GPIO Tutorial for Raspberry Pi Part 1 - Setting up
GPIO Tutorial for Raspberry Pi Part 1 - Setting up
sentdex

This video teaches how to use Quantopian and Python to create and test algorithmic trading strategies, with a focus on strategy back-testing and the requirements to do it right. It covers the basics of Quantopian, how to use its community and forums, and how to create and test trading strategies using Python.

Key Takeaways
  1. Make an account on Quantopian
  2. Go to the community and forums
  3. Look at posts and back tests in the community
  4. Click clone out algorithm to add it to your algorithms
  5. Check the risk metrics and source code in the back test
  6. Delete sample algorithm and hit new algorithm
  7. Create an initialize function
  8. Add a new element to context with Apple's stock ID (AAPL) as the value
  9. Search for Apple's stock using the stock ID
  10. Define a handle data function
💡 Quantopian provides a powerful platform for backtesting and creating algorithmic trading strategies, and its community and forums are valuable resources for learning and improving trading skills.

Related AI Lessons

Up next
Salesforce Flow New Features (Summer '26) | Open Record, URL & Show Toast Messages
AITECHONE
Watch →