Python Algorithmic Trading Course – Massive, SnapTrade & Alpaca Integrations

#Algorithmic Trading #Python #Django #SnapTrade #Alpaca #Massive API #Programming
💬 Chat with this Video
Ask anything about this video…
In this practical you are on course will use Python for creation full-fledged algorithmic trading systems paper tools from scratch. You will configure uninterrupted connecting conveyor market data from Massive for safe portfolio execution via SnapTrade. Main program logic calculates 12-month momentum indicators for a universe of 50 shares for generation automated trading signals. These signals then automatically are directed to simulated brokerage account Alpaca for risk-free implementation. This course became possible thanks to a grant from SnapTrade and Massive. Nick McCollum created this course with the help of Katie Charbonneau. Hi, I'm Katie from SnapTrade. I will show you how. customize yours SnapTrade account . So, the first thing you need to do is need to do this go to the website snaptrade.com and click "Start" button. Now you can choose " commercial" and press " Continue". Now you can you fill this out information and press the " button Register." So, now I have created your account, and the next thing I know need to do this confirm your email address mail. So I'm going to use yours by phone. I will press by email with the inscription " Confirm your email address Shapeshift" and I'll go for link in it. You will be redirected to page from message that your email address successfully confirmed. As only you will see it , you can update page and see, that your email Address confirmed. So, I'll click " API keys", and before I I can set this up. we need to adjust two-factor authentication. So I I will press " Security settings ". I will use it. with your Google app Authenticator. So I will open and scan the QR- code. And from there I can enter the code. Therefore, now you can to see that mine Authenticator app is on, so this is configured. So, I I can go back to API keys. Therefore, from here I will click " Generate key. Now we are here and you you can copy your ID consumer and save it. Copy yours identifier consumer and save it. Very it is important to keep this in a safe place, because you are not you can see this again after closing. So, once you do this save, you can press "I" copied yours identifier consumer". That's all. So, I'm handing you over. Nick, who will conduct you through the rest of this course. Okay, so in this one part of the video I I will show you how. create an account Massive recording so you could generate the Massive API key that we then we will use later in the video for data acquisition stock market with Massive API. The first thing you need to do this go to massive.com, and on their main page at the top right corner you notice that they have this blue button " create an account recording". So you will need press it now. After you register, there is several different registration methods. You can register via GitHub via Google or by using email and password. We will use email. I I think that this sends an email letter from confirmation on my address email. That's right. So, let's let's find it now. It seems that the link for confirmation opened in a new browser, so I I'll drag it here. Okay, and here we are here. So, Massive is quite simple in use. Here many settings, but in reality all that we need this opportunity to get the key is right here. So we click on this. It looks like we already have it. API key for default. You you want to take it and use in in your project in future. So I I'm going to return. this is so that no one who watch the video, no could it use. But, yes, here's what you need need to be done to get your API key Massive. And make sure that you saved it for then, because we we will use this is in the project that we we create. Good, Next we need create an account recording in Alpaca. So, Alpaca —this is, uh, stock brokerage company. They have a public stock brokerage company that can register everyone, but what is important for this video, they have there are paper trading bills. So, you you will be able to follow according to this educational manual, in fact without replenishing brokerage account and not carrying out no bidding, using real money. Therefore, the first thing you need to do need to do this go to alpaca.markets. This is not alpaca.com. Believe me, I was there. It real website, related to alpacas. So, when you are on alpaca.markets, at the top right corner you you will see a button registration. They have two different APIs: trading API and Broker API. You will need register in trading API. As only you here you will find yourself, system just collect some information about you. So, my name is, oh, need a stronger one password. Steeply. How are you? Did you hear about us? Let's say YouTube, because, probably many of you are watching this on YouTube. So, we click " register". Oh, I need choose a country from this dropout list, I think. Interesting. Maybe they do not support Canada, so I'm a little I'll cheat and say that I from the USA. Register . Okay, I got it. confirmation email, like and before, so let's Let's find it. That's it. It says: "Therefore," it opened in another window, but I I'll move it here, so that you can do this see. So, there It is written that your email address confirmed. Now you can enter. We let's move on login page and Let's go in. And then I I'll press this little "remember" field me". Okay, let's go. let's continue. Good, so we are on the main on the Alpaca page. Here immediately worth it pay attention to this blue message. You you will see what is there It is written: "You do you trade paper prices, and real money is not are used." This was important for us during creation this video because we wanted everyone could participate, if he wants, regardless of your financial condition. Em if you want go to real trade, you can press this drop-down menu in upper left corner and go from paper trade on an individual basis trade. You can to see that this is fresh paper trading the account has false balance in amount of 100,000 dollars. So, that's where we are we will base our project. Hmm, there are others. interesting things in interface. You can see your positions, your orders, your activity, own balance sheets and something else. You you can see that everything it is closed because the system wants me to configured the application for authentication. So I'll do it now. Actually, I'll do it. off-screen so as not to to worry about hiding their credentials or something like that. But You guys seem to will need customize yours authenticator to really take participation in this video. If you have never before they didn't do this, there are many different programs that you can you use for this, such as Microsoft Authenticator, Google Authenticator, Authy, Bitwarden. Majority programs for password management, what kind of people use today, have this built-in function like -from 1Password or LastPass. So, make sure what did you set up your authenticator, before moving on to the next step. Otherwise we we can delve into project. Okay, for outside the screen I set up your addition- authenticator and I just would like to to briefly introduce you with the Alpaca interface . We will be here long enough. long, until we are developing our project because we we are going to create application that will allow us place deals. Then we will move on to Alpaca interface and let's look here to to make sure that we we place the necessary agreements. So, this is home page. You get balance your account, and then yours historical balance. You you can see that because it is new paper trading account, and we never not really placed any agreements or something like that , the balance is constant with sometimes at the level of 100,000 dollars. Other main places we will be to search, are located in the sidebar here. So, first this was closed. I opened submenu account. AND then you can to see yours positions. Therefore, obviously we don't have positions. You can see your orders. Obviously, we don't have warrants. Activity, balances, and then some options configurations. So, in we are on fractional trade and short positions. AND then we have pricing and trade support third party options equal. So, here a lot of useful things. We we will see more about this is when the project will be built during the rest of this video. We we are going to start creating our first project. AND before we let's delve deeper and let's start writing code, I I would just like to to walk and give you a kind of idea about how the project will look like after him completion. So, this is information panel. And the fact that we are here we create, -this trading system investing in momentum, which allows you to take a whole range of shares, rank them by 12- lunar momentum, that is, in essence, for by changing their price for the last 12 months. You rank all stocks in the universe behind this. AND there are many academic sources information about the idea, what if you buy stocks with the highest momentum and potentially selling stocks with the lowest momentum, you will receive extremely high profit. This the strategy we we develop, inspired by the book " Quantitative Impulse" Jack Vogel and Wes Gray. They manage by a quantitative firm investing in the USA, which implements many of these quantitative strategies , but it's kind of inspiration for this. So, I'll show you all different things that can to do this little one software application, and then we step by step Let's consider step by step. him and we will create everything it. So, this app in the main divided into four sections. Do you have toolbar, Do you have indicators? momentum. So, here no data yet. We will consider this for a second. And then there is trading signals on based on these momentum indicators . Finally, there is a section for management your portfolios. So, this is the part, where will we be use SnapTrade to actually connect this addition to your brokerage account for the implementation bidding and monitoring your balance sheets. So, yes. First of all, let's let's enter some data in this thing. You will need press this button in upper right forged, to count momentum. Uh, and this just a hint: "You want to list momentum estimates for all shares? This can to take a few minutes." Let's Let's do it. And then we we get a hint, that momentum estimates successfully listed for 50 shares. You you'll see when we do it actually create, but we are tough encoded a small a universe of 50 stocks, which consists of Investly universe for this application. Um, okay, so here's what we we are considering. You see, we have two here main tables: 10 best promotions momentum and 10 worst stocks momentum. Um, 10 the best ones are a bunch... So, uh, it's March. 2026. Top 10- this is, in fact, a pile artificial intelligence shares intelligence and technological companies, because lately we we are experiencing a great artificial boom intelligence. So, Google and AMD, Intel, Nvidia, Tesla, etc. . I'm a little surprised, I see promotions here. blue chips, such like Johnson & Johnson. But this one impulse is, in essence, their 12-month price list yield. So, this is decimal. You you can also express it in percentage. This means that Intel grew by 98.5% over last year, etc. AND then, similarly, in We have 10 shares with the lowest indicator impulse. So, United Health fell by 45% the last 12 months. Adobe fell significantly. Uh, a lot of these things are very fell, I think it's possible to say, because of fears before artificial intelligence, etc. Therefore , SAS, etc. Uh, Salesforce, Adobe is good examples of this. AND then you can see that we don't have active portfolios and no events rebalancing. AND then the only thing I don't I remembered, this is what there is some on top information about, uh, average momentum and median impulse, e- e, and also about our briefcase, etc. Therefore, if you want to see, uh, impulse indicators for the entire portfolio or rather, for the whole systems, you can go to tab impulse indicators, scroll down, you you can see them everyone is in the ranking. Top 10 –all green, bottom 10 –red, and theoretically one of strategies that you could be applied in this universe, is open a long top 10 position and open a short position in the bottom 10. Hmm, yes. There is also conversion button, if you come back tomorrow and you need fresh data, you can to use it. AND the last one is the page trading signals. So, this is where you are you can get trading recommendations regarding all shares in the universe. But first than we can do this to do, we need connect the portfolio. You can see, if we try do it now, uh, it will say: "You want to generate new trading signals based on current momentum data? This may take a few minutes. You you will get an error, because we don't have active portfolios. Let's fix this, by connecting account via SnapTrade. Therefore, press the button « Portfolios" on the left. Click "Create" your first briefcase ". This will guide us. through the OAuth process to connect this program to our paper account Alpaca with the help of SnapTrade. So, we let's call this portfolio "Momentum Portfolio" 2026". And ours investment the strategy is to in order to buy 10 best promotions momentum. Good. So, this is integration. live trading. There is here a few warnings. THERE ARE several supported brokerage offices. It is now limited. only Alpaca for this manual. And then we click "Secure" connection via SnapTrade. Click here. It appeared on to my friend monitor, but we we get a pop-up a window that looks like this. Allow I have to do it. a little bigger. Now I already...I entered the your account Alpaca recording on this computer, therefore, probably, I have saved token device in Alpaca, and this means that he, probably not will ask me enter your name here user or password, but usually it is being done. So, this is still Snap Trade, he just telling to you, what is here? is happening. We we are going to finish process authentication by using Alpaca paper. And now we are on the web- on the Alpaca website. So, I I think if you did this because haven't been in for a long time system, he first will ask you to enter your username and password, then redirect you to this page. Therefore, which paper Alpaca account Do you want to connect? Well, let's go. Let's connect this one. Paper accounting record—the only one that There are us. We press " allow", and this will return us first to our app after connection. Boom. Connection completed. So, this is opened in a new the window that I am in now I will close. And then, if I will refresh the page. briefcases here, you you can see our momentum portfolio, which we just did connected. Perfectly. Now we can return to shopping page signals and actually to make...some deals. So, we press this green button in upper right carved with the inscription " generate signals". The prompt says " generate new ones trading signals on based on current momentum data". This may take a few minutes." Yes. So, we generated there are 10 signals here. And this one the system is configured so that the data is in the mode real time may be a little expensive, and they don't included in free plan, which we have with Massive. Therefore, I think, usually you want weigh the stock with with the highest momentum slightly higher than the stock with the 10th largest momentum, and make weighted average value. We did it's a little easier. We just getting together invest 100 dollars in each of 10 best promotions momentum. So, in each column has "buy" button. You click "buy", and it says:" Okay, we're going. buy Walmart. Size deal is 100 dollars ". Accurate the number of shares will be calculated during execution from using current market prices. And this is actually takes place on on the Alpaca side, not on the us. So, we we are going to him perform. Boom. Therefore, our purchase order Walmart for $100 was successfully submitted to the broker. This is great. Theoretically you could to walk and perform all these orders, but instead of this let's just let's go to Alpaca and we will make sure that this the deal is posted right. Good, I need to enter here is the password. So I I'll just do it in another window. I I'll be back in a second. Perfectly. So, I am now entered Alpaca. You you can see, uh, that is, it's all paper trade. Uh, if you go to account and warrants, we must see the warrant for I'll buy Walmart for 100 dollars. This is a warrant, which we just did placed. If we Let's open it, you you will be able to see warrant. Now, in Alpaca interface some are missing elements regarding conditional agreements. So, you you can see that in it has no limit prices, no stop price, um, purchases, etc. And you like: "Oh, where is 100 dollars? "It's easy to miss, it right here. But this the deal we just made placed for 100 dollars at Walmart. AND in a similar way you could easily buy all the others from the top 10 and create your own own portfolio impulse from zero, using software the provision that we we are going to create in this project. Therefore, here is your little one preview project. Stand up, Take a walk, a little. take a break, make some coffee and then come back. We we are going to delve deeper and create this thing from zero now. Good. Now I will show you how customize your local environment for starters, as well as I will explain mine. recording philosophy this so that you can to learn as much as possible more while you watch behind this. This repository that is behind at nickmccollum/ algorithmictrading, is a place, where I thought a lot about these projects, created them in parts, tested them and it can to be final source of truth about of how it should be look like a project. In the future we we will work on thereby repository, but with added dash entry. So, this is empty. repository. I I'm going to clone. its in my local development environment, and we will collect it in parts. I I am going to record. all the mistakes that I made I do, and show you how I fix them . You will see the real commit history in repository you are using you will be able to to use to see where I am I decide to commit. things that commit message create etc. And, by essentially, this repository will serve as a step-by-step review for actual recording, which one are we going to to do, uh, within the framework this video. So, uh, what do you want to do locally, copy this is, uh, sorry, first create your own repository so that you could do it independently. Copy this, uh, this SSH address, and then run get clone, and then insert it. Uh, you will have an empty repository locally which you can open and to start. Good, So, I opened... Cursor to new repository that we just created, which is called algorithmic trade...Now we need to be configured our catalog project. We need customize requirements Python and getting started initial formation project framework. Therefore , the first thing we'll do, this will create a new one folder named " Project one. "And then "inside" the Project one "we will create" file named requirements.txt. In this files are stored all your dependencies Python. If you have switched from the land of TypeScript or Node.js, that's about it same as package.json file . When you install third-party dependencies, you write them down here. So, I open your integrated terminal. We let's move on to catalog" Project one ". And then, the first thing we we want to add to of this requirements file, this is Django. Django— most popular web Python framework. He allows easy process HTTP requests. This allows integrate with databases, such as like PostgreSQL, and it will be the basis of what we we use for creating this project. So, uh, we we are going install this in our local ee environment. Before everything, uh, we we are going use package manager under called UV. Uh, so we we are going to perform UV pip install-r requirements .txt. Now, I think it's us asks: uh, he says, file not found requirements.txt. What do we have? Hmm. Why doesn't he see? ? Oh, it is located out of catalog project. Let's let's move it there. Good, Let's move this. Good , now we are going run UV pip install -r requirements.txt. This is beautiful. request. Uh, let me. I have to do it. a little bigger. It good request. He says not found virtual environment, run UV VNV to create an environment. So this is, uh, UV VNV, uh, creation virtual environment simply means that everyone dependencies that we we establish, will be isolated from this project. So, we let's create a virtual environment, then we will establish Python dependency. You you can see that Django, Asgi ref and SQL parse installed. These two, obviously, there must be Django dependencies. Now we can create a framework for our project. Django comes with built-in command called start project, which allows you to give the project name, and then Django will review and will create all the different files needed for project launch. I I'll show you how. looks. Team Django-admin start project, a then you need Give the project a name. You saw from the description project, what is this project software provision for momentum trading- rating, so we let's call this project momentum trader. I am right. wrote? Momentum trader. Yes . Okay, you'll see. on the sidebar, boom, a bunch of things just now created. I actually I will move the created things on one level above so that they are in project one catalog. AND now we can start our server Django locally and to see how he is looks. Excuse me, I moved them to start of the repository. I want them to be within the project one. That's it. OK, now we can start our server Django. So, the command for this-Python manage.py uh run server. Cool. Therefore, a few things. On- first, you can see that the server works, and every time we make any changes to our code base, for example, if we'll just add here a little space, and then we will save it, you will see that server immediately will reboot. Okay, so you can to see that this is the first once the server started, and then This was the second time. when the server started. This is the first. Secondly, you can see what Django warns us that in there are 18 of us unused migration files. It means that migration Django means change database schemas, on which yours works Django project. So, if you add a column, this creates migration Django. If you delete the table, this creates a Django migration. Whenever you make changes to the database data, software software automatically creates Django migration, and, obviously, currently in Django built-in 18 migrations. To us need to apply them to our local databases. Therefore, the command for this is python manage.py migrate. This is a list of all the migrations that we just applied to our database. So, here we go again let's start our server, and this warning there will be no more. Therefore, python manage.py runserver. Okay, you see that warning about migration more no. So, we can visit our server and see how he looks. Let's let's open it in another window. I I'll drag it here. Perfectly. Therefore, installation completed successfully. Congratulations. It there will be a web page, which in the end will turn into Momentum Trading app, which I was showing you earlier. Okay, so, now we will create several Django applications. There is a difference in the world of Django between the project that we just created, and an application that is like isolated part project. So, if think, for example, if you create DoorDash, you can have one project under called the DoorDash app, and there is, sorry, a project DoorDash, I have to say. AND inside it there can be two different applications for driver management and buyers, for example, in this project we will create two applications under called trading and portfolio, to accommodate different things related to project. Django, uh, has built-in functionality for automatic loading new application inside your project. Therefore, er, the team is very similar to the one we were doing for launch the entire project. You Do you remember how we were then? started the Django admin project momentum trader. Uh, team to launch the application- start app. We will launch portfolio. You will see that here automatically a heap is generated files. And then we let's do the same for trading. Okay, you see, what is the app for trade and application for portfolio created. The last thing we need to do, this is uh, register these applications in the project Django. So, we created all files for everyone application, but for now the project is not really knows that these files exist. So he doesn't knows how to read them or refer to them in any way. Therefore, in every Django project is this extremely the important file settings.py. And this is essentially the file here , obviously, was automatically created by Django during project download . He can to turn into a very long wall configuration if you You don't know what you're doing. So we'll simplify it. We just need edit one the list here, which is called installed applications, and we just need add two attachments, which we just created . So, we added trading and portfolio. Okay, we let's keep this. Hmm, this is approximately in a smart place to we could commit this and send to GitHub. One thing we we want to do before this is to add a file .gitignore. So this is the file configuration if you not familiar, which one Git tells you which ignore files under GitHub submission time . I don't want to commit. this SQLite file, because it is a base data, and its trace to store only locally. So, we add star.sqlite 3, and you you will see that now he must be unallocated, and this means that he is not will be prepared for commit. Perfectly. Okay, so I I am going to do ` get_add`. We will prepare all for the commit. And we we are going commit this to GitHub. I will say `initial' project download and registration Django application. Perfectly. So, you you can see summary of all changes here. We added 25 files, added 23 lines of code and all that will now be on GitHub. Okay, so now we let's move on to the section this project, where we let's start modeling data in our database data for our project algorithmic trade. Hmm, you see, I opened trading/models.py, and This is where we will create all our base models data. Therefore, specifically, we let's create the following: stock. Um, for now I I'll just add it here. pass operators. We let's create another one model called um price data. You can to see that all these Python classes inherited from Django model class, which essentially means that his need to be compared with database table. Um, and then we momentum score needed, trading signal and rebalance event. Um, momentum score, trading signal and rebalance event. Okay, this is, um, each of these classes corresponds database tables. AND then in these classes we need actually indicate which um fields exist in this tables, setting attributes for the class. For example, if you have there's a stock ticker, um, and this character field, you, probably will do something like that. I am now I will get the exact names. fields um. Okay, so, regarding shares, we you will need uh ticker. We will need ticker. I don't know what. gave me this autocomplete. Uh, we will need name. To us a sector will be needed. Sector. Uh, us market will be needed capitalization. To us will need active indicator. So, this is will allow us disable the action in in the future if We don't need it. We will need a date. creation and date renewal. Good. So, for each of these fields to us type must be specified fields, and Django has built-in classes for each of them. Therefore, the ticker will be character field. And I I'll comment on them for now. so that they don't give out errors in the file. Therefore, the ticker will be character field. Its maximum the length will be 10. It it will be unique that equals truth so that we didn't have duplicate tickers in database. And we we are going to add before that base index data so that the search is fast. The name will be similar. This is symbolic. field. Its maximum length, let's say 255. And, uh, we let him be empty during creation. Sector ( Sector) will also be character field. Its maximum the length will be 100. And it will also be blank is true. Market Market cap will be great integer field. And it will be null- permissible. And we let's also let him to be empty. For those who are not familiar, null is a restriction on database levels, and then blank allows you on different levels in Django too install this value to false. Therefore, uh, Django has a built-in panel administrator, where are you you can log in and view different database connections. And setting blank equals true allows you actually send empty values ​​in these forms. « Active, how are you? can you imagine, will be a logical field. And we are going set for him value for default "true", so that when you create one of them, it virtually automatically became active. Its will not be necessary activate manually later. "Created in" will be a date field and time. And then, uh, Django has this built-in assistant named auto_now_add. And this means, what if these objects are recorded in the database data, Django automatically sets their time creation, uh, without necessity to indicate it manually. So, we let's say that auto_now_add equals "true". And, uh, this shouldn't be capital letter. Here Yes. And then, " updated in" will be very similar to "created in" , except that instead of auto_now_add it will be just auto_now. Okay, this is it. first database table data that we we are going to create. To actually create a table databases in the database data, you need generate file Django migrations, and then move your base data. So, uh, let's do this. Team for creating migration Django-python manage.py makemigrations. So, as you can see, this is creates three new bases data or, sorry, four five. My counting today not successful. Five new database tables, one for each, which we just created here. And when we we migrate, you will see that the initial migration was applied, and all these tables now exist in our database SQL ID. So, I just I'll copy, uh, some configurations for other tables to to start. So, the data about prices will have these fields. Uh, they have foreign key for shares. They have date field. They have opening price, maximum, minimum, closure and volume, adjusted price closure and created in. Momentum score has the following fields: Promotion, date calculation, momentum score, rank, quintile, upper quintile, beginning of the period, end of period and created in Last, which one are we going to to create, called a trading signal. This one is a little more complicated, because he has value enumeration. AND some base indices data. So, I'll insert this is here. We can do it. review. Therefore, trading signal includes this list types of signals. And, by essentially, what is it for? is used, you you can see link to it here. This type of signal has limited choice, which means that any what is the meaning, written in this line database, there should be one of these three. AND they are set up here as two tuples, so that the first meaning is what actually is recorded in the database data, and the second the meaning is that will be displayed in in a readable form person, in different parts of the interior Django codebase. So, here's what it is. THERE ARE -eh, if you walk by for the rest of the model, it has a foreign key for shares, date signal, signal type, foreign key for momentum estimates, target quantity, target value, field of reason, is being done, is performed on that date creation. Then in you have this metafield that allows you to add additional configuration to database tables in Django. So, she has database table, we specially wrote the name tables for her. Uh, it has order by default when you are extracting data from database, and then she has these two database indexes. The last, uh, the last database table in trading application is called an event rebalancing. Therefore, if we add this here, uh, these are all the fields, which she has. Date, total number analyzed shares generated buy signals, generated signals sale. So, these are the goals numbers, this is the number how much signals of each type was created. Total cost portfolio, status implementation. This is also has a choice limitation. Uh, a message about error, then date creation and date completion. So, what we need to do now, this regenerate our migration files. However , uh, we can't to do it, uh, again, because we contributed too many important things changes to these tables database for this goals. So, uh, what am I I'm going to do this. just delete this one database. We we are going recycle it. Uh, here. And we must have the opportunity to perform, uh, deletion during this initial migration. Never do this in work application, but this is the fastest way to fix this here. We will fulfill migrations python manage.py make. And then we will execute python manage.py migrate. OK, perfectly. Now everything looks good. Ahem, let's do it again Let's start our server. While I'm thinking about it, you sometimes see that I I run pm as alias for python manage.py. So, it's simple. It becomes like this when I I'm launching it. Me just a little faster to write because I I do this all the time. So, we execute pm run server and look at application, and everything is still looks great. Therefore , uh, after we we did it, we can go to our another Django application and create several there database tables. Okay, now let's go. let's create a few data models for our portfolio- application. First model called a portfolio. We let's do the same thing as last time, just let's create them all, and then we will fill in later. Next is called position, that is, she represents something in your brokerage account you are actually own. Next-trade. So, this is represents an agreement, which you are sending to the broker to change positions in your portfolio. And the last one- this is an indicator productivity. Therefore, like last time, I I'll just copy everything. indicators, and we we can them to discuss. So, here, in your briefcase, you have name, description. They quite simple. Initial cash funds and current cash, total cost. It all decimal fields, because they intended for currency representation. Identifier SnapTrade user and identifier account SnapTrade. So, these briefcases will be specifically related to SnapTrade partner. AND then the secret SnapTrade user will be a field, security-related which we need save. Active, created by and updated about. Many similar things to some of our others data models. We we are also going place here metaclass. So, we we are going to provide this is a certain table database called briefcases, certain order. Next data model is called a position position. So, she has a foreign key to the portfolio you just created here. She also has foreign key to shares that are in trading model. You you will see what is here wavy line. It because this name is not defined. So, there are two ways to fix this. You can import it here so: with trading.models import stock. That will be enough. Or you can pass it on as line and specify the name Django applications and model. That's what I'm here for. I decide to do it. We just use trading.stock, and that's it will fix it. So, for Do you have any positions? number, average cost, current price, current value, unrealized profit/loss, unrealized profit/loss in percentage, date last update and creation. We also add metaclass to this database models. So, we will give this database tables special name positions. We will do this, so that the portfolio and the stock could only have one position. So, this is unique constraint together. And then we let's put this in order by default, where it will be sorted by current decrease value. So, if you will pull them out database, then your default position with the largest current value will be displayed above. Let's let's move on to the model trade. This option starts with several lists for selection constraints, as we discussed earlier. So, uh, in we have types of agreements and status options. Uh, we have an external key to the briefcase, foreign key to shares. We will do it here. the same as before. THERE ARE -uh, we have a type of agreement, which, uh, depends from the list of types agreements. So, that's essentially it. does not depend on is this a purchase agreement, or sale. Then in we have quantity, price, number of completed, executed price, order value, status. It depends. from the list status options here. So, it is possible status options for agreements: pending, submitted, partially completed done, canceled or rejected. Then we have an external order identifier , identifier SnapTrade orders, message about commission error, submitted at, executed at, created by Fr. I just I'll take a minute, uh, explaining the difference between the external identifier warrants and identifier SnapTrade orders. When you send the deal via SnapTrade to Alpaca, Alpaca assigns her order identifier . This is what assigned in the field external identifier warrant here. And then SnapTrade also assigns him an identifier warrants, and we we keep both in database on our side. The reason why we called it external identifier warrants, not Alpaca, is that you could use that modeling itself data for trading also in another broker. So, perhaps, could you take this system, split it and set it up so that so that she can bargain both on Alpaca and on Interactive Brokers. Both identifiers orders of these brokers will be stored in this field external identifier warrants. So, let's move on. We also add metaclass to this data models. We have database table with the name of the auction, sorted by descending, created in . So, when you have them pull out the last ones will be on top. AND then two indices database, index unification by briefcase and status, and then index of association by status and created in. So, it's simple. question productivity. Latest base model data in this application is called a metric productivity. I I'm going to add all fields here, and we will Let's consider. So, in we have a foreign key for the portfolio, we have date, general value, monetary cost, cost positions, daily income, total income , total number deals, winning deals, unprofitable transactions and created by Fr. And then, this won't surprise you at this stage, we we are going to add metaclass. So, we we are going assign to this database table indicators efficiency, unique constraint for the common use on portfolio and date. So, essentially, you don't you can have an indicator efficiency twice in the same day for a specific portfolio. Of course? And then, order by default here will be in descending order date, and there is one index databases. So, this is there was a lot data modeling. The last thing we need need to do this create migration Django to do all this applied. Therefore, Do you remember that? the command for this is python manage.py make migrations. It will create a file. Therefore, you see that model created briefcase, model indicators efficiency model positions and model trade. This is exactly what what did we expect. AND then we can apply this file migration by using python manage.py migrate. And boom, that's all for our modeling data. Now we we can commit this. So, I'm going to add all our indexed files . We will see that indexed if you will run get status. There should be a whole a bunch of good files. And then Oh, actually, if you look at these are, uh, some of these things we don't we want index. Pycache files are required add to our get ignore. So let's Let's do it now. And, uh- Well, I think we we want to do this . Pycache. And then, if I I'll come here and get it. all things from Pycache files . This file. This file. That's it. Hmm. I think which is actually better way to do it, I I think GitHub has Uh, yes, that's what we need necessary. So, GitHub has a repository under called gitignore, and they provide, uh, templates gitignore by default for different types software projects. So, this is gitignore for default Python, and I'll just add it. to all content our gitignore below, seems. So, now, if we move on to our control versions, you will see, that we will reject this change and add ours gitignore change. All files pycache now are excluded. Therefore, if we get status, yes, just that, that we edited. Um, so we'll do commit and, say, source files data modeling and migration. Perfectly. Submit this to GitHub. Okay, now we let's set up our panel Django administrator, which will help us to manage everyone different models the data we just created. The first thing that we need to do for this, this create superuser for our application, who can actually enter administrator Django panel. Therefore, the command for this is python manage.py create super uh create superuser. So, this is will offer us just pass on some information. So, the name The user will be Nick. Um, address email not it matters, so I just enter nick@test.com. I will enter the password here. AND I will confirm later. your password. Steeply. So, now we can open administrator Django panel, which is one of mine favorite parts of the web Django framework. Therefore, we will run python manage.py runserver. She just launches our standard server developments. If you open this in browser, move this to screen so you can do this to see, and then, uh, just add {slash} admin at the end of, uh, this URLs, enter the credentials you just sent to Django, and boom, you're in administrator Django panels. Therefore, now here for real little information, except for some information about groups and users. It what we want change. We want add all models the data we just created, to administrator Django panels. I am now I'll show you how. make. You will see, that in two applications, which we created, application for portfolio and applications for trade, each of This file admin.py has them. And we want edit it like this, so that more of our data models were reflected in this administrative Django panels. Therefore, Let's start with the portfolio. We want to create four classes. Administration portfolio. In essence, we let's create one class for each created we data models. Administration portfolio, and this has to inherit from admin.modeladmin. And then you Do you want to decorate this? using admin.register, and then Django models, which you are trying register. Therefore, if you keep this, we will get this error on our development server, which says that the portfolio is not defined, therefore let's import this is now. From portfolio.models import portfolio. Save this, and our the development server has boot. If we will move on to administrative panels, we now we can see it. THERE ARE- uh, where did it go? Here it is. Okay, now. you can see what is administration portfolio. Uh, and here there is nothing, because ours the database is empty, but you can add portfolio, review yours portfolio, list them, etc. Uh, and just like you do...Excuse me, yes just like you do it, you can add very similar administrators for the other three models data in this project . I will show you what I am. I mean. Therefore, if you just copy this three times, and then in the first in case you change portfolio per position, in the second portfolio for trade, and then in third-portfolio on the metric productivity. Uh, you can see that in our file has three mistakes because we are still did not import them into this file. So let's Let's change this. Position, trade and metrics productivity. Okay, now if we let's move on to Django administrator, eh -hey, he's asking me log in again. I I'll move this to the bottom of the screen. which I am writing down. Okay, you can. see all four Django models. Therefore, again, here for now that there is nothing, therefore that our database empty, but we we want to check this is later. Hmm, the only thing, What else I would add is that what can be done in this class to convey a lot really powerful functions to make its customizable. For example, when you for the first time you will go to portfolio page in administrative Django panels, you you will see a list of all your portfolios, and you can you specify which fields actually will be displayed in this list, passing the attribute list display, like this. Similarly, you can filter and search on this page, page portfolio list. AND these two attributes determine what you are after filter and by what you can search. AND then you can too specify some fields read-only, so people could not enter and edit them. So, you indicate read-only fields like a list, like this. I would said, like a motorcade, here it is Yes. I just... I'm going to improve. the rest of our models data, like this. And this our new administrative page. So, we let's move on to trading application , and I will also copy the desired type there final version this page. And we we can go to beginning of the actual integration with one of data providers in this project. Perfectly. So, we let's just spend a little check working capacity in Django admins. Let's see how it goes. looks. So, you you can see that each of us Django applications have your own section. There is a portfolio section and trade section. If you want to see only one section, just click on him, and he will show only this section. AND then all our different database models registered here. So, this is exactly what we we want. We can commit this now. We'll do, uh, we get, uh, period . Oh, there's more" Why this one Is the guy still here? "I I think we just we want to take it away and move. AND then we will commit it. Configuration Django administrator. Steeply. Download this on GitHub. And now we we can go to integration with data provider Massive. Okay, now we let's move on to creating our integration with Massive, which is data provider stock market, which one will we be use for obtaining data about stock prices for of this Momentum project. Usually when you integrate with third-party API or system, this new integration placed in a folder called services. Therefore, you will see that I already set up in trading application a directory called services. And inside this catalog we we will place a new one a file called massive client.py. Now make sure you added this file init.py, so that other Python code in this codebase could read it. Inside this we will add a new file a class called massive API client. And we will begin very simple, simple specifying the init method, which will accept self. He will accept the key. API, which can be either optional line, that is, it will be a string object that by default has value none. And then we will also indicate number of requests per minute to am, which is whole number and by default equals five. Therefore, this is because Massive has speed limit. On the free you can level send only five requests per minute, and we must build this system in such a way that to follow this restriction speed so that it doesn't disrupted work our program. Hmm. The first thing we need to do this to set up, uh, some logic for reading our API key. So, I I'll paste it from here. Uh-huh , and I'm going to add some are missing imports here. So, this is V1 of the Massive API client. I I am going to explain that does all this. So, uh- uh, this REST client comes with the Massive Python package, which we need to add to requirements.txt. So, we add it, and then we are launching ours again pip install. We, uh, sorry, we want to be in the catalog project one. And then we perform UV pip install -r requirements.txt. Perfectly. So, this is brought us Massive One, which we indicated, and then some dependencies next to him. So, urllib, websockets and certified. Hmm. Next, what we want to do, is to start creating big bulky a method called fetch stock data. And this will allow we receive data about prices from massive APIs. It looks like this. Oh, I clearly inserted the wrong thing need. Get data about stocks. That's it. So, what is missing here? some imports. To us need to import list and dict. So, both they exist in the package typing. That's it. Good, let's see, What does this, uh, take? this fetch stock method, or, sorry, fetch stock method data that we create. So, he accepts ticker, start date, end date, multiplier, adjusted limit period of time, cache usage, maximum number of attempts and repeat delay. There a lot of things. Therefore, let's start with the very simple. We want return aggregated data about stocks. It, probably the simplest way to do it. We let's start with the list empty eggs, and then we sort through massive list of eggs client and add them all like dictionaries to this list, first than to return them from functions. There is a bunch here. of unspecified things, which we need to fix. Therefore, The first is this one. period of time or, sorry, date-time is undefined variable . We just need import it. It built-in library Python. From date-time import date-time. The following is the key cache. Um, and uh, we We are implementing it now. So, every time we send an API request to Massive because it has strict restrictions speed five requests per minute, we never want send duplicates requests. Because of this we we will cache requests during their sending. And if we we are going realize caching, us must be specified cache key. This is how we We will do it. Every time, when we send ticker request from a specific start date and completion date, we will keep it's like a cache key, just adding it all up together like this. Then we can update this new method data acquisition shares to ask this cache key is like this. Good. The last thing we need it is necessary to specify that logger. Hmm, that's very universal logger Python, which can realize practically in any which Python project. He looks like this. Okay, next thing we need to do, is to find a way is protest. Hmm, good way fast sort server things in Django projects- to use it the so-called team Django management. Control command Django is, in essence, just a CLI that you you can run it, and which automatically will read the whole the last code from your codebase and something will do. Therefore, let's set up one. Um, teams Django management always are in the folder under the name management/commands . So, we will create this folder. We will create init.py file. Hmm, this is need to be placed in command. Yes, no, it is in the right place. Um, Okay, one more thing we need need to do this easy to set up empty command control from which we we can perform iterations. So, here we are Let's create a new file. It will be called pull massive data.py. And I inserted this. I just asked by ChatGPT write to me empty command Django management. Therefore, you run them like this just like we launched all other Django commands in this project. You run python manage.py, and then the team name management. So, in in this case you would executed python manage.py pulling massive data. If you look what this is does, he has some arguments. Uh, we are actually now let's delete these arguments, because they we don't need it. Uh, and we will also remove help command, line help uh . I expect that this just say "hello" world "when we do this let's start. Let's see. Perfectly. So, that's right. configured. We can we update this control command, so that it actually pulled out some data from Massive. Therefore, let's do from trading.services.massiveclient import Massive API client. Uh, yeah then here we will say, that client equals Massive API client. And then We will take the client out. Good. Let's see what now it will happen. Settings does not have the Massive attribute API key. So, if you Look here, I said that we can or pass the API key as an argument for this service, or, if it null, then it will try read it from our settings Django. So, our file settings.py if you have it open and manage F here for Massive, there there is nothing, and this because we haven't seen it yet set up. What are we Let's do it now, okay? let's set up, um, we let's configure, um, the package Python, which will allow it is easy for us to read environment variables. This package It's called Python decouple. We will add it to requirements.txt. Python-decouple. We let's reinstall our project requirements.uv pip install -r requirements.txt. Steeply. So, Python decouple now installed. Then we need configure example environment variable environment. So, um, this is will look like this. .env.example. And the first the record that we we are going to introduce, this massive API key. Now, um, then that we establish this variable, uh, in this example file environment, doesn't actually mean that our Django project is already reads it. To us need to be entered changes to our file settings so that, um, force Django project read this. I I'll show you what I have. in mind. So, if you will go to settings.py is closer to beginning, we will add this import. From decouple import config. This package decouple is the one we just installed in our file requirements.txt. Then, near the end, you you can add this. Massive API key equals config, and then you are just passing on variable name environment, and everything ready for the race. Now that we we are launching this control command, she must have another mistake. Interesting. She has no other errors. Um, exchange these services. I I think it's easy for us need to copy .env.example in regular .env file. Let's let's try this now. Steeply. So, we have configured massive API client, massive API client object. Which one is it now? uses this API key. Now, obviously this API key won't work because it just random line. So I I will return to my massive portal. Now, obviously, this integration is not will work with this API key, hard encoded here because it's just random line of text. First of all, I need to insert my actual API key. So let's do it. this is now. Let's insert its. Then we want update our team control so that it actually pulled out some data from stocks. So let's we'll do, uh, fetch stock data. We'll try Apple, and I am missing here. some arguments, but Python will tell us, What exactly don't I like? enough. So, the date start and date completion. Let's try 2026 05 10 and 2026 05 15. Let's see what it is will give us. Good, now we get error that says that our Mass API client does not have an attribute cache , and that's because I copied and pasted some things, not after reading them carefully enough. So what do we want? do in the init method, is to add a simple cache in memory, which It looks like this. Let's see what will happen. Good, it seems like this potentially It worked. Uh, us print operator is missing in the control team Django. So, let's say that this is the result. Let's see which one result. And then I I'll put it there too. a stopping point to then it was possible play with the data. Okay, it looks like we received some data from Massive API. This is important landmark. Our integration officially, hmm, it works. So, the next thing we we want to do this add a little logic before that, so that speed limit really followed . And for this we we are going to make a bunch of changes to this Massive client. First, what we want to do, is to add an attribute to init method called" queries per minute. This will look like this Yes. Everything we do, -it's nothing special . He just takes, uh, this argument from the method init and assigns it as a class attribute. Then we want add, uh, method speed limit, which is called, when we send him with ours requests. He It looks like this. So, uh, what's missing here some imports that causes errors, so we are going import package Python time. And let's let's consider what this is does. So, he gets the current time. He is looking for all of us. query times that older than 1 minute. AND if it is longer than number of requests per a minute than stated, he goes into mode sleep, that's just means he is waiting a certain amount seconds. Uh, and then he adds more data by query time . So, uh, obviously What do you notice? doing this, this is what time of requests not determined. We also we are going to add this attribute in the method init. It will be simple. a list of all the different ones, hmm, this is a list of hours marks of each once when we sent outgoing request to Massive API. Good . So what can we do? do it now, this update this method, so that he has a bunch handlers for working with this. So, I I'll just paste it here. the method needed, and we we can walk along new logic. So, this is new method, and I some are missing imports, so I them I will add. Good. Let's Let's walk through it. So, this is the final method version data acquisition. The first thing he does is this gets the cache key for the query, and then first checks cash on delivery data. If in cache there is nothing, that is the cache is not warm, you would they said we need get fresh data. Then he checks our limitations speed and determines whether it is necessary him to move to sleep mode. If he no need to switch to mode sleep, then this is the one the method we used earlier. He will try. to do it maximum the number of times that specified in the definition method, and the value for default equals three. Therefore, in fact, he will send outgoing request to Massive up to three times and will try get data. And if he will fail three times in a row, then this will actually lead to a severe setback, and everything will be ready. Therefore, This is great. Problem is that if we are going to do the Momentum project and we want to send outgoing requests for a huge amount shares, then we will need to have opportunity to do much more than just send one request for one action and wait 5 minutes. We need to be able to process it in batches. So, we do this, adding this new one a method called Fetch Bulk Momentum Data. He uses different APIs from Massive, which allow you get grouped daily eggs. So, I'll insert this method, and we together let's consider what he means. Good. Therefore, this is a great method. Here method signature. So, he accepts tickers, and then accepts date calculation. So, this is mass sampling from using grouped daily API Massiv. He sends only two API calls and receives all tickers for 12- monthly and 1- lunar days simultaneously. Therefore, let's take a look it. The first thing he does, it checks, or the settlement date is equal to zero. If she is not there, then he assumes that we we count on today. Then he gets date 12- a month ago, he gets the date 1- a month ago. You Do you remember when I described this project at the beginning that we we use momentum 12 minus 1. This is means that we considering momentum stock prices for the last 12 months, for except for the last 30 days. So, they they call it 12 minus 1. For this reason we need to get 12th lunar day antiquity, we need to get 1 month old day prescription. Then, for all tickers in the list tickers that we provided, created this is a reflection where we say that we have no price 12 months therefore, we do not have a price 1 month ago. Then we are checking our speed limit, sending the first one API call. We send a request to Massive endpoint Group Daily Aggs, and maybe will be useful review documentation on this question. Okay, that's it. documentation for the endpoint that we are going to use to get all our price data for this trading moment strategies. So, you you can see what's there written to receive daily OHLC data, which means volume opening/closing at the maximum/ minimum, and VWAP, weighted average for volume price, for all US stocks on a certain trading day. This endpoint returns the full market coverage in one request that allows to conduct massive analysis, processing big data and research of a wide range market efficiency. Hmm, just to repeat, the reason why we we use this end point, is that free Massive API has limitations speed in one request or, sorry, five requests for a minute, and we want to trade widely spectrum of stocks, therefore one request for just a minute not enough. Hmm, sorry, five requests per minute not enough. So we we are going to unite this is in requests to this endpoint. Let's dig deeper. and let's create it now. Hmm, or excuse me, let's go deeper and let's check this out now, I would say. If you come here and say" fetch, er, bulk momentum data ", and then we let's restart this control command Django, what do we get? Two are needed if specified is incorrect argument. So, this is takes tickers and date calculation. Let's let's take Apple and Nvidia and let's see what it is for us will give. For the date we calculate Let's take the 10th number. Steeply. Unsupported type. Oh, that's an expected date. So we will do from datetime import date. And we Let's make a date. Steeply. Try this. He has there is no fetch attribute. So, here is a backup the method that I will need to be added. It is called backup method receiving mass momentum data. We we are going to him add, and I will explain that he does. So, he returns to the old method, if Group API daily request not works. Let's let's find out why we have A failure occurred. So, this is was here, reserve data processing method momentum. AT, backup method processing of missing data was also missing. So, there is all kinds of special the logic that we adding now, and me will have to do this to figure it out. Therefore, backup method processing of missing data tries find the nearest ones dates. So, obviously, if we ask stock market data over the weekend, this will encounter some strange problems. So, we have a few shifts of days. He will go for 3 days in future or for 7 days in the past. And this helped to solve many problems that we could have done it differently see in this API. If we run this now, this API, obviously, handles a bunch of data. Ago return requests may take some time time. Uh, and I think that this is what it is now is happening. He just gets data from Massive. Let's give it to him. a minute to process. Okay, I clicked. pause button to just understand that is happening. It somehow funny. I wrote it down as Nvidia, and not like a ticker, and it was causing the problem. So, the next thing we need to do is need to do this just add this one method of obtaining several shares, and we we can start management team and see what will return from Massive. Steeply. So, our management team has a result. Let's see, what is the result? Therefore, we have the price of Apple 12 months ago and price Apple 1 month ago. Similarly for Nvidia, in we have a price for 12 months ago and price 1 month ago. Both of these prices actually quite performed well over the last 12 months. So, our integration Massive is located in pretty good condition. In the next section we will move on to build our integration of fast trade. Before we let's move on to Snap Trade integration, I forgot one thing: us you just need record all our changes. So, we have This PyCache file constantly returns. I I am going to delete. its. And then everything else looks good. We we want to preserve our changes here, here, here. So, I'm going to do everything to place it. Uh-huh, This looks good. Good. Um, MVP of the Mass integration. Steeply. Then, uh, in the same catalog where we created a massive client, we will create new file named Snap Trade Client. In this files, uh, we let's create our client The Snap Trade API, which I conveniently called trading executor. Because it is in mainly that, for what will we do? use. Sorry. As before, we are going to add new init method. He is not will have no arguments, so this It will be very simple. Ahem, and we are going configure Snap Trade SDK here. He will look like this. And as soon as I did that I'll insert it, you'll see, what do we need to do a few things. First, we need to add some are missing imports from django.com. Import settings. I not really spent time on explanation of this in this video, but, according to In fact, we saw before we have this one settings.py file. This import allows import everything that defined in settings.py, in any other folder in your application Django. So, that's the first one. The second thing we need need to do this install SnapTrade SDK Python in our project. Therefore , I will show you project page on PyPI. She looks like this. Yes. So, this is the name the package we want add to requirements.txt. AND then we can import it into this file. So, we let's move on to requirements.txt, we will add it. And then, as before, we will perform UV pip install-r requirements.txt. So, this establishes many dependencies, which are subdependencies SnapTrade Python SDK. And then here, this allows us import SnapTrade Python SDK is like this. So, from snaptrade.client import SnapTrade. Okay, uh, we we are going to add a whole bunch of different ones methods to this SD to this, uh, client SnapTrade now. One of they will be called synchronization portfolio permissions. THERE ARE -oh, what am I going to do? to do, uh, for this integration, this is what I am going to form all this here yes, and every method is wise will simply call error exception not implemented during settings. Uh, here we will need import our portfolio model. So, from portfolio.models import portfolio. Uh, us too will have to import this list mind with typing import list . So, it's simple. type hint with built-in typing libraries Python. And then we also will have to import model positions. So, from portfolio.models import uh, import position. Steeply. So, this is first method. Second the method is called execution of orders on I will buy. So, this is the method you call as soon as possible chose securities, that you want to buy, and it's time actually place a deal. So, as before, we we are going to perform error raise not implemented. There are also no some imports. Therefore, we want import from trading.models import stock and trade. And then, uh, this one decimal type just take it from built-in decimal Python libraries. Good . Next method very similar. Instead execution of orders on we will buy we are going to perform sell orders. And we we are also going to supplement this error not implemented. Cool, it works. Uh, then we are going create a method for updating our trading statuses. It looks like this. Error Raise not implemented. And then we need more two methods that are called get current stock price and get available cash for trading. I actually just insert them and I'll explain right now, because they are both very simple. Before I'll do it, we're here. two more are missing imports. One was optional, but another is date and time. Good. So, for receiving the current stock prices are very simply. We just let's take a massive API- a client we had earlier, and, uh, call the method getting a price for date. This method not really determined. So, if you copy this and look here and take the test action F, it's not there. And that's because we forgot to add it, but it's true simple method. He It looks like this. So, here we have link to this price obtaining method on the date that we also didn't add it because I thought that he is not is used, that my mistake. It a fairly simple method, which we can add now. It looks like this Yes. So, getting prices on the date accepted ticker, target date, and then the number of days admission. Therefore, number of days tolerance determines, on how many days massive client will go forward or back if on this date none available price data. He just causes method of obtaining data about the action, which we created before. So, here it really is there is none custom logic. It just another way link to this. Uh, and the last thing we need here is not enough, that's what we need configure logger Python as we did earlier. So, we we are going import logging, and then logger is equal to logging.getlogger like this. OK. So, that's all. Um, the last thing we need need to add this method below under called um get trading executor uh , which returns a copy of this. It very simple. Looks like like this. OK. Let's begin. create some of these methods now. Uh-huh , in fact, before we will do it, we need to be configured our credentials SnapTrade. So, you remember that when we first started to work on large-scale integration, we had to adjust some variables environment so that we could actually connect to SnapTrade . Let's do it. the same process for SnapTrade. So, two The variables we need are here. I'll just copy. these two lines. We we can insert them here. And then, with a small amount kung fu like this, we we can, uh, set them to reading from our environment, er, file env {dot}. Okay, so you you can see that in we had a massive key API equal to configuration, and then massive API key. We did the same for secret key SnapTrade client and identifier SnapTrade client. If we now let's move on to our env {dot} file, and then, uh, let's open it new SnapTrade window. I I'm going to come in here and get your... Actually, I'm going to register a new one account now. Uh, registration , personal, continuation. Uh, steeply. So, to me need to do some things here are like this as confirmation my email mail, etc. I I'm going to do this in separate window. They probably are now send me link for confirmation email. Yes, I got it. Cool, my email Email confirmed. I I think if I now I'll update this, it will point to it. Yes, now generate an API key. First of all, I need to be configured 2FA, so I'm going copy this code and insert it here. Cool, check it out. enabled two-factor shutdown. Great, in I have an API key, so I I will take it and I'll put it like...How do we named the variable? Identifier SnapTrade client. Identifier client is equal to this. And then the key consumer, I want regenerate it and take it like this. AND then this is how we let's do...SnapTrade...How is it is it called? Uh, client secret. Oops, this is not what I wanted take. I wanted to take it. Perfectly. Our client SnapTrade looks good. Let's go now let's start creating some of these methods. So, the first thing we we want to do this add some precautions to to make sure that the briefcase contains certain information that we will need for its synchronization. In particular, we will do that. So, we let's check if it has briefcase and identifier SnapTrade user, and identifier account SnapTrade. If not, we we will cause an error value. And then, similarly, if we we will not pass any user secret, we will also call error error value. Then, uh, I I will insert all the logic. this method, and we we can figure it out with him step by step. Good. So, the next thing, what we will do is actually send API request to SnapTrade to get all positions account user. And then, for each position in answers about positions, we will get symbol, number, average cost, the current price, hmm, we let's skip everything that doesn't have a symbol or where number less than zero. And then we we will create promotions for all of them. After creation of shares we also create or we will update the positions, and then we will save them all in the database. Therefore , that's all for positions. Then we'll do something. very similar to balance sheets. We send a request to the API SnapTrade under the name " get balance account user ". And then , for balance sheet data, we will get through all of this in the loop and save everything is in the database. Therefore , we are going get balance cash from API balances and save it to current cash in briefcases. That's all. Now we will move on to execution section purchase orders. The same. I am going insert it and guide you through all of this. A lot of this will become clearer, when we move on to next section interface construction user. Okay, in execution of orders on I'll buy the first thing we let's do this we will make sure that there is actual list purchases that are sent. And if he is not there if he is empty or its no, we just return empty list. We also have similar check secret name SnapTrade user, as we did it in the method synchronization portfolio positions. AND then for each stocks on the list purchases we will create object of trade and let's save it in the database data. Then we we are going to send order to SnapTrade, using the method forced placing an order with with such a body. So, we we indicate the account record. This is a warrant for I will buy. This is a market warrant, that is, we do not need to specify Here is the price. Time of action The order will be valid for 24 hours, and notional value will be divided into shares, which was passed to this method and stored in object trade. The last one, what do we need indicate, this is a ticker. Then we gather. get the result warrants. We are going update the agreement, indicating the external order identifier . We are going update the status of the deal, so that she would be sent. We we are going to save timestamp when she was sent, and then we are going save it in executed agreements. Order method for the sale is very similar. I I'll show you now. So, we insert him here. Starting from above, if not list for sale, we we are going to return empty list, and if there is no secret user, we we are going to call value error. Then we will create a variable called " executed agreements" and we will assign her empty list. We let's go through all current positions and let's save them in a set . Then, for each stocks in the stock list for sale, we will start cycle. We will miss action, if it is not is in current position. So, if I own only Apple and Nvidia, and I trying to sell a Tesla , it's simple will miss the Tesla sale because she not really in ours portfolios for sale now. That's it. these two lines do. Then we will try create an agreement, send the agreement to SnapTrade, process response to the warrant just like we do made in the section purchase orders, while preserving the exterior order identifier for the deal, keeping status of the deal as sent, and then keeping the mark time sent warrants. And then we let's take all these executed agreements and We will return them. Here there is also some processing exceptions. Good, Let's move on. IN this SnapTrade client has another method, first than we can go to creation our interface user. It status update trade. I am going treat it the same way, by copying it into the window you see, and I will guide you through all of this. Okay, by- first. For any trade status, which we would call final, we Let's skip them. Therefore, if it is done, canceled or rejected, we just return false, that means that we don't needs to be updated its. He is located in the terminal condition. Then, likewise as we checked user secret in all our others methods, if the secret user not transmitted, we we will cause an error value. Then we we are going to get order status for using a method in the API SnapTrade. Get it status and assign his old status. Excuse me, take it. trade status with databases and appoint him/her old status. Then take trade status with SnapTrade and assign his object of trade in the database. Then we we check the pile fields, and if they installed in answers to order, we we keep them in the agreement , and then save agreement in the database. So, wow, that was very fast work, um, but this SnapTrade API basics. We have there is much more do in the interface user from point view of the actual connecting our accounts etc. Hmm, and I'll tell you. More about that later. Good before we let's move on to website creation and actual visible interface user for of this project, which I I know, we are all very worries. There are two more. services that we need to add to our system for rebalancing and calculation of trades. Ahem , so we also let's place them in this services folder. They will be called, uh- yes, strategic mechanism, and they will be called, calculator momentum. So, uh, I I know we just wrote a lot of code for the backend, and all glad to see this on frontend. Therefore I I will try to do this. a little bit of shorter. First we we will consider calculator momentum. Therefore, calculator momentum will look like this. So, I put this in, and I I'll just consider it. I will explain each method. at a high level, as they are working. First than I will do it, you you will see that we we get some attributes from settings.py that we need to specify. So it should be 12, and it has to be one. And this what, uh... the reason why are they configured as variables in settings.py, is that if you want split this project and actually accept its real trading strategy, this will allow you go from 12 minus one momentum to any -any other strategy momentum that you do you want use. If you want make eight minus three, for example. I am not sure that there is a lot of literature, what would it be confirmed, but from now on it is possible to adjust. Good. So, the calculator momentum has a method for calculation one momentum for shares. So, it's simple. allows you to do 12 minus one momentum , getting a bunch of prices from databases. He has method" get price from the database ", which allows easy find price data stocks in the database. AND then the method "get" price with API "like, but instead of contact the database data, he appeals to massive API. AND finally, we have a method "calculation of grades momentum "massively, who does everything necessary for calculating grades momentum in frontend. I will tell you. you about it step by step step by step. The first thing he does, it checks, Is there a settlement date? If she is not there, he assumes that this today. Then he checks whether it is list of stocks. If it no, he gets all active shares with databases. Then he goes through or, sorry, gets big data momentum from massive API. And then for each share in of this massive data momentum or about that for of each share in our list of shares he goes through them, gets 12 and one momentum, and then calculates here momentum assessment and stores it in the database data. Um, yes. auxiliary method for calculation of individual momentum estimates, and there are also a lot of things for ranking stocks. So, this method is called by ranking stocks by momentum. He takes into account the assessment momentum and calculates quintiles for a specific date. Actually we don't have such auxiliary method, so let's let's add it now. Good. So, if we let's move on to the assessment momentum, this is the method, which we want to add . And we need import timestamp belt so that it worked. If we scroll down, let's consider, How does it work? So, according to first, we see this regularity in many places this project, but he checks whether we send the date calculation, and if not, he accepts today's date for calculation purposes. Then he pulls out each copy momentum estimates in database and arranges them by falling grades momentum. If there are no grades, he just does the early return. If they no, then he goes through them all and calculates quintiles like this. Um, okay, let's go back to calculator service momentum. Using similar logic, we we have the opportunity get the top quintile, get bottom quintile, and then update our universe of stocks. Therefore, this is done in massive client and gets all S&P tickers 500. Then there is a certain logic for filling in price lists data. There is a certain logic. to receive momentum statistics . There is a certain logic to checks calculations momentum. And this summarizes the service calculator momentum. Fourth and the last service for this project called a motor strategies. I am going to make something like, uh, a brief overview of this now and then we we can go to interface creation user. So, I inserted it here. Uh-huh , it has a basic init method. And one of things that you immediately notice when look at this, this is it, that the only argument there's a briefcase for that. So, the portfolio represents a briefcase, connected via Snap Trade. So, essentially, when you apply one of these strategies momentum, you you need to choose portfolio, connected to Snap Trade. Uh, there's a lot of stuff here. The first method called should rebalance (should be rebalanced). And, uh, what does that mean? or what it does is looking for your last rebalancing day, and then asks: " How many days have passed since the last one rebalancing? Hmm, trading strategy by momentum it can be weekly or monthly. And this does, it checks, Is it already day? rebalancing during the last week or during last month. AND if so, he will say that you don't need rebalance. Following step is, um, method implementation rebalancing, which actually performs all trade, necessary for rebalancing. So, he ranks momentum stocks, generates trade signals, and then performs trade signals. Here is a method generation of trade signals, which passes through and determines which agreements you need to buy. So, this is essentially recalculation mechanism , and then another one method that is called execution of trade signals, which does all this. Finally, there is a method under called get strategy performance ( receiving productivity strategies), where you you can see productivity strategies, and then verify settings strategies if want to look at it. The last method in this is called running backtest, what is it really? just a placeholder. One of the homemade tasks that I I'm going to give people this project, this open a request for removal before this repository with good backtesting logic, and, uh, I would like to see everything you have. Therefore, This sums up our latest services. Further we will start with interface user. Good, now we will start with interface development user. This is a course from algorithmic trade, not with interface development user, so this, will likely include a lot of copying and inserts. Uh, but I I will do my best. to explain development principles interface Django user by progress of work. Therefore, First of all, I created off screen uh catalog in the store application called templates/trading. And then I copied a bunch here interface templates Django. Uh, come on. let's look at a few examples. Uh, what? would it be simple? Hmm, maybe delete portfolio. So, that what do I want to show you here, this is this one logic. It is called language Jinja templates. And if have you ever used React or any other library dynamic interface, I just I want to show you what this is the Django equivalent, and it allows you to have loops, conditional operators such as if statements etc., inside your HTML- templates. This is enough. stylishly. Now this is considered a little old-fashioned, and many serious programs just choose React. But that's exactly what it is here. Now, for our project actually used this, we need to add urls.py file. We let's go to the store addition. We will press "new file". He will be called urls.py. And then we need insert something similar. This is, in essence, URL heap mapping addresses with a bunch of HTML- templates. So, if we will run python, Let's clean up first. my terminal. If we now let's run python manage.py run server, we Let's open it. We we will never see each other again standard page Greetings Django. We we will see the real one addition. AND It turns out that I was wrong because missed a step. I you I'll show you. Um, in mainly to us need to go to Root level URLs.py and import them also. So, in the application Momentum Trader, which is like home of everything our project, we need, mmm, insert, um, URL- import addresses from trade. To us need to do this. Representation trade like Oh, okay. We also lack some representations. A lot is missing. So, apart from ours file URLs, nam also needed add a bunch Django views. So this will be enough large file. He has 800 lines. This is a pile, mmm, a bunch of submissions Django, which handles life cycle responses to the request in application. So Bear with me while I will finish this. We we are going return to momentum_trader/urls. Um, I actually used wrong here syntax. I want use this. Turn on Cool. And I I think that this the frontend has download now. Maybe I will have to restart the server developments. Yes. Perfectly. Okay, our app is already running, and you you can see that this approximately similar to that , what did it look like demonstration that I showed you before in the video. However, I missed a big one step, ignoring all these representations Django. So I am now I'll explain what it is. On In fact, each of these methods–this is a function, which processes the request browser. So, Simply put, can you imagine Django presentation as a function that accepts browser request and sends a reply browser. That's why this argument is request, and you can see below, what are we we render something for sending back. And in render functions you you will see that she accepts the request, accepts which HTML- display template, and then takes a certain context to insert in this HTML template. Therefore, if you switch to dashboard.html, I'll close these windows that we don't have now we use. If you will look at dashboard.html, you will see, that somewhere there is a field for calculation dates. Right here. So, in Python functions for toolbars we calculate the date calculation, it inserted into toolbar, and then we can see it in interface user. And this, in in principle, how frontends are working Django. We need to work on it, to be able to see some promotions in our portfolio, and we Let's do this next. First than we will continue interface development user, we let's fill our database given a bunch of stocks and historical data about prices, so that in interface user were things we can to see that to make sure that the project works as follows we expect. For I will add a new one to this. control command Django called backfill data. This is quite long. team, and I don't know, or its details extremely important, because she just to fill our databases. Actually it is not related to program, but in basically she fills our database given a bunch of shares, and also historical data about these shares. So, put this in your project, and then run this command: python manage.py backfill_data, a then you can add--update-universe, a then--days 420. And, um, us also needed make sure that this method determined that we clearly missed earlier. Hmm, I didn't think so. that he will be to be used in project, and it is not used, except for the sake of, um, this, and it's just hardcoded list of some S&P 500 tickers. He It looks like this. Good, so get the tickers S&P 500. I think he returns, um, 50 largest stocks in the S&P 500 or something like that. AND these are the stocks we first we gather fill the database. So, you can to see that we we get about 200 and some historical prices for everyone security, and this it will take some time to to finish because you reach the limits speed. So launch it, and then come back, when he finishes. Okay, so after batch completion filling and repeated loading interface user you you will see the button " To list momentum" in upper right forged. You need will press on it , and loading will last a long time. It may take 3 minutes, because need to be done many calculations " under the hood", especially when everyone data from Massive API are loaded into your local database data for the first time. But when will it be done , your home the page will look like like this: you will have Top 10 and 10 worst stocks momentum, all of using logic , which you wrote yourself . So congratulations. Now we just need to adjust functionality trade. We created a lot of logic on server side, but nothing yet not tested. So Let's begin. If you go to mine trading signals and click « Generate signals » , you will get this error. And you will say: "Oh, what is this?" Every time, when do you get interface error user, similar to this one, from Django, to you you need to come here and look into your terminal to to see what it is error. So, here It is written that we are not we can import trading with trading, and this because we imported it from wrong programs . It should be imported. from portfolio.models, not from trading.models. So, it was just my mistake, when I, uh, coded this manually. So, I made I saved this change. Hmm, we need again press" generate signals ". Active portfolios not found. First create a portfolio. So, we clicked "OK" ". And, uh, if you I wonder where this is. because I know that we didn't create this manually, uh, create portfolio. It is in the file views.py, which we inserted into the window signal generation. So, we need generate now portfolio. If we click in interface user on the left panels on this tab portfolios if we click here, a request will appear for creating your first portfolio. Let's call it, uh, free registration educational Code Camp guide. We Click "Next". AND then we will choose Alpaca for our broker and safely let's connect via SnapTrade. So, I have another window a pop-up appeared window. It looks like this. We press" Continue ". We are back again press" Continue. "And then I already entered Alpaca. AND It says that we authorize Snap Trade for installation connection, etc. We press" Allow ". Boom. Um, this is not very nice displayed in small window, but if you like it you will open you will see that The connection is complete. We have $100,000. in cash, like us expected from paper connection Alpaca, which we installed earlier. AND, uh, now we can view portfolio . So, this is a briefcase. We we can synchronize it, we can generate signals, we can receive trade signals, we can view our momentum indicators etc. Let's do it again let's come here and let's press" generate signals ", now that we have portfolio set up . We have another one mistake signal generation. So let's do it again let's fix this in Django terminals. Good, It is written here that we trying to get access to portfolio.get_current_positions, a This does not exist. So let's add it. If you go to portfolio, or, sorry, this should be in models.py in portfolio application. To us need to add a method called get current positions in the portfolio. So let's do this. There are actually several methods for position, which we will need for this. So let's let's add...Okay, so what do I just added? I added a method called update current value, which updates current value portfolio that I surprised. Me had to add a method called add shares. I added a method under called remove shares. They are on wrong model Django. Sorry about that. They must not go. to the portfolio. They must go to position. So, update current value, add shares and remove shares in position. In our portfolio you only need to add two very short and simple Python methods. We need to add calculate total value. Everything that he does, this summarizes the current the meaning of all positions in the portfolio. And then we need add a method under called get current positions, which simply filters all positions in the database data and selects them. So, after all we can do this return to our interface. Em , this is not the right window. It the window in which we have failed. So I will refresh the page. AND then I press " generate signals ". I click "OK". AND then we are successful generated 10 trading signals, 10 purchases and none sale. So, what is in us here? We have some purchases of Exxon Mobil, RTX, this Raytheon? I think. Nvidia, Johnson Johnson, Merck, Broadcom, Google and Google. I think that if you really were gathering turn it into production and build on this real trade system, you probably you want deduplicate between two Google. It, obviously one and the same the company itself. AND then you have AMD and Intel. So AMD actually has highest score impulse, therefore let's buy it at 100 dollars. Click here. Um, we're going. choose this portfolio. This is the only one we have connected. Hmm, and then we are going make a purchase. Okay, so it's written. that the purchase order successfully submitted. Now we want to go to Alpaca and see what happened. So, this is Alpaca. We've seen this web- site earlier in the video. Um, I'm going to sign in. by means of account, which I created earlier . I need add your code authentication. Okay, I am now. entered. Um, I get it. welcome message. What about me? surprising, but look where Intel actually bargained correctly . So, we have already grown up. by 0.03%, and just like that we we can walk and to trade the rest momentum strategies. Um, that's the whole project. Thank you guys for that. followed us all the way time. Um, if you want to contact me with questions or with something else that you could do about project to to learn a little more, please Let me know. IN otherwise, uh, no feel free to play with this. I would like to see how you are, Guys, get on with it. this project and create with his help more things or others cool things for using Massive Trade or Snap Trade. And, uh, send me any What are your jobs? I would wanted to see them. Thank you.

Generated algorithmically for Search Engine Indexing.

Summarize Another Video