Backtesting Stock Trading Strategies in Python with Zipline

NeuralNine · Beginner ·📐 ML Fundamentals ·1mo ago
Skills: ML Pipelines80%

Key Takeaways

Backtests stock trading strategies in Python using Zipline

Full Transcript

Today we're going to learn how to back test stock trading strategies in Python using a package called zipline which allows for eventdriven back testing which means we're simulating the days one by one or we're back testing the days one by one. So we're going through the history. This happened on day one. This happened on day two and day by day we make decisions. We can implement our own strategies with different technical indicators with technical analysis strategies and then we can see how we would have performed if we were to apply the strategy in a specific time frame. So in this video today, we're going to learn how to implement these strategies. We're going to work with different data sources. We're going to take a look at things like leverage and shorting and also considering the transaction cost also trading multiple assets. So we're going to learn a lot today. If you like this video, let me know by hitting a like button and subscribing. And now let us get right into it. >> All right. So, we're going to learn how to back test our stock trading strategies using a Python package called Zipline. And I'm going to tell you about the history of this package a little bit because you need this for context. But first of all, very important here, every time I do financial videos, this is not financial advice. This is not a finance tutorial in any way. This is a programming tutorial. I'm showing you how to use a package, what strategies you use, and what you interpret, how you interpret the statistics. I might make mistakes here when it comes to explaining financial concepts. You are responsible for your own decisions. So this is not a financial tutorial. It is a tutorial, a programming tutorial on a financial package. But of course, you need to know uh what you're doing and I'm not responsible for any losses or whatever you do with your finances here. So having said that, let's briefly talk about zipline. Zipline was a package by Quantopian uh which is a company in the quan space I guess and they're no longer maintaining this package. So this package is basically dead. But there is a guy here um Stefan Jansen if that's the correct pronunciation. He also writes books so maybe you want to check them out. But he's basically keeping a bunch of these finance packages alive. Pyfolio zipline as well. And he's keeping this package alive. He's maintaining it. So we have zipline reloaded which is the thing that we're using in this video today. And this is the documentation page. So zipline is for eventdriven back testing. The idea is we have assets that we're trading. We have a certain strategy. This can be every time certain metrics cross, every time certain metrics go above a threshold, uh we're just going to go and buy or sell stocks. And how we define a strategy is what we're going to learn in this video today. And we're going to also see how to evaluate them. So let us move into the setup. I'm going to go into my tutorial directory. This is where I want to be working in. Uh this of course works on all different operating systems. I'm working on Linux here. You can do the same thing on Mac. You can do the same thing on Windows. Uh the installation is just a Python package. So either you use your core Python installation by saying pip or pip 3 install zipline and then reload it of course if you want to have the current one uh or in my case I'm going to use the UV package manager. So if you also want to do that you need to make sure you have UV installed. You can do that also using pip. Uh and once you have UV you can say UV init but you don't have to use UV. If you don't know what UV is and it confuses you just don't do it. Use pip directly. Install zipline reloaded. In my case, I'm going to say UV atzipline- reloaded. And that is going to give me the package. Uh later, we're also going to install other packages, but I want to start with a very simple strategy. I want to implement a completely random stock trading strategy, which is basically every day, we're going to flip a coin, and if the coin is uh in this case, it's not a coin, it's a threshold. So, if the random number between 0 and one is above 0.5, we're going to buy stock. Otherwise, we're going to sell stock. And that is exactly what we're going to do here. Nothing too fancy, just to show you how we can build the most stupid strategy there is. So for this, I'm not sure if pandas is installed, but we're going to use pandas as well. It's part of zipline already. And I'm also going to activate my virtual environment here to get autocomp completion in my editor. Now, I'm using Neo Vim here. You can use VS Code. You can use uh Jupyter Notebooks, whatever you're comfortable with. You just open a file with that editor, delete everything, start a blank new file. I'm going to call mine main py here, but I'm going to rename it later. And we're going to start by importing pandas as pd. And we're also going to import from zipline the function order target. Now, you have multiple different ways to order stuff to place an order. You can go for target, which means that you're targeting a certain number of shares. like order target 100 of a certain ticker would be I'm aiming to have 100 shares of Apple, for example. It doesn't mean that I order 100 shares. It means that if I have 50, I'm going to order 50. If I have zero, I'm going to order 100. If I have 100, I'm going to uh keep 100. And if I have 200, I'm going to sell 100. So, the target is always like where I want to end up. Uh we're going to use that order target method or function here. And we're also going to use record to keep track of stuff and also symbol for the ticker symbol. Now in addition to that, we're also going to say from zipline itself, we import the run algorithm. There's two ways in which you can run zipline scripts. You can run them in the file or you can run them with a command. I'm going to show you both, but we're going to go with the code uh way of running the algorithm. It's just nicer in my opinion. And then also we want to import random because our strategy is just going to be flipping a coin. So the first thing we need to define is a function called initialize. So we're going to say initialize and this function is going to take in context and it's going to do some stuff. Now what it does depends on what we want it to do. But in my case here I want to start at a specific day. I want to say that in my context here I is initialized as zero. Day zero is the first day of trading. And I can also define the ticker symbol. So context dot ticker is going to be equal to symbol and then apple or actually ticker is not correct because ticker is apple since we're going with symbol apple I should say it's the asset that we're trading context asset is symbol apple so this is now our context that we initialized the second thing is going to be handling uh the different days so we're going to say handle data and this is going to take take in context and data data. So we use the context we have and we also have data that we want to process. And here basically we have our trading logic. So one thing that we're going to do here is we're going to advance I. We're going to always go to the next day. So I is going to be plus equal to one. And then my basic trading strategy will just be if random.random this is a number between 0 and one. Um if that is above 0.5 so that's basically a 50% chance then I'm going to buy. So I'm going to say order target. I'm going to provide the asset which is context.asset and the target which is 100 shares and otherwise I'm going to just do the opposite which is I'm going to target zero. So we're always either going to own 100 shares of Apple or zero. So we don't have anything else which is buying and and selling 100 shares of Apple stock. Now important uh for the actual back testing we need to record stuff. We need to keep track of stuff. So I'm going to say here record and we can provide keyword arguments here to keep track of stuff. Now, in this case, we don't have any fancy indicators. So, I'm just going to keep track of the price. So, I'm going to say aapl is equal to data.curren. And then in here, we need to provide the asset. So, context asset and as a string the thing we're interested in, the current price. So, we're keeping track of the Apple price and we're buying and selling. And a lot of stuff is also being kept off uh kept track of automatically like the portfolio value and everything. We don't need to calculate this manually, but now we're recording the price of the Apple stock. Now, theoretically, we can already close this and use a command which I'm going to have to copy or not copy but type from my second screen because I don't know it uh off the top of my head. But basically, we can run the strategy now by saying zipline run. And for this, you need to be in your virtual environment if you're using UV so that it recognizes zipline or you have to do UV run but zipline run is fine. And then we say -f and the file that has the strategy. So main py and then we say d- start and we provide a starting date and uh let's go here with 2014 1st of January and then we're going to also say end date is 2018 1st of January then we also provide an output - o is going to be results.pickle pickle for example and then d- no benchmark to compare against. Now this will not work the first time you do it. I'm not even sure if it's going to work in my case now. But what you need to do for this to work and in this case it does work because I already did that. You need to have data on your system. You need to actually have data that you can work with. And the default data source here is Quandle. Now Quandle might not be optimal for a number of different reasons. So, I'm also later in the video going to show you how you can use the Y Finance package to download current data for free without an API key. I want to show you both though because that's the simple way to do it. That's a default way to do it with Quandle. So, Quandle, I'm not really too familiar with it. But basically, it's a NASDAQ uh thing, a NASDAQ API, I think you could say. So, you just have to log in. You have to sign up. Uh you don't have to pay anything for that. you you just go to NASDAQ data link and then you go to your account settings and you will see an API key. In my case now hopefully I'm censoring this out but that is an API key that you need. Now with this API key it's totally free but you can only access data from the past. So you're downloading a wiki I think it's called data set and you're not really um allowed to access data that is current for free. You can pay and get the up-to-date data. So we're going to work with the past data for now and later in the video I'm going to show you how to use the Y finance API to just download any data you want and then do the same thing here. So for that what you now need to do is you need to say export and then quandle API_key and then is equal to whatever API key you got from the account settings. So I'm not going to do this here. I already did this. But you just have to export this in your command line so it exists as an environment variable. And then you need to run the zipline command. Zipline ingest and then quandle. So quandle is going to be downloading this specific uh bundle is what they call it. So you're downloading the quandle data. So yeah, once this is done, you can just run the strategy and it's going to use the data from this time frame in this case for Apple and you get a results object. So results.pickle. Now I'm going to show you uh how to run the same thing also in Python first and then we're going to take a look at the results. So instead of doing this in a command line, you still need to do the ingest command, but instead of running the strategies in a command line, you can also say here if_ame is equal to main then we're going to run the algorithm. And here now we need to provide a bunch of arguments. So the first thing is we want to have a pd.timestamp. So that's going to be our uh date for the starting date. Here we're just going to say 201401. I'm going to copy this. I'm going to say int is equal to the same with 2018. The initialize function is going to be equal to initialize. The handle data function is going to be equal to handle data. Then also interesting capital base. We can also provide it in the command line. We can set this to a certain uh value. So I start with $10,000 for example. However, this is not necessarily um enforced. I mean, it is kind of enforced, but you do have the problem that if you don't provide specific extra stuff that we're going to talk about here in a second that you can basically buy whatever you want with leverage. So, we're we can provide this, but it's not going to be super important because even with $1, I can buy endless amounts of Apple stock just because I can use leverage here. Then, we're going to say data frequency is daily. So, we have daily data and then important here bundle is equal to quandle. And later on, as I said, we're going to change this. then we can use our Y finance CSV files. But for now, we're going to use Quandle. It's just the simplest way to do that. And now I can do UV run main py and we get the same thing. So I can actually remove the results to show you that they're going to uh come again here. So u main py and we're going to get the results.pickle file. And this thing here returns actually the results. So we're going to say results is equal to run algorithm and we need to export them to pickle. So we need to actually say here results 2_pickle and we're going to call this results.pickle. There you go. So we can save this and now I can just do UV run main py and that is going to result in the same thing as before. We don't get all the output but you do get the results pickle. So I can also remove that here uh results pickle and run the whole thing again and then it will be there afterwards again. Results pickle. So now to take a look at the results, we're going to actually use Jupyter Lab. Now this is optional. You can use a Jupyter notebook. You can use an ordinary Python script. I just want to use Jupyter Lab. So I'm going to say here UV at which is again the same as pip install on your system. UV at is going to be Jupyter Lab the first package and the second package mattplot lip for visualization stuff. And once we have this, I'm just going to go and say Jupiter dash uh or Jupiter space lab whitespace lab. And this is going to open this in my browser. So I actually get an interactive Python notebook to take a look at all the stuff. So I can um open a new notebook here. I can call this analysis.pipyny andb. And in here now I can load the pickle file. So here now I can say import pandas as pd. And I can load this thing as uh or from a pickle file. So I can say pd. and then pickle and then results dot pickle and I can say that this is equal to df and then I can say df and I get a data frame here. I can zoom out with a bunch of different columns. Now one thing that you will notice is that a lot of columns are hidden and also that some values are difficult to read. I mean right now we don't see that I think but often times you will have difficult values that are difficult to read. So we can set some pandas options here to make things easier for us. I'm going to say pd.options dot display max columns is going to be equal to 500. And for the other one we're just going to wait until it becomes a problem. But basically I get here now a bunch of columns a lot of columns. The interesting ones probably for us right now is we want to know how much money we made. So we can see that the starting value of the portfolio, the portfolio uh portfolio value in the beginning here is 10,000. That's our capital that we started with and then at the very end it's 19,000. So it seems like we made some profit. But again, take this with a grain of salt because we have leverage. I can just buy stock and then I have more money because the stock went up even though I started with less money than I would have uh had to buy stocks. But you get a bunch of columns here that are interesting. We're going to take a look at them later. What I want to do now is I want to just look at the portfolio value over time. So I'm going to say df portfolio value.plot. And this is going to give me the visualization of the portfolio value. We start here at 10,000 and it goes up and then kind of steady stays around the 20 20k mark I would say. But yeah, this is the random trading strategy. We're just doing something. Every day is a coin flip. whether we're going to sell or buy. Um, but now let us take a look at how we can actually do something useful. So, how could I actually implement something that might have some brain in it? So, I'm going to move my terminal to a different workspace. I'm going to also move the notebook and I'm going to open up another terminal, go to my tutorial directory, activate my environment again, and then we're going to open up a second file. Let's call this one SMA strategy py. and actually want to copy most of what we had in main py, but we're not going to use random anymore. We're going to use a simple SMA crossover strategy or I think it's called maybe dual SMA strategy. The idea is we have one SMA simple moving average for 30 days and one for 100 days for example and when they cross we want to make a decision. So since we're going for 100, let's go and first of all say skip the first 100 days. So we're going to say if context do I is less than 100 we're going to say return because in this case we don't want to do anything. We just need to let some days pass so we can calculate the simple moving average of the past 100 days. So then we're going to say SMA30 simple moving average for the last 30 days is going to be data. We will provide the context. We will provide the attribute price. And then we say bar count 30 for the last 30 days. And frequency is going to be equal to 1 day. And then we can copy this. We can say the same is for 100 days. And that's going to be bar count 100. So now we have these two metrics. And basically when they cross we want to make a decision want to buy or sell. So, if the simple So, if the 30-day simple moving average crosses the 100 day simple moving average, then I want to make the decision that we're going to buy stocks. And otherwise, if the 30-day simple moving average goes below the 100 day simple moving average, we're going to sell. We're going to target zero. That is as simple as it gets. And we can also keep track of these values now. So I can say SMA 30 is equal to SMA30 and SMA 100 is equal to SMA 100. And of course don't forget the underscore here because otherwise we're going to get some errors again. And also very important we need of course to say mean to get the mean from this time frame not just the data itself. Otherwise we don't have the average of the last 30 or 100 days. So now let's go and run SMA strategy. This will produce a new results file. And for this we can go back to workspace 4. And here we can just rerun the code and see what happened in this case. And now we can see we are the final portfolio value is also 19,000. So not too different from the random strategy. Doesn't mean anything of course but that is a simple one that we can do. Now one thing I mentioned is that this is not a reliable thing because I can just buy stocks even if I start with very very little capital. If I go here and I change the script to be uh starting with a capital base of $10, I'm still going to be able to do all the trades. So, I can run this and it will not tell me, hey, you can't do the trade. You cannot buy 100 shares of Apple because you don't have money. I can just go and use leverage. So, what I want to do to actually make this more realistic, to actually make this more uh yeah, to to actually see if this actually works is to set the option to only be able to go long. So, we're not shorting and to also not use leverage. So, I'm going to import that from the zipline API. Set long only and set max leverage. And we're going to just call this in initialize. I'm going to say set long only. And then set max leverage is going to be one. So, 1.0. One more thing. If we don't want to get the exceptions, because if I do it like this now, we probably will get uh an error when trading. So, we're going to get a signal and it will tell us that this violates the constraint for leverage. So, in this case, what I want to do is I want to check if this is possible. Can I even do the buy? If not, I'm not going to do the buy, I'm just going to skip. So, what we're doing here is if we want to buy, we're going to say if the context portfolio is greater than or equal to 100 times the price of this of one share basically of this asset. And that's going to be data current contextasset price. We're assuming no transaction cost here and no uh slippage or anything like that. If that's the case, then we're going to buy. Otherwise, we're not going to buy. So, that's super simple. And maybe we should not start with 10. That's a little bit uh that's that's not enough. But let's go with 10,000 again. And let's see if this still works without problems. So, it produced the file. Let's go to space number four here. And I'm going to rerun the entire code. And you can see that in this case actually we lost quite a bit of money. Uh we're actually didn't lose money, but we are basically back to the beginning. So this strategy didn't work out too well for us. Maybe the random one would have worked better. We can actually give this a try as well. I can just um use my old strategy again. Instead of saying this, I'm going to say if random.random random is greater than 0.5. Then we're going to do the by logic and then I'm going to say else. We're going to do this. We can still keep track of the moving averages. That's not going to harm our uh performance. So, let's run this and see if this works. Okay, I do get the violation. This is probably an issue with the timing. So maybe we should say if we have a little bit more than that, let's just go with a safety buffer of I don't know 10 bucks or something. And now this should work because otherwise, you know, you have maybe enough money, but then uh there's some small issues and you don't have enough money anymore. But let's go and see if this now performed well. Uh it performed better at least. It doesn't look super super nice, but this would be the portfolio value over time. But these are all like uh play strategies. Let's try something else. Let's go and use a MACD like a moving average convergence uh divergence I think was the was the name. Uh so let's call this MACD strategy py. Of course, again, we're going to copy most of the stuff that we have here and we're just going to change the small bits. But one thing that is going to be interesting here is we're going to involve another package which I also made a video about uh TAIP technical analysis lip. So we're going to actually use this to calculate the MACD using TAI lip. So for that we're going to go back out. We're going to say pip install or uvat and then ta-lip. So that is going to add the technical analysis lip and we can now use it easily or use that to easily calculate the MACD. So I can say now the context. Let me go full screen again. uh the context here if we have the first 50 days. So that is less than 50 we're just going to return and otherwise let's get rid of all this. We're going to get the prices of the last 50 days. So prices is going to be equal to uh data history context asset price then what was it bin count bar count I think 50 and then frequency was 1D and these are the prices now we're going to use those for the MACD so we're going to say MACD signal and histogram is equal to talip and of course we need to import that actually so let's go here import talip go back down and we're going to say this is equal to talib and here we need to provide some data now. So prices and then the default settings are fast period 12 then slow period is 26 and then the final thing is the signal period is equal to 9. So this gives us now the MACD the signal and the histogram. We only want the last value. So, MACD is going to be equal to MACD -1 uh like this. And then we're going to do the same thing for signal signal and for the histogram values. So, his is equal to his negative one. And our rule is basically going to be if the MACD goes above the signal, we're going to buy. But of course, we're going to check again if this is possible. And otherwise, if the MACD is less than the signal, we're going to go to zero and we're going to not keep track of the SMA because we don't have it. But we're going to keep track of MACD. Signal is equal to signal and hist is equal to hist. That would be another very basic strategy. UV run MACD strategy. And now if we go back to our notebook, run everything from top to bottom again, we can see that this one actually performs quite well. So over this time period, we would have ended up at around 14K with the strategy considering that we're using no leverage. If I may for a second, I would like to plug myself in as the sponsor of my own video. If you go to my website, neural9.com, you will find a tab services and a tab tutoring. Here you can hire me for all sorts of stuff like data science, machine learning, web development. If you need help with something in a project, here you can book me for one-on-one tutoring. If you want me to teach you personally something that you don't understand, if you like my teaching style, on both pages at the bottom, you can contact me via mail and also via LinkedIn. Just wanted to let you know about this. Now, I want to go back to the SMA strategy and show you how we can do shorting. So, how we can actually short stocks. And for this, we can keep everything as is here, but instead of just going to zero if the SMA 30 is less than the SMA 100, we're just going to short the stock. And we do that by saying negative 100, which means we're sh we're selling 100 shares that we don't own. And for that, of course, we're going to get rid of this. And we're going to also get rid of that. So I'm going to comment this out. And this now is basically also a shorting strategy. So I can say UV run SMA strategy. And this is going to sell stocks or bet against stocks as well instead of just not buying them or selling them. So let's run this and see if this was a good decision in this specific time frame. Yeah, I mean we did have quite a dip here. So the max draw down is quite crazy, but we do end up at a very high position. But this is with leverage. So take that again with a grain of salt. So now I want to show you probably one of the most important things. How can we actually download data that is not quandle data? Because Quandle requires an API key is paid. So here now we're going to create a script called download Y finance data.py py or call this whatever you want. Uh I'm going to save this file but also of course we need to install the Y finance package. So either again pip install uh or pip 3 install or uv and then yinance. This is going to add the yinance package here as a dependency. And now we can just download the data set using this script that we're going to write. And we're going to um to then turn this into a CSV file and then register it as a proper bundle with zipline. So to speed this up a little bit, I'm going to do copy pasting here. I'm not going to copy paste the entire thing at once because I do want to explain what we're doing. But I want to save time here with typing. So I'm going to just copy paste segments. If you don't know how to work with Y Finance, I have a crash course on this channel where you can see how to work with the Y Finance package. But it's actually quite simple. We start by importing pandas and Y Finance. We define a couple of ticker symbols that we're interested in downloading. These are going to be in our data set. So we can then access the stock prices of these ticker symbols. Then we iterate over these ticker symbols. We basically say data frame is equal to taking the ticker instance of that ticker symbol. Get the history from 2014 uh January to 2026 January. So this is up to date. We can actually use the current data that we have or actually this is like a couple months ago. But you can still also adjust this to be today essentially. Um, and then what we do is we reset the index. We rename the columns to be compatible with the zipline notation. So date is date open but all in lowercase. We then also fill up the other values that are part of zipline. So we have the date here. We turn this into a specific format into year, month, date with dashes. We have dividend zero split one. And then we just get all the columns. The data frame is now limited to these columns and they're also in the right order the columns. And then finally we say here for column in all the columns df column is equal to pd2 numeric. So we're type casting that we're dropping all the nan values. And then we're exporting this to a directory here which is zipline csv. You can call this whatever you want. Slash daily. This is important. You need a notation some directory slash daily and then ticker csv. This is important. You need to do it like this. And you need to make sure that this directory exists. So I'm going to say make directory here and I'm going to create zipline csvs /aily. So that's going to create a directory. And then I can just run the download yinance data script. So now if I take a look, we do have the data in ziplines and daily. There are the CSV files for the respective companies. And now what we also need to do is this is a uh global thing. So this is not limited to a project. You need to go to your user directory on Linux and Mac. You go to user and then dozipline and then there's an extension py file. And in here, I already have this because I played around with this uh for the video. But I'm going to have to change stuff because now we're actually working with um with a different directory here. But basically, you just import pandas. You just have the zipline stuff. By the way, all this code will be on my GitHub, so you can copy paste it from there if you don't want to type it. But basically we just define the time frame here and we use register from zipline to register whatever you want to call this. I call this Y finance CSV directory bundle and we pass here daily and the path. So home neural 9 documents programming neural 9 here it should not be YouTube preparation now and not zipline tutorial and not scratch but we're going to go with tutorial/zipline. So that's just going to be the directory that I'm working in. And then we have calendar name, New York Stock Exchange, start session, end session. That's essentially it. What we need to do now once this is set up is we need to run the ingest command again. So we need to run zipline ingest same as quandle before but with Y finance CSV deer bundle. So that is going to load this as an actual data frame here or as an actual data source here. And now we can just go into our MACD strategy for example and change the bundle to be equal to our Y finance CSV deer bundle. And this allows us of course to also use time frames that are more modern. So I can go with 2025 or actually let's go with 20. Yeah, let's go with 2025. That's fine. And so I can now save this and I can do UV run MACD strategy again. And this will now use my data source with the uh Y finance data that I downloaded as CSV. And if I now go back here, I can run the analysis and you will see that we have the time frame being up until 2025 and we're going up here with this strategy. Now, by the way, also I copy pasted this. Now we have other columns that are also interesting here. So we can go uh now I don't have results. I actually called this DF. So let's say that results is equal to DF because this is my prepared code. Um basically we have stuff like final portfolio value total return this would be602 63ish% um return. So basically we more than doubled our portfolio value. Max draw down basically means the worst dip we had from a peak down to the valley is negative uh where it's 17.75% drop. sharp ratio of almost one is not that good but I I would say okay so starting with one it's getting into the good is it a good uh section of the sharp ratio the good range uh total orders is how many trades we made total transactions here and then we have also the last position so what does our portfolio look like in the end because it could also be empty because we just sold and didn't buy again so this is some interesting stuff to look at but you can also just go and say df columns to see all the different columns and probably some of you guys watching just will be finance experts. So, you don't need me to explain to you uh what all this stuff is and what you can use it for. I'm showing you how to work with it on a programming basis. Now, I want to show you how to work with multiple ticker symbols. So, let's go back to our MACD strategy and let's say we're not just trading Apple, we are trading multiple tickers. I'm going to be trading Apple. I'm going to be trading uh Nvidia. So, I'm going to say tickers is Apple is Nvidia. Or actually, let's let's make this more intelligent. We're going to say here that the assets we're trading are going to be a list. So, it's going to be dot assets and that's going to be a list. And we have symbol apple here and we have uh not this. There you go. Symbol Apple here. And then it's going to be symbol Nvidia and it's going to be symbol or what did I have actually in my in my download finance data? Yeah. So, Apple, Meta, Nvidia, Tesla, and Google. So, let's go with that. Tesla and Google. And then we just have to make sure that we iterate over them and trade all of them. Now, we're also going to set a target weight. So, I'm going to say context.target weight is going to be 19%. So, we're trying to have 19% of each of these stocks in the in the um portfolio if possible. And then here now I'm going to start a loop for asset in context. I'm going to say if not data can trade asset. So if you cannot trade the asset, we're just going to continue. And otherwise, we're going to do all of this here. So basically, all of this stays the same, but we're going to record more data now. We're going to record um a dictionary that we're going to unpack. So I'm going to say record and then here I'm going to say asterisk asterisk. So unpacking operator here with dictionary and we're going to use formatted strings. So asset do symbol and then underscore price is going to be equal to the price or in our case that's the data current context or actually not context it's just asset and then price and this is of course important because here we also shouldn't have context asset but just asset that's that and then we're going to copy this here and do the same thing with MACD and with signal and with hist. And then we're going to say that that's actually just the MACD and the signal and the hist. So that's that. Let's see if this works or if I forgot something. So let's run the strategy. Uh trading algorithm has no asset. Yeah, this is a problem of course. So some at some point I didn't actually replace this. So that is the context asset here. Of course, that's just the asset, not the context asset. And it seems like we have another one. So that should be context assets. Context assets. There you go. Order target is of course asset and not context asset because now we're iterating. So it's not in the context. And also of course one very important thing that we didn't do um I of course didn't replace the order target in general. We need to also say we're now going to order the target weight. So that's going to be order uh target uh percent. So order target percent is the function here. And we're going to say order target percent asset and the context dot target weight. And here it's just going to be target percent zero. So order target percent asset zero. And of course you should spell context correctly. So UV run MACD strategy. So now it has to execute of course five times the same logic. So this will take a little bit longer, but also we can do a very interesting visualization because of that. I'm going to copy paste this one too because of course this is not a map of the tutorial and we're already spending too much time on writing all the code here. So this is now done. Let's go into the analysis notebook here. This is going to be still the entire portfolio value. So that's going to be like this. This is crazy. Probably mostly due to Nvidia is my guess. Um and we can see what the last positions look like. So speaking of that, I'm going to now show you here. I have it in my notebook prepared because I already did of course all the coding. Uh here we have a simple math.lip script. So we have last positions and the cash amount that we still have. This is what we didn't spend uh on stocks. And now if I just run this, we will see a visualization here of our portfolio in the end. 62% cash. So that's almost 50k and Nvidia and Apple are still 18 18.8% here. That's awesome. And that's that's a very nice visualization to have here and to analyze the portfolio performance. But again, we started here I think similarly with a portfolio value or starting cash of 10K and in the end we have way more than that. So this is the cash where's a portfolio value. There's a portfolio value. You start with 10K and now you have 80K in the end. This is this is very nice. Now the very last thing I want to show you here is how we can actually also consider or take into account the transaction cost. So for this we can say from zipline.inance import the commission and the slippage. So this is basically commission what you have to pay to the broker and slippage uh for the timing delays and everything. And we also need the two functions here uh set commission and set slippage. So we're going to say here set commission and then we can say commission is dot per share. So per share we have a certain cost. Let's say the cost is 0.001 and the minimum trade cost is nothing. And then I can say set slippage as well. And I can say it's a fixed slippage with a spread of 0.01. So we can just set this up to have a more realistic scenario here. Now probably let let me remove some of the tickers so we don't have to run through all the stuff again. I'm just going to go with two of them with the two winners, Apple and Nvidia. I'm going to run this. And now we have also the transaction cost and everything. So this is also kept um or this is also taken into account. So now again back to the notebook and let's see we're not going to really probably see a huge difference here. Yeah, still going going up to the moon so to say. Yeah. So this is back testing with the zipline package in Python. So that's it for this video today. I hope you enjoyed it and I hope you learned something. If so, let me know by hitting a like button and leaving a comment in the comment section down below. Also, in case you're interested on my website, you will find a services tab and a tutoring tab. There you can contact me if you need help from freelancer. If you need some help with a project, if you need consultation, you can contact me at the bottom of these pages using LinkedIn or email. Besides that, don't forget to subscribe to this channel and hit the notification bell to not miss a single future video for free. Other than that, thanks much for watching. See you next video and bye.

Original Description

💻️ Need some help with a project or some consulting? Contact me here: https://www.neuralnine.com/services 🐍 The Python Bible Book: https://www.neuralnine.com/books/ 💻 The Algorithm Bible Book: https://www.neuralnine.com/books/ Timestamps: (0:00) Intro (0:54) Environment Setup (4:03) Backtesting Random Trading Strategy (15:45) SMA Crossover Strategy (22:03) MACD Strategy (26:30) Yahoo Finance Data (32:45) Trading Multiple Stocks (37:37) Transaction Cost & Slippage (38:59) Outro
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Related Reads

Up next
What is Deep Learning Explained with Examples
VLR Software Training
Watch →