Transcripts
1. Introdution: Hello, and welcome to the
Algorithmic trading with Python using Alpaca
and Polygon course. I'm your instructor,
Nate Albright, a little bit about me. I've worked as a data
specialist since 2018, utilizing business
intelligence, data analysis, data science, and
everything in between. I have experience
with Python, SQL, HTML, CSS, JavaScript,
and Jango. What this course is about, you're going to learn
the basics of Python. You're going to create an
Alpaca markets account. You're going to pull data
through the Alpac API, as well as place trades
through the Alpac API. Utilize polygon, dot IO to
pull stock related data, and the basics of creating
a trading strategy. What this course is not about, utilizing the data to create a commercial website
or application, which is the broker
API portion of ALPACA. You should not use
the strategy examples in this course on a
live trading accounts. For example, purposes only, you should create your
own trading strategies, make sure they're tested
and tried and true. And lastly, this is not about
crypto options or Four X. We're strictly going to go
through stock related data. So with that being said,
let's get started.
2. Disclaimer: Course disclaimer.
The strategies and information
presented in this course are for educational purposes only and do not constitute
financial advice. The content is
designed to provide general insights into
stock trading and is not intended to be a
recommendation or endorsement of any particular
trading strategy or investment decision. Trading in the stock market
involves significant risk, and past performance is not
indicative of future results. It is important to conduct
your own research, consider your
financial situation, consult with a qualified
financial advisor before making any
trading decisions. By participating in this course, you acknowledge that you
are solely responsible for your own trading decisions and assume all risks
associated with them. The courts creators,
instructors, and associated parties make no representations or warranties regarding the
accuracy, reliability, or completeness of the
information provided, and they disclaim any liability
for any losses or damages incurred as a result of using or relying on the
strategy to discussed. Proceed with caution and
trade at your own risk.
3. Download and Install Anaconda: All right. In this lecture, we're going to go
through how to download and install the
Anaconda environment. So First thing
we're going to do. Let's go to Ancona
download in Google. Click on this first link here. It's going to bring you to
the Ancona download page. We're going to go ahead
and skip the registration. And then you'll select depending on your
operating system, either Windows Mac or Linux. I already have this installed, but for Windows users, you would just click the 64 bit, and so on for Mac and
Linux. But click this. You'll get it installed. I'm just going to
bring it in here. So you can see here at the top, I have the Akana download. What I'm going to
do is I'm going to click to open that up. I'll move this out of the way, and it's going to take a second here to actually open that up. Once I've got that, then I can go through the prompt to install the
Anaconda environment. So click next. I agree. You want to read through
that. Just me next. Next. I actually have to You
shouldn't have to do this, but I already have
this installed. So it's going to make
me do this again. Let's just say
whatever Anaconda for. And we'll click Install. Once you click install, it's going to take a little bit, but it's going to
go through and get all the packages installed
onto your device. We're going to take a break here to let that stuff install. When it's done,
you'll click Finish, in the next video we'll actually open up that environment and
show you what it looks like.
4. Navigating Jupyter Notebook: All right. So now
that we've actually got the antica
navigator installed. We're going to go ahead and
open that application up, so we'll come to
our start screen, find the anticodon navigator. You're going to click on that. It's going to take a
second for it to load up. Once it does,
you're going to get a window that looks
just like this, and you're going to scroll down until you find Jupiter Notebook. Jupiter Notebook
is the environment that we're actually
going to use to code. A lot of programmers use
it to test out code. We're going to be able
to use it for pretty much everything we want
to do in this course. So I'm going to click Launch, and it's going to open a new
window within your browser. So we'll give it a
second to do that. It's opening up. Once
we've got it open up, this is going to be
your main screen. This is where you'll
see all of your files. You'll be able to
navigate, just like you would in a file Explore
on your computer, all of the files that
you've created and save. For now, we're just going
to create a new file, so we'll click new
here and new notebook. Now, this is going to be
the screen that you'll see for a majority
of the course, like I said, we're just
going to select Python, and this is where you
can begin to code. You can do a markdown
if you just want to, for example, if we want to just words to
indicate each section. So we can say, and the hash
tags, the more you put, the smaller the lettering
is, start here. If you click Shift Enter, it executes the cell. So as you can see, you can cut cells,
you can insert cells. You can run the
code if you wanted to run all cells at once, if you have a bunch of them,
you can do that, functions. Pretty similar to other
coding environments. It's just a little bit more friendly with the
separation of the cells. So for example, if we wanted
to just do five plus five. And you can click play
if you want it to run. It's going to give you ten or if you wanted to just
use the keyboards. There's a bunch of hot keys. You can actually look those up. I believe you click keyboard
shortcuts is under help. All of these. I use
some of them sometimes, so if you see something click, and I don't actually
click it on the screen. This is probably what's
happening on accident. But like I said, shift enter works as
well two plus three, Shift Enter, and it's
going to give you five. So beyond that, we probably won't use many more functions, but this is just a basic entry into first the installation and download of Anca Navigator, but more importantly,
Jupiter notebooks, which we'll be using for the
remainder of the course.
5. Python Basics - Data Types & Variables: Right. Now that we've got
our environment set up, we're going to start going through the Python basics
in the Jupiter notebook. First thing we're
going to review is the data types string. So a string is any sort
of characters that are wrapped within either
single or double quotes. It really doesn't matter. But, for example, if
I did just hello, and I check, you can
use the type function. To check it. We'll get
into functions later. But if I just did hello, You're going to
see that it comes back as the type of a string. In array is a list of values, so it can be any
group of values. It can be a
combination of strings and integers or
whatever it may be. For now, we'll just do numbers. So this is our array, and I'm going to copy this and then I'll print out the type
for that as well. So you'll be able
to see that list. List and array, it's
the same thing. Integer is a whole number. So, it can be negative. It can be 1 million But
it's just a whole number. So the type for that. It afloat is a decimal point. So once again, it can be
negative or positive, no matter how high, if
it's a decimal point, it's going to be
considered a float. So 1.05, let's do that. And we'll check the
type on it. Float. Now, Even though this is technically one
as a whole number because we have
that decimal point, it considers it a float. So if I got rid of
it, changes the int, but once we have
that decimal point, goes back to a float. Now, a dictionary
is a way for you to store values and reference
them using a key. So once you call upon that key, you are able to get
the value for it. So what I mean by
that is first to you, it's within curly brackets, so we'll open those up, and the key always has
to be in string format. So let's just for now, we'll call it key one. And then to separate the keys and the values, you use a colon. And then you can
use whatever here. We could have a
nested dictionary, which just means we could start another dictionary
within this dictionary. We can use an integer, we could use a float. We could use another
string. It doesn't matter. Then to add another
value to this diction, another key value pair
to this dictionary, you separate it using a column, and we'll do key two, and we're going to make
this value as five. So let me just copy this
and show you the type. Dictionary. There you go. Now, if I wanted to call on. Actually, we'll show
you how to call later when we go through
the actual variables. For now, just know that
this is the format, the syntax of a dictionary. A bool is just false. So you have to use a
capital either T or F, and you'll see I'll do false for checking the type. It's a b. And then a nu value
is essentially that. There's just no sort of
value type, non type. Now, these different data types can be stored within a variable, meaning that we store it
utilizing some sort of name, and we're able to
call upon it later. We'll dive into
that more as we go through some of the other
sections of this Python basics. But For now what
we're going to do is we'll start with our strings, and we're going to just label it as actually,
what we'll do is A. So the name of this
variable is A, and we'll set it
equal to string. Actually, we're going to we're going to make the
string just hello. So if I run this, it's not going to
give me anything, but if I call the
letter A shift enter, it's going to give me
that variable value. So now, B, we're
going to run through, let's hear, what did we do next. We did an array. So let me copy this
array up here. And we're going to
store B as an array. And then we ran that
cell shift enter. Now, if I call on B, it provides me with that
array or that list. C, we're going to
do the integer. So let's here we got 1 million. Just make sure that's 1 million. 123, 123, yeah, it's 1 million. C is 1 million. We'll do D is just going to run through
this quickly here, 1.05. The dictionary will be E. And F is going
to be the bull, we'll call false, and then
is going to be the nun type. All right, so I'm
going to run this so we have all of our variables, and then we can take
a further look. So obviously, if I
call C shift enter, it gives me 1 million, same with D. It's just going
to give me that flow value. Now, E, E, you have to use if I just call E it's going to
give me the dictionary. But let's say I want
to actually call upon one of the values
within the dictionary. So if I wanted to get this five, I need to if I know the key, the key is q two, I want
the value for K two. So what I'll do is first
type in the variable, and then we open up brackets. And then type in the
actual key values. K two. When I call this, it
should give me five. Now if I change this to K one, it's going to give me
the value four K one, which is the string
string. So simple as that. That's how the
dictionaries work now. If I call F, it's the bull, and then G is the. So it returns,
obviously, nothing. So that is just a
quick review of one, the data types, and
then the variables and how to call some
of those variables. Next, we're going to
get into operators.
6. Python Basics - Operators: All right, we're going
to continue here with operators in the
Python basic section. I went ahead and created three
variables to show these. So we are in the
same sheet as above. Now, I know we used this A B and C as
variable names already. What happens is when I shipped enter on this,
it reassigns those. A is no longer a string of
hello, it's an integer of ten. Same with B as being integer
of five and C three. So the first operator we're going to go
through is the addition. So if I take A plus B, which is ten plus five, it's going to shift enter
15 is the answer for that. Now, same thing as C. It's going to give me 13. The one thing to know here with the addition operator is that you can also
use it for strings. So just real quickly,
I'll show you that. So if I said hello, and I use the plus
sign and said world, I put the space in there just so that it's going
to come out correctly, you can see that it prints
out the actual string of it. So that's just something to
know, but now we'll just focus on the using
numerical values. You can do this with
floats as well. We're just using integers for
the time being subtraction. Obviously, if you understand
how the addition part works, you're going to know how
to subtraction works, multiplication, we'll
do eight times B, gives you 50, it's taking
ten times five division, take a divided by
B gives you two, it's 10/5, the remainder, what this is is it's taking and it's signified as
the percent sign. It's going to take A divided by B and then present the
remainder of those values. So obviously, 10/5
gives me no remainder. But if I did ten divided by C, which is three, three goes into 103 times with
the remainder of one. So when we run this shift enter, it's going to give us that
remaining value of one. Now, the greater than operator, so this is going to give a boll. So if I do A is greater than B, it's going to say it's true because ten is
greater than five. Now, if I say A is less than B. It's going to say false because ten is greater
than, like we just said, five, but if I did three is less than five or C is less than B, then
it gives me true. Now, equal to. The way you check to see if
two things are equal. So A e two equal signs. A is equal equal to
b, presents a bull, that's false, but is A equal
to A, that gives you true. The last part of this is the greater than or equal to
and less than or equal to. Is a greater than or equal to b, that gives true is c
greater than or equal to b. That's false, is B, greater than or equal to b. That gives true because
they are equal. So it's either one,
greater than or equal to. And then less than obviously
works the same way. So it's a less than or equal
to B that gives us false because ten is higher than
five, not equal to it. C now gives us
true because three is less than or equal to five. So those are the operators. Next, we're going
to move into loops.
7. Python Basics - Loops: All right, we're going
to continue with the Python basic section
and get into loops. So we're going to go through in this same Jupiter notebook here. We're going to go through
four loops first. So what this does is essentially
allows you to write code to perform an action multiple
times. It's looping. So the way you write syntax four a four loop
is you start with four. Then you pick a name for the value each time
that we're looping. So it's going to be essentially a variable name that we can utilize within the
four loop function. Um, I'm just going
to call it val, and then we type in and then this is where
you can choose. If you have a prior variable, you can use that, if you just
want to use a current one, I'll show you how
to utilize two of the different ones and we'll see more throughout
the course later. But the first one we'll
just do is a string. So the way it loops
through this string is it's going to perform a loop. For each letter
within this string, so this will be five
different loops. Now, the letters
really don't matter. You know, I I wrote
within this four loop, and you have to make
sure it's indented, that's the proper syntax. Print val. What this is going to do
is it's going to print the letter each time it loops through within
this string here, I'm going to shift enter, and
you can see it does that. But if I just wanted to
do print the number one, it's going to print every
time for the word hello, if I picked another five
letter word, like horse. It's going to perform
the same exact action, so you can see that that
doesn't really matter there. The next thing I want to show is how how it
loops through a list. So if we did one to 345. If I wanted to print the val, it's going to loop
through five times printing the value within
the list in order. You can see shift enter, one, two, three, four, five. Now, this can be utilized for
adding to a certain value. So if we wanted to start with
a variable x equals zero, and then we wanted to set a
new value for x on each loop, but x is equal to the
current value of x, which to start the loop, it's going to be
zero plus the val. So the first time around, what it's going to
do is it's going to take the starting value
of x equals zero. We're going to create
a new value for x, so x is equal to the current
value of zero plus val, which in the first loop is one. So then what that will do, and we're going to print x, then the new value of x
is print out one. Then the next time around,
x is currently one, so we're going to create
a new value for x, x is currently one plus
the current loop value, which will be two. So that'll be one plus
two equals three. So the next time that it loops through it'll give
us three and so on. So if we shift enter, you can see exactly
how that works. Next, we're going to move
into while loops here. This functions a little
bit differently. It essentially has to get to a point where it
stops, so it's saying, it's going to loop while the
current process is true. So if we say, wow, x is greater sorry, less than six, and we'll actually give it
a starting value for x. Actually, just to
not get confusing. We use y this time around? Y is equal to zero. That's our starting value. While y is less than six, the new value of y we're
going to give is y is equal to y plus one. And then what we'll do is
we're going to print y. So the first time
around, what it's going to do is y
is equal to zero. While y is less than six, this is true, right
because it's zero, zero is less than six. We're going to run
through this code here. So the new value we're
going to give to y is y, which is zero plus one, so it's going to be one,
so it'll print that. It's going to do this up until y is no longer less than six. So once it gets to
the value of six, it's no longer going
to run the code, and it will break
essentially, it'll stop. So let's run this. You can see, it gets up to that value of six. Why did it get to the
value of six and not stop? Here's why. Y goes through, it becomes one, two,
three, four, five. Once it gets to y is equal
to five, it prints that out. We have five here, so
five is less than six. The new value for y is y equals five plus
one is that six. So that's why it
didn't stop there. Now, if you wanted it to stop, five, then you can just
change that variable up. But that is a four
loop versus a loop, we'll show you more on
those later in the course.
8. Python Basics - Functions: All right. Moving on to functions within the
Python basic section here, functions allow you to define a set of steps and parameters
and call upon it later. The way that you
begin to function is always the same with
the letters the EF. And the next part of the syntax is to actually
name the function, so we're going to
call it my function. We open up parentheses. If you have parameters for when the function is
called later or variables. You'll insert that here. For now, we're just
going to leave it open. Insert a colon and
then click Enter, drop down to the next line, make sure you are indented. Jupiter notebook will
automatically do that for you when you're
writing Python code, but if you're using
a different IDE, then, make sure you're
paying attention to that. Now, in order to return
something from a function, you will use the word return and then return
what you want to. So if I wanted to
return the word hello, this is a very simple function. I'm going to go ahead,
shift Enter to run this. And then the way
that we can call on this function is
by typing it out. My function, and we shift enter, and it returns that hello. So that's just the very basic
form of how function works. Now, let's say we have different variables that are
within our code somewhere, and they're going to change. So it's not always going to
be the same thing we don't always want to return hello. What we'll do is we'll use
the example of a tax payment. So we're going to start
to create the function. We're going to just
call this tax payment. And within these parentheses, the variables we're
going to use is income. And the tax percent. So then we'll add her
colon, click next. Now in order to calculate this is going to calculate the taxes that we're paying,
not what's left over. So we're going to call
our variable total paid. This is where we're
going to create the equation to calculate
this tax payment, and all that'll be is the
income times the tax percent And what we'll want to
do when this function is called is return the
total amount paid. So we'll shift enter that creates the tax
payment function. And now to actually show you
how this function works. We're going to first type in the function name tax payment. And then we have to insert
our two parameters, which is the income and
the tax percentage. So let's say we have
$100,000 in income, and we pay 25%. And taxes, we're going to
enter that as a float. When we click to enter this, what it's going to do is it's going to run
through this function. It's taking in our
income as $100,000. It's taking in our
tax percent as 25. It should return us $25,000. Shift enter 25,000. So you
can see how that works. Now if we wanted to run this for somebody else who has
a different income, maybe they make $80,000, and they're paying 20% tax, will shift enter, and
$16,000 is 20% of 80,000. So that is how functions work.
9. Python Basics - Pandas: All right. The last part of this Python basic section
we're going to cover is the Pandas library in order
to install a library. If you don't have it installed
already any machine, you use the word pip install. And then you type
out the name of the library. In this
case it's Pandas. I already have it installed. So when I shift enter, it's going to tell me that the requirements are
already satisfied. You should see just a bunch of downloading and
once it's finished, it'll tell you it's done. Um, then the next
thing we have to actually do is to
import your library. So that's as simple as import, and the Pandas library. If you want, you can
just leave it as that, and when you go to
call Pandas function, you type out the
entire word Pandas. What's standard practice is
to give it an alias of PD. So import Pandas as PD. So now we have the
Pandas library import, and we can call some
of the functions. Really what we want to
do. Pandas is used for data import manipulation.
You can pull it in from CSV files. We're going to use it to pull after we've pulled
API data from AlPACA, we're going to create nice data frame tables utilizing Pandas. So that'll be a big part of it. And I'm going to give
you an example of what those data frames are
going to look like. So I have this just
random data up here, and I'm going to go ahead
and just run that data. Then what I'm going to do is show you how to
create a data frame, so you can name this data
frame, whatever you want. It's a variable, but standard
practice is just DF equals, and then we need to call
on that Pandas library. So like I said, if you
didn't give it an alias, you'd have to type out Pandas, but we gave it the
Alias a PD dot, and then we are
creating a data frame, so it's a capital D
F open parentheses, and then the data that
we want to use is this variable to dictionary that we have called data. Now, This already has the way
that it's formatted. It has column names in this. If it didn't for
whatever reason, if it was just the arrays, you would add as the
second parameter of this, the columns, and
then list those out. But this does have it, so we're just going to go ahead and shift enter to
create the data frame, and then we will
display the data frame, and you can see it
gives you a nice table. It's easy to manipulate. If I wanted to get
just the first row, can type in data
frame dot head is the first row and put
in the number one. It's going to give
me then one row. If I wanted the last row,
I would type in tail. So you'll see that
we utilize these two later down the line just to kind of take
a peek at data. This is a tiny data frame, so we'll just pull
in the entire thing. So that wraps up the Python
basic section of this course.
10. Alpaca - Sign Up: All right. Next, we're
going to dive into Alpaca. First thing you want to do
is create an Alpaca account. So you're going to come
to Alpaca dot markets, that should take you
directly to this page here. When you come here on the right hand side,
you'll see the sign up. As I mentioned before, going to be covering
just the trading API, which is for individuals,
not the broker API, which is to create commercial
applications and websites. So click on Trading API, and we're not going to go
through everything here. I've already got
an account setup, but fill out your credentials, you might have to verify a few things through
your e mail. But once you filled
everything in, click Sign up. And then once you officially
have your log in, get logged in there
for the first time and we'll show you in the next video what
that's going to look like and give you an overview
of the dashboard.
11. Alpaca - Dashboard Overview: All right. Now, once you've
signed up and got logged in, this is what your dashboard
is going to look like. You can see we're
on a paper account. Means that anything
we trade with, it's just for practice, and it gives you a little
message about that at the top. You're on a paper trading. No real money is being used. There's an option to open
a live account where you can use actual money on
the Alpaca Brokerage. But for this course, we're just going to
be using paper money, that way we don't have to
recognize any actual losses. So an overview of
this page here, you can see what your current
account balance is at. That's your portfolio right
here as you make trades. It's going to show you over time your total account balance. You can change the time frame as to what it looks like,
what's being displayed. This is right now
just for today. We haven't made any trades. You can see there's a $10,000 balance on this paper
trading account. Now, let's say you're
testing a trading strategy, and down the road,
you want to restart. You don't like what you've
done. You want to be able to just start off
with a clean number. If you come to this
reset account button, this allows you to
add a new value in. So, whatever that may be, if you want to do realistic, unrealistic, any number $0-100 thousand, you're allowed
to type in there. So let's just put in 50,000. I'm going to click Confirm. Paper account reset. It's going to reset,
reload the page, and then you'll see that my
account is now at 50,000. Um, on the right
hand side here, now, beyond just using
the actual API, the Python code to buy and
sell shares of stocks. You can do it directly
here on this page. So the market is open
right now it's Thursday. I'm just going to type in Apple. We'll do just a market order, which means just to
execute right now, one share Goto canceled, review the order.
And click Confirm. And the order has been created. You can see that my cash
down here went down. The buying power, the
reason why the buying power is twice as much as the cash is because it is technically
a margin account. So they'll give you 100% more on top of the cash that
you hold in the account. If you don't know
what margin trading is, I would look into that. We're going to just
focus on trading essentially with the cash
that we have on hand. You can see when I scroll down
further to top positions. I've only got one,
that Apple share that we just bought now,
and you can see it live, that it's actually trading,
so our balance is moving, and you're going to see
this one day change. This chart is actually
going to get filled in, now that we actually
own something here. And then recent orders as well, it's that share that we
just bought a minute ago. Um, the last thing to go over on this right hand side here of the dashboard is the API keys. So these are the
ways that you're able to enter into the code. First of all, the endpoint, and then the keys that
allow you to pull data through and know that it's
for your specific account. If I click Generate keys, it's going to generate
me a new key, and a new secret key. Secret key. Make sure
to read this note. Your secret key will
disappear after refreshing or navigating
away from this, and make sure you store
that in a safe place. You can always regenerate
the API keys later, but that's just a little
something to pay attention to. We'll get into pulling these and some of
the future videos, but this is just
an overall summary of the Alpaca dashboard.
12. Alpaca - Alpaca Connect: One other quick thing I
wanted to cover before we dive into this is
this Alpaca Connect. If you click into this,
this is where you have the ability to integrate apps
that are built by others. You can see, I don't
have any connected apps, but there are featured apps, trading view, if you're
familiar with trading. You've probably been
on trading before. One of the best tools
for visualization. You can also develop your own apps if you
want to and submit that. But if you come here, there is a ton of
apps that have been created that you can
integrate with your Alpaca account. So trading
view, you can see. When you're on the
trading view website, it's going to allow you to
integrate Alpaca with it, make trades directly
on trading view, utilizing your Alpaca account. So that's just a quick
little tippit about the Alpaca Connect
and what it entails.
13. Alpaca - Documentation Part 1 - Introduction: All right. The next thing
we're going to do is go through the documentation, which will then
eventually lead us into actually using the API. So we're going to
click on API here. This is going to pop open a new tab for the documentation, in this video, we're going to cover the introduction section. So it's the welcome.
Welcome to Al PACA. You can go ahead and
read all of this. You can read about ALPACA. So if you're interested in
the founders, the vision, allow 8 billion people on the planet to access
financial markets. What services does
Alpaca provide, you can go ahead and go through this overview,
lPACA API platform. So it's a RST API. They have web sockets as well. We're obviously going
to be utilizing this and not just using
those dashboard tools that we had shown
in the last one. Architecture, any
updates and upgrades, changes, breaking changes. SDKs and tools. There's a Python library
that you can utilize, and then additional resources, if you're interested, learning. They have a blog, Slack,
of course, Forum, If you need any support. So for more, you can click here. System status have to date
on any updates and outages. And then finally, you can read
through their disclosures.
14. Alpaca - Documentation Part 2 - Broker API: All right. This next section is going to just quickly
cover the broker API, as I mentioned, we're
not going to be really reviewing this in this course. This is for creating commercial applications
and websites. You can see that here. This is the documentation about Broker API that helps you build trading apps and brokerage
services for your end users. If you are interested
in this kind of thing, this is exactly where
you're going to find the information
to go through it. In the other sections, you're going to
see how we review documentation, and utilize it, so you'll be able to use that knowledge to
then refer back to this broker API and kind of go through all of the
different sections. But as I had mentioned, we're not going to
be reviewing this.
15. Alpaca - Documentation Part 3 - Trading API: All right. The next section
of the documentation we're going to cover
here is the trading API. As I had mentioned, this
is what we're going to be utilizing about trading API. Trade stocks and crypto
with APAC is easy to use trading API up to
four times intraday, and two times overnight
buying power, short selling, advanced order types, all packaged and delivered
through our API. As we've already gone
over, we're going to be utilizing a paper
trading account. You can create a paper trading account anywhere in the world. Now, the live accounts. I believe there's restrictions
based on countries, so you might want to look into that depending on where you are. But've got the account plans. You can go through, review that. Crypto trading.
Understand orders fractional trading,
meaning, you know, if there's a share
of apple stock, Apple was trading at, I think it was around 230
when we looked at it earlier, you can buy as little
as $1 worth of apple. So you don't have to buy
an entire $230 worth. They have this, as mentioned
for over 2000 US equities. Authentication. This is
what we'll be utilizing to actually pull through
the data from the API. Now this is not exactly
what's going to look like. We're going to be utilizing
Python as mentioned, so to look a little
bit different. And we'll go through and
review all of that later. We'll be utilizing
that those keys, the key and the secret
key with the domain, as I had mentioned. Getting started with
the trading API, section outlines how to
install AlPACAs, SDKs, if you're utilizing the
library, the account, assets. Now, this trading API section, this is everything
that's associated with your account pulling through different sets of financial
data, and all that. We're going to review
in the next section, which is the market data API. So we'll be utilizing
trading data, the trading API and
the market data API. As you can see here,
assets, orders, positions, you're going to be
able to pull all of this data using Python.
You can see here. It's already got it set
up in Python format. If for whatever reason, you care to use a
different language. C sharp, whatever it may be, you can change that within
the documentation review it. We'll strictly be using Python. Though, you can pull
through your positions. This is going to
show you what you have in your paper account. We've already gone through
paper and paper versus live. Your trading account. We aren't going to
get into crypto, but if that's something
that interests you, this is where you can review
the information on that. Option trading. We're
not going to get into maybe in another course, but there's the ability
to trade options as well. Part of the reason
why they gave you the margin account
account activities. We'll go through and pull this, the fractional trading
that we had mentioned, and how to actually place
those fractional trades. With the API, margin and short selling,
we're going to skip, we're not going to
do any short selling or trading on margin. Orders, we'll review
ser protection. You can come in and review this. Not going to do any
web socket streaming. And if you have any questions, this FAQ section is
a good place for you to go to get any of that
information figured out, have something explained to you, weighted average,
whatever it may be.
16. Alpaca - Documentation Part 4 - Market Data API: All right. The last part
of the documentation, we're going to review
here quickly is the market data API about
market data API gain seamless access to a
wealth of data with ALPACA market data API offering real time and historical
information for equities, options, crypto, and more. This is, as I had mentioned, where we're going to
pull that market data. You can see there's
a pricing structure. The basic is free. So you can get Most of the symbols that
you're going to need definitely the ones that
we'll need in this course. If you pay $99 a month, you can get more than that. Historical API call, you can see that you're going to
get 10,000/minute, as opposed to the 200/minute that we're going
to get for free. And the data is delayed slightly
about 15 minutes or so. But for the purposes
of this course, we're not doing
Algo live trading. We won't need it if you create a strategy and you eventually do on a live account,
whatever it may be. This is something you consider. But like I said, we're
not going to use that. There's the options data
that you can pull as well. Broker partners dates, the below subscription
plans are available. So if you need even
more data, you know, this is specifically for the brokers who are creating
the commercial accounts. But you've got the same authentication way
you can get started, we're going to show you
how to do all of this, so we're not going to
dive too deep into it. But just a quick overview, historically PI stock data. This is what we're
going to be utilizing on this investors Exchange LLC. Pto data, we're not
going to get into, but they've got
historical data for that, options and news data as well. Some people, maybe you'll be utilizing a large
language model, whatever it may be, maybe that's something that
you want to pull in. Not going to go through
the web socket stream. But then if you have any
questions, as always, they have this FAQ
section where you can go in and get any of your
questions answered.
17. Alpaca - Authentication: All right. Now
we're going to dive into the API reference, the trading API here on
the Alpaca dashboard. I'm going to go ahead and
click on this API here. It's going to bring me
over to the documentation. I'm going to click
on API reference. And the first thing
we're going to do is ensure that our account
is authenticated. So there's two things
that we need to get. Those are the the key
and the secret key. So I've showed you this before, but if you scroll down
on your dashboard, click regenerate,
you can generate new keys if you didn't
save your secret key. Now, once this secret key, once you navigate
away from the page, completely, or you click Hide, you're not going to be able
to get this secret key again so make sure you
store it in a safe place. I'm going to go into a blank Jupiter notebook and
start creating the code. Now, this time around, we're going to show the
code, essentially manually, but the videos that are
to I'm going to show you a shortcut that Alpaca
gives you to make it a lot easier to generate these
requests that you want. So the first thing we
want to do is import the requests library so that we can actually
run a get request. So all that is is
import requests. I want to shift
enter to run that. Now we need to get
a couple pieces of information here so we're
going to create variables. The first three
variables we're going to create are the endpoint. So we will just
call it endpoint. Oops. Start typing
your endpoint equals, and we're going
to wrap it in ts. Then we want to create the key, and we'll grab the key. And ops. And then the secret key. We'll grab the secret key. You're going to want
to put your key in your secret key somewhere safe. You're probably going to see me. Maybe just have it on the
actual upener notebook, but you're going to
want to store it in a safe area where
you can get it, and it won't be able to be
compromised by somebody else. So the next thing
we need to do is create for this specific
get request, the headers. And like I said, we're doing
this all manually this time, but you're going to see in
the videos moving forward. It's going to be a lot
easier to actually get this. So just follow me here, type and accept Clon
application Oops, we want this in as a string
application, slash Jason. And then we want
the next parameter, and the next parameter
is going to be the key. So we're going to take this, and we're going to
put that in quotes. And then that's going to be the key variable that
we created right here. Then the next parameter is
going to be the secret key. And if I can describe this, and we'll come over here, wrap it in quotes, and we
call that secret right here. And then we are going
to actually close off our headers dictionary here. We're going to run that, and then we're going to check to see if our connection
is authenticated. So we're creating a
variable called connection. We want request, running
a get request here, and the URL parameter
is equal to our endpoint variable and the headers simply is just
equal to our headers variable. Now, we're going to go
ahead and run this. Now, if we authenticated, we're going to get
a 200 response. If we didn't, we're going to get a 400 something response. I'm going to shift
enter to run that. You can see we did not
properly authenticate. That's because we need to add something to our end point here, you can see when
we're authenticating, we need this accounts at
the end of the endpoint. So we're just going
to go ahead and grab that. We're going
to add that here. We're going to shift enter
to run all these again, and you can see that we
got that 200 response, meaning that our account
is properly authenticated.
18. Alpaca - Accounts: All right, moving on
in the API reference. Under the trading API, we're going to move
to the accounts. What you'll notice right away
is this section over here. This is what I was
talking about how it's going to get easier
from here on out. You know, it's not there
in the authentication, but in the accounts it is. So the language might
default for you to Shell. You're going to want to go
ahead and click on Python. And what this is
going to do is auto generate the COB need in
order to pull from the API. So for the accounts,
what we need to do is go and grab our
key and our secret key, and then it's going to populate those into the header for us. We'll be able to just
copy that and run it. So I've got a Jupiter
notebook with my keys in it. I told you to store
those somewhere wherever you might have
them drop in the key, and you can see it auto generates down here
in the request. Grab the secret key, and then do the same
thing right here. Points already been added. All you need to do then is just go ahead and
copy this request. Come to your Jupiter
notebook, paste it. It imports requests for
you. It does all of it. It's got the Endpoints the URL. Your headers are created. We're going to shift
enter, and it's going to shoot back out your
account information. You can see it's
got my buying power and my cash and whatever
it may be for the account.
19. Alpaca - Assets: All right. Next, we're going
to move on to the assets. So this is going to be getting
information about assets. We're going to go ahead
and we've already got our key and our secret
key pulled in here. We're going to copy
this get assets. Request. We're going to come over to a blank
Jupiter notebook. Run this. It's going to
give us a limit issue. So what we need to
do is cut this down. So, as I mentioned before, there's going to be
more parameters beyond just these headers of the
key in the secret key. So, what we'll do is
for the exchange. We'll do NASDAQ. Ops. So that should, hopefully, and you can see it's not get added in the headers. It's getting added up
here in the actual URL. So let's copy this again. We'll come back, and
we will replace that. We're going to run it, and it's going to take a
second for it to load. And what we actually
might do is, I'm going to import JSN, and see if I can make this
look a little bit cleaner. So We will do JSI dot loads, response text, and hopefully this gives
us a cleaner version. Right. So it just makes it a little bit
nicer to look through, you can actually
see the exchange, all of the associated
information with each of these assets. So there is, if you know, specifically, you can see here, if you know the ID, the symbol, you can do it specifically
like that for the request. So if I did Apple, You can see it got added here. Apple. We're going to copy that. I'm going to come
back over here, and we will run that request. Now, let's do this
one more time here. Let's grab this json dot
loads and put that here. And it makes it look nicer. Now, you can see four
specifically, Apple, all of the associated
asset information you can get from this request.
20. Alpaca - Corporate Actions: All right, moving on with the
trading API API reference, we're going to come down
to corporate actions, and we're actually
going to come not to specific announcement
because you need to know the idea
of the announcement, but retrieve
announcements Returns, announcements, data, given
specified search criteria. So we already have our key in here in our secret key if you don't go ahead
and populate those, so it makes your
get request easier. The other thing, we
want to narrow this down using some of these
required parameters over here. So the first thing
that we need to do is answer what kind
of announcement? So we can put in a few of them. If you want, it says,
comma delimited. I'm just going to do
dividend announcements. Dividend. So you
just typed that in exactly as it's shown here.
You can even copy it. And then you're going
to do a date range. So it says since and until. Now, the thing to note here is the date range is
limited to 90 days, so you can't do this
for an entire year. But what I'll do is I'll just do in this specific
format right here, so I'm going to do the
first of this year. Until we'll do 1 March. How about that? It should be auto populating the dates in here. Yeah, you can see that. We've got the dividend, we've
got the sins and the until. So we'll go ahead and copy that, come over to a Jupiter notebook. We're going to paste
that, and it's going to re all of these
dividend announcements during that time period. Now, If you wanted it
for a specific symbol, like we could do it for Apple. Let's try that. I'm
going to copy it. I'll come down and
I'll paste it. Actually, what I'm going to
do is I'm going to do what we've done before and
do the JSI dot Loads. And let's just make sure that JSI is imported and
we'll shift enter, and you can see it
populates that nice. There was a dividend
announcement. Declaration date was February 8 for that effective the 12th. So you can see how
you can narrow the parameters down if you
want to or you can open it up. We'll actually make
this one look nice too here with all
of the different. I'm just going to copy this
to make it easier on myself. All the different announcements
for all of the companies. It's going to take a
second load and boom. We've got all sorts of
dividend announcements, so that's how the
corporate actions works.
21. Alpaca - Orders: All right. Moving on, we're going to get
into the order section of the trading API. We're going to go
through creating an order getting the orders, we're going to get requests
to get the orders and then deleting all of
the current orders. Once you pull your orders, then you can do things
more specifically. L get an order, if you
know the ID of it, replace an order by the ID or delete one specific
order by its ID. We're just going to run
through these top three here. So we'll start out with
creating an order. So places a new order
for the given amount. And request may be rejected
if the account is not authorized for trading or if the tradeable balance is
insufficient to fill the order. So we've already got our key and our secret key filled in. If you haven't made any
changes or switch devices, you should be good to go
here within your account. It started the request down here with the correct end point, got the orders on the end there. There is a few
requirements here. So for this first part to
create the actual order, wants to know a symbol.
We'll do Microsoft. And the quantity,
let's say we want to buy ten shares of Microsoft. The side, we either want to buy or sell,
we're going to buy. Type is either market limit, stop, stop limit, trailing stop. This is for stocks,
which is what this course is focused on
not on options or crypto. We're going to
leave it as market, which means whatever the
current market price is. That's where we're
going to buy it at. You should usually do this with some sort of limit order just to make sure
for whatever reason, a random Black Swan
event happens, you didn't get screwed over. But for just example purpose is beleaving it as
a market order, T and force is We could
do Good till clothes. So you can run through here the different
options that you have Day Good until cancels, my bad on the terminology
there. A few different kinds. We'll leave it as day for
now. And that should be. Now you can specify some of the other
information here for now. We're just going
to do a basic one. You can see down here if you
get some sort of response, either, 43 or 422. This is what they mean, just in case they're
shoot back at you. But we're going to
go ahead and copy the request that's
been created here. I'm going to come to a new
Jupiter notebook under Create. I'm going to go ahead
and paste that. You can see all of our
information was inserted there. I actually want this to be a JSN dot lows so
that it looks nicer, and we're going to go
ahead and run that. And Oh, I misspelled Microsoft, so we can actually
fix that right here. Misspelled the
ticker. So let's try that one more time. Runs. You can see that it was created, submitted, all the information that is applicable to
this specific order. If we come over to our
account, and we scroll down. You can see that
that Microsoft order was just created in
our recent orders. It was filled just a
few seconds ago here. So that's the very basics
of creating a buy order. We'll move on here, go
down to get orders. So this is going to pull any open orders that we might
have. We don't have any. So what we'll do is we'll
just on the dashboard, create one, so you can see it. So I'm going to create
one and I'll do it for I guess we'll
just use Apple again. That's just an easy
one to remember here. Maybe we'll do Facebook.
All right. We'll do MTA. Now, we're going to
create a market order, like I said,
actually, no, sorry, we're going to do
a limit order that way that the order is open, and we'll set the price below its current value
so that it remains open while we go to pull
all of our current orders. So let's review this. We're going to confirm
it. Confirmed, you can see that this
order is now opened. It's a limit by 500, so if the price drops
to $500 or below, then it's going to execute it. Its current price is What
was it around 50510, 25? So what we're going to do is we're going to
do this Git order. It's going to pull
all of your orders. I mean, if you want
to get specific, you can add some parameters. If not, just go
ahead and copy this, and we'll scroll down here to the Git section our
Jupiter notebook. We'll paste that to the
JSON dot loads again. Like I said, We do that, so it comes out nicer. And we'll run that, and we can see that we do have
a single order. If we had a bunch of them, there would be a list of them, but we just have this one meta
order that's open, right? So it's Ba open. The
limit price is 500. You just saw us do all of that. Now the last thing we want to do is we can delete all of
our current open orders. So if I come back here, all orders, this is
a delete request, attempts to cancel
all open orders, a response will be provided for each order that is
attempted to be canceled. If an order is no
longer cancelable, the server will respond with status 500 and
reject the request, which you can see
right here, failed to cancel. There's no parameters. We're going to go ahead
and just copy this. And you can see that that
order is still open, right? And once we run this, so we'll Jin dot loads. We're going to go ahead
and run. Status 200. We come back here. We
can see that the 200 to your multi status body and
array of objects that include. Okay. So we got a 200
instead of a two oh seven. Let's see if that
made a difference. It didn't. So it's canceled. So that's how you can create an order to
execute right away. You could do the same
thing. You could create a limit order from Python
if you wanted to as well. Just did it on the
dashboard to make it easy, how you can pull your
current open orders, and then how you can
delete your orders. As I had mentioned at the
beginning of the video, you can do it by specific ID. So if you knew the ID, for example, here's
the asset ID, if we wanted to just do this, we could take this, and
if it was still open, if we wanted to delete by this, we could just type in
the order ID here, and that would work for us. But we had just done it we
deleted all of our orders. So that is the basic
foundation for creating, getting and deleting
orders on Alpaca.
22. Alpaca - Positions: All right, next, we're
going to cover positions, the trading API here. So the two that we're
going to go through here is first all
positions open. A all open positions. What this does is it just
goes and fetches any of your current open positions.
Close all positions. The other one we're going to do, which we'll do just that, close all of your
current open positions. If you specifically want
to get an open position, and you know the
symbol or the ID. You can go ahead and
do that specifically. Same thing with closing
it specifically, For this example, all we're
going to do is just all open, get the information,
close all of them. We're not doing anything
with options here, so we can just
ignore that for now. But let's start off here with the all open positions.
It's easy enough. You've already got your key and your secret key placed in there. Go ahead and copy this request. Come to a new Jupiter
notebook. Paste it. We're going to json dot loads, Shift Enter, run that. What this does is it fetches all of our current
open positions. So for Apple, we currently
have two shares, and we can verify that
in our dashboard here. Yeah, we have two
shares of Apple, and it should say for
Microsoft, we have ten shares. So let's come back here. Microsoft, Quantity
available is ten. So that did exactly as
we were looking for. Like I had said, if
you specifically wanted to close one of these, what you can do is
take the asset ID. So if we just wanted to only
close our apple positions, we can go ahead
and copy that and bring it over to
the documentation, and we're going to
just close Apple here. Because we could do that, and it'd be all set to go for us. We could copy this and
then paste it and run it. But we're going to actually
close all of our positions, so there's nothing for
us to do, cancel orders. We don't have any orders, so I don't even
know if we need to it doesn't look like
it's required field. Cancel all open orders before
liquidating all positions. You could do that if you did. And maybe it's safe
if that's something you want to do to just
go ahead and put true. So there's no other parameters. We'll go ahead and copy this. We can see we currently have
these two open positions. We're going to go ahead
and it's a delete request. And as always, we're
going to make it look nicer with the
JS on dot loads, when it returns
the value, run it. Now, it should show us that
these positions are closed. So we got a 200
status for Apple. We got a 200 status
for Microsoft, meaning that they are closed, and you can see our Microsoft just finished closing there. So we have no more
open positions, and that's how the positions
API portion works.
23. Alpaca - Portfolio History: Alright, moving right along. We're going to get into
portfolio history here. So this is a get request. Returns T series data about equity and profit loss of the account in
requested time span. Now, you can specify
the time frame here. Looks like none of these
are required fields. So we're going to go
ahead and just grab this. We've already got our key in our secret key in here if you don't drop those in there so that they populate
in the headers. We're going to go ahead
and copy this data, come over to a new
Jupiter notebook. We're going to change this
print to JSN dot loads, and we're going to run this. We got to import JSan. So make sure you import
JSN, now we rerun that. Now this is going to give us time series data on the account. This is showing these are actually times right
here, time stamps. What we're going to
do is convert this into an actual usable list here. We'll take this data and we will create a data frame out of it
as we had done earlier. So actually, what we'll have
to do is import Pandas. If you don't know
how to do this, or you're having
trouble with Pandas, make sure you revert back to the previous lecture about it. But pd data frame, and we have to a PD, importing Pandas as PD, and we're going to
take this data, and we're going to
shift to run it. And then it should have created a nice data frame for us that
shows the timestamp now, what we would like to do
is actually convert this. This is second since
a period in time, It's standard
practice for Python. We can convert this time
stamp to a date time. We're not going to do
it in this lecture. But this is day by day
the value of the account. You can see this is the base value that
we started out with. But as time went on, you know, our equity went for 50,000
down to 40 9998 and so on. Up until today in
one day increments, you can see, that's defined
by the one day there. So the profit or loss
is actually decreasing. We had Apple over a short period of time here
and it decreased in value, so that's what
you're seeing there. So this is the
portfolio history.
24. Alpaca - Watchlists: All right. Moving right
along here to watch lists. There's a bunch of different options for watch lists here. You can get really deep in
the weeds with specifics. All we're going to do here is actually create a watch list and then get the items from it. You can create a watch list on your dashboard if you wanted to. We're going to
actually just go ahead and do it utilizing the API. So I'm going to come back
to the documentation. There is a required
parameter of the name. This is the name
of the watch list, so you can identify it
if you have multiple. I'm just going to call
it Watch list one. Then the other thing is
to you can just create the watch list without adding
any specific stocks to it, but that's not going
to do much for you, so we're going to create a
separated list of symbols. So we're going to do Apple, Microsoft, Facebook, and you can see these
populating here. We've got the name and the symbols populated in
this Palo dictionary that gets hold in for this response to go ahead and post,
which is to create. We're going to copy this then. As long as you have your key and your secret key in there, just check those two things. Come to a Jupiter notebook,
and we'll paste it. As always, we want to import JSan so that we
can San dot loads. The response here, and looks like we were
not Microsoft asset, not found Apple, Microsoft
Meta. All right. Maybe we have to let's. Okay, so it looks like it's not a common separated
list like this. We need to do it one piece
at a time, Microsoft. And let's add one more. Let's see if this makes a
difference. Let's hear it. How is our code set up? Yeah. Okay, so it's
separating it. Instead of it all
being wrapped in the same exact quotes,
it's going to separate it. So we can actually even do it
right here if we wanted to, but for example purposes, I'm going to go ahead and
do it the proper way. And it looks like that's
populated correctly. Now, let's go ahead and copy this and replace
this current code. We did already import JSN, when we ran the last one,
but we'll do it again, and we will JSI dot loads, and we run this, and we
should be good to go. Now, I created this watch list, Watchlist Watch List one. It's got Apple in there. It's got Microsoft in there,
Microsoft Corporation, and it's got Meta, which is the parent
company of Facebook. So now if we come over
to our dashboard, maybe we have to give it
a refresh here to see the watch list If
it's not showing up, we'll just have to go
ahead and pull it. Yeah, I might just
be a little bit delayed here on why
that's not showing up. So we will go ahead and
just pull the watch list. Using the G, so get
all watch list here. There's no parameters to
put in as long as you're key in secret in there.
We're going to copy that. We're going to come over here, and this is going to
be our get watch list, and we will paste the code. Jonas. We'll run that, and it's going to
return our watch list, which is Watch list one, and it contains Oh, this was a previous one
we had created here. So sorry. Wh list one is the one that
we had just created. It gave us the account ID. So if I take Sorry,
not the account ID. The actual watch list
ID if I take this ID, and I wanted to get
watch list by ID. Then this is where
I can specifically pull the watch list
that we just created, and then that should give
us the information on that. So let's try this one more time. We're going to get
watch list one, paste this JCs Shift Enter. And there you have it so that
one we had just created, you can see Um, we are pulling
specific information on that watch list as
Apple Microsoft and Meta.
25. Alpaca - Account Configurations: All right. Moving on to the
account configurations here. This is going to be very basic. So just as it says, get the current
account configurations values in order to get that, as long as you have your key and your secret key
already in here, if you don't, go ahead and
grab those and put them in. Come down here, copy the request code that's
automatically generated for you. I've got a Jupiter
notebook open. We're just going to go ahead
and paste that in there. We'll shift enter to run it. It's going to provide
you with the values. I'm actually going
to chase that load. So it looks nicer,
and it's going to go ahead and provide you with your account
configurations. So, for example, fractional
trading is true. So what fractional trading is is Alpaca allows you to buy
a share of something. Where you buy a piece of it. So a specific dollar value, instead of having to
buy the entire thing, so say there's Apple is
trading at $200 a share. And you only want to
buy $50 worth of apple. You are allowed to buy a fractional portion
of an apple share. It'll increase in value the
same with the percentage, but you'll obviously just own
a smaller portion of that. Let's go back to
the reference here. Check out this account
configurations. This is where you
can actually update or configurations
on your account. So if you wanted to
change any of these, you can go ahead
and change that. So if I wanted to change
my fractional trading to false on my account. I can go ahead and update this field here and
come back here, and we will paste that, and it's going to return
the updated value to you. So if we run this, now it says, fractional trading is false, and I'm just going to go
ahead and change that back to true because we want to be able to use fractional trading and boom
it's true. So that is the count configurations,
pulling through your current
configurations and then updating any of the
configurations if you need to.
26. Alpaca - Account Activities: All right, moving on
to account activities. You can see your retrieve
account activities. It returns a list of
activities on your account. So what we'll do is we'll just show you exactly what
we mean by that. You can type in parameters, specifically if you want to, if you wanted to find
your activities, between a certain date range, you can specify that here in
any of these query params. But for now, we're just
going to pull everything, so make sure you got your key, in your secret key in there. It's automatically going
to update this endpoint, and all you need to do is
copy this get request here. Come over to a Jupiter notebook. We do want to import
JSN so that we can make it look nicer,
and then we'll paste it. You can see that everything's
already in there. We'll exchange print
with Jason dot load, so it looks nicer
when it returns, shift enter to go ahead
and get that to return. All of our account activity, and you can see this is
the stuff that we've shown you previously filling
certain transactions, so we had that cell
of the Microsoft. More cell Microsoft,
More cell Microsoft, we sold it bunch of them. I think maybe we had like five or something like
that, sell the Apple. We were getting rid of
everything on the account. We were going through one
of the prior lectures. If you come down, there is a few other activity
types in here, besides just the fill
that we have here, like this activity type, JLC. So let's say that we only
wanted to get our fills. We can go ahead and come over
to this option right here. Retrieve account activities
of specific type. So, this activity type here, you can see those labeled, within each of these items in the dictionary that
was returned here. So we just want to
look at the fills. So we'll go ahead and
type that in here. It's going to
automatically update. You can see that updated
here in the endpoint, and we will go ahead and
copy this and JSN dot loads. Return that, and then
it's going to give you only the fills, you can see that that
other activity type the J&LC is no longer
being displayed anymore. So this is how you can retrieve your a
account activities.
27. Alpaca - Calendar: All right, moving on
to the calendar info. So we're going to
do a request to get calendar info, what this is, the calendar API serves
the full list of market days from 1970
all the way out to 2029. It can also be queried
by specifying a start or an end date right here if you want only a specific
period of time. In addition to the dates, the response also contains the specific open and closed
times for the market days. Taking into account
early closure. So we're going to
go through that, take a peek at what this
is going to give you, in case for whatever reason, you need to know if there are certain days where the
market closes early. So make sure you've got your key and your secret
key already in here. It's going to go
ahead and create this get request
for you as always. We're going to copy that, come over to a Jupiter notebook. We're going to import JSN, just so that we can ensure the response we get
is nicely formatted. We're going to go ahead and
paste and then exchange that replace that print with Jason Dt Loads.
Go to print it. It's going to take
a second because there is a lot of dates here, and you can see it does date
back all the way from 1970. This is January 2 of 1970, and it goes all the way forward into 1973 is what
it's displaying here. If you want to get
more recent data because this is such
a large return, you're going to have to specify the dates that Jupiter notebook can only
handle so much here. What we will do is, since you see over and over
again, the market's closing, it's opening at 9:30 A.M.
And it's closing at 4:00 P.M. We're going to go ahead and look to see if there's any dates where it doesn't
close at that time. If it doesn't Yeah, if it doesn't close
at that time, then what's the point
of even using this? So what we'll do is within
our same cell we have here, we're going to
create a four loop. So we'll do four item in and we're going to use
that same JSN dot loads. So we're going to loop through the JSN data
that was returned. And we want to see if the
close is not equal to four. So why why would
they return this? I every single day that the markets open,
it closes at four. So we'll do if the item. So each time it loops
through the item, and the specific piece of the item that we want to
look at is the close, and we want to see if it
does not equal that 1,600. It has it in as a string. So that's how we're going
to create it as well, and we will then open that up. And if it does not equal
that 4:00 or that 1,600, we want to print
the entire item. So we can see all of the
applicable information. So let's go ahead and run this. It's going to go
ahead and run it. And as you can see,
there is a ton of dates returned for each
year going all the way until 2029 as to where the close date
does not equal to 1,600. What does it equal to?
It equals to 1:00, 1:00 P.M. That's Eastern time. And if you take a look
at the dates for this, it's all because of holidays. So this is going to be, I assume Black Friday, so Black Friday every year.
There's an early close. Right around 4 July, there's an early close, and then right around Christmas time, there's
an early close as well. So it varies from year to year. I think they've changed it. I could be wrong on that,
but just based off this, that's what it kind
of looks like. We can see in this year
2024.'ve got three of them. So the day before 4 July, it closed at one. I believe this is the
day after Thanksgiving, so Black Friday, closes early, and then Christmas Eve, it closes early as well. So that's how you can utilize
the calendar feature.
28. Alpaca - Clock: All right. The next
item to get into is the clock G Market clock. Info, this is very basic. The clock API serves the
current market time stamp, whether or not the market
is currently open, as well as the times of the
next market open and close. And you'll see when we go
ahead and do that get request, it's going to give us
that exact information. So make sure your key, your secret key, and
there is always. It's automatically
going to generate the endpoint, this URL. Go ahead and copy that, head over to a Jupiter
notebook, want to import. Jason so that we can make this look nicer when
it returns to response. And as always, Jason
dot loads, shift enter. We're going to run
that, and it's going to return the current
market times stamp. So today is September 12, 2024. Current time is 11:54. I'm an Eastern time zone. This should return the Eastern
time zone, no matter what. You'll have to verify
that just to be sure. But I believe that's the case. The market is currently open. It's Thursday at, like I said, 11 54, so it's open. The next open is tomorrow, the 13th, which is
a Friday, at 9:30. Closes at four, next close, is going to be today's close, which is at 4:00 P.M. So that is the
clock get request.
29. Alpaca - Crypto Funding: All right. The last part of this trading API reference
is the crypto funding. As I had mentioned,
prior to this, we are not going to be
getting into crypto of this, so we're just going to
briefly go over it. If you're interested in
this, I would suggest doing further research to figure out how exactly to utilize this. You can use the
skills that we've given to you with
these other requests. This is a bit more complex. There's a ton of different
Gits posts and deletes that you can go through for
funding your actual wallets. If I'm going to come over
to the dashboard here, you can see that there are cryptos available.
So the symbols will be not just BTC for Bitcoin, but USD at the end. That's the entire symbol, and you can see it
provides that label on it, and it'll give you
the price of it. I think ethereum is ETH, USD. Yeah, so it's going to
provide you that as well. So you can see that it
is an option to purchase crypto and to fund your wallet
and all that good stuff. But we're not going
to get into that. So that will wrap up the trading API reference
portion of this course.
30. Alpaca - Stocks - Historical Auctions: All right. Now we're
going to move on into the Alpaca market
data API section of the API reference here. Starting with the stock data. This is going to be what we
pay the most attention to. There's a ton of
different git requests. We're just going to
start at the top here with the
historical auctions. So the historical Auctions
endpoint provides auction prices for
the stock symbol between the specified dates. So you can see, ensure you have your key and
your secret key in here. If you don't, you can
always regenerate those. If you come to this
front page here, click regenerate
on the dashboard. Grab those, put those
in here so that they auto fill within the request. Just makes less work for you. While you stay signed in, it's going to keep
those auto filled every time you click onto
a new section of the market or the API reference. If you want to continue,
if you have codes stored somewhere and you
want to continue to use the same key in secret key, make sure you keep those
in the safe place, so you can just grab them and not have to worry about
updating your code. Let's start out here
with the top parameter. This is the only required one, which is the symbol or symbols. It's a comma separated list. You can see they
give you an example of that with Apple and Tesla. We're going to we'll do Apple
and we'll do Microsoft. And we'll do Meta as well, which is Facebook's Pad Company. So that's the only required one. If we wanted to specify
the date, we could. The default is the beginning of the current day.
You can see that. The default for the end
time is the current time, if the fee does not sip, or if the user has
a subscription 15 minutes before the
current time otherwise. Okay? There's a limit, so you can limit the
number of records returned based on us just
doing the current day, we're not going to
get a ton of records, so we don't have to
worry about that. You can probably ignore
these other ones. I mean, if you really
want to identify the currency, go ahead. Otherwise, we're
just going to copy the request that AlPACAs API
reference generated for us. Come over to a notebook, and you can see how it's
messing with it already. We're going to go ahead
and first import JSN, and then we will copy or we will paste that get request that
we just took from AlPACa, shift enter, to run it. Let me actually change this to JSN dot load, so it looks nicer. And then what it's going
to do is it's going to show us the auctions
for each of these symbols that we specified Apple. You can see the apple
price $2,222.87 MTA, showing the price 52575 on the
12th here, which is today. And then Microsoft, as well, you can see that it's $427.09. So that is the historical
auctions API poll.
31. Alpaca - Stocks - Historical Bars: Alright. The next
lecture we're gonna get into here is on
historical bars. The historical
bars get requests. This is more than likely the
data that you'll be using. It's what I utilize. It has those key pieces that you want when
you're analyzing data, and I'll show you
what I mean by that. When I actually pull it, but the first thing we'll do
is just set up that pull. So we want to type in symbols. This is a required parameter. So we'll do Apple and Meta. Which is once again,
Facebook's parent company. The time frame is
a required field. So we'll do and it gives
you these options here. We're just going to do one day. So we wanted to pull whoops. We wanted to pull for one day. And then we'll come
back and we'll fill out more of these parameters in a sec to give you an idea. But for now, we'll just run this in a blank Jupiter notebook. We want to import
JS on as always. And then we're going to
paste that request in there. And we want to replace
this with json dot loads. And we click Run. And now what it's going to do
is it's going to run. The default is just for a day, and it might even specify that. Yeah. The default for this is the beginning
of the current day. So that's why we're only going
to get one day's worth of bar information for
each of these for Meta, and for Apple. But these key pieces here, this is the closing
price of today. This is the high price of today, the low price, the open price. This is the time that they
actually logged it at. So you can see that
that's the close. This is the volume, and then this is the
weighted volume. So what I want to do
is actually go ahead and pull a time frames worth
of this specific time frame. We'll do the beginning
of this year. Till the end of not
the end, but today. So we'll put in tomorrow's date, which is 13 September, the other thing that it might
give you an issue with is, if this is on SIP, you're going to want to
make sure that you put in the investors Exchange IEX. And then once you have that, go ahead and copy this, and we'll come back over here and we're going to replace this. And since you've
already imported J on the Jupiter Notebook, You technically don't have
to re import it again. It's already ran unless
you restart the kernel, but you don't have to go ahead and type that out again. So we're just going to run this. It's going to provide that. We need to changes
to Jon dot loads. I got to get request. And you can see it starts with the first trading day
of this year for Apple, and that is 2 January here, and it provides
you all that data. Now, If you want to take this data and put it
into a nice data frame, which I would highly suggest it makes it easier to look at. What we can do is we've shown
this in previous lectures, but we want to
import Pandas as PD, and then we want to
create a data frame. So I'm going to create
two separate data frames, one for Apple, and the
other for Microsoft, which are Meta, me, which will be starts right here. Yeah, it's in the
middle of there. So we want to create
Apple as a data frame. How we do that is we give it the data frame variable name. I just have Apple symbol, and then the underscore the App, you'll see me do that a lot
throughout this course. And then we have to type in pd dot data
frame, open it up. And then we need to
put in our JSN data. So Json dot loads. The same thing that
we were showing above response dot text. And then the other
piece of it is it starts this dictionary with this bars and
then goes into this, so we need to go into the
dictionary type out bars, and I'll actually
just show you what it looks like when
we don't do that. So, I'm missing a
parentheses there. So if I just ran it like this, you can see that it doesn't split it up the way
that we wanted to. It's taking bars as the top
section of the hierarchy, and then just creating
two records out of it. So if we 2 bars that bars key. And then we run this.
This will look like this. Now it's going to grab all the
records for both of these, but not split up the data. We want these to be two
separate data frames where each column is
separated for the clo, low, and so on. So then the last part
of it we have to do is specify in this
diary, the symbol. So if we run that, now you can see this is the Apple data, and we're going to go
ahead and just copy this. And we'll do the
same thing for Meta. So all you have to
do then is just replace the symbol
in the dictionary, and then the variable name. So we'll run that.
And then let's run MEDA here and you're going to see this price change
right now it's 185, at the beginning of
the year for Apple. For Meta, it was
346, now it's 525. So that is a basic overview of pulling data for
historical bars. The one thing you might notice, depending on how big your date ranges is at the bottom here. For us, it says next
page token none. That's because everything was
able to fit in one request. But if you have a
large enough request, you're going to have to iterate through multiple pages
and pull that data. We'll show you that in
a different lecture. But for now, we just wanted to run through
and show you what it looks like to grab that
historical bar data and start to organize it.
32. Alpaca - Stocks - Next Page Token: All right. In this lecture, we're going to cover something
that I had previously mentioned the next
page token feature. So when you'll need to use that is when
you send a request, and you only get part of the information
that you're looking for. You'll need to loop through
utilizing a next page token to get the next page of data until there
is no more data. So, I've already
got this coded out. We're going to run
through all of it. So if you want to code along, I'll try to go slow enough so that you can
follow what I'm doing. But there's just a lot here so I want to ensure that I
didn't miss anything. So the first thing
that we're going to do is we're going
to go ahead and grab and the API reference here, we're going to go ahead
and grab the request. So we'll start off
with the symbol. I'm just using
Apple. I'm utilizing one symbol for the first go
around for simplicity's sake, in the future, as you get
more complex data polls. You can expand upon this, but for now, we're just
going to use Apple. The time frame, we're
going to do one day. Of course, make sure
that you have your key and your secret key
values in here. I expanded the time frame from what we were utilizing
the prior lecture. I did the beginning of 2020, all the way until today's date. And then the last thing
that you'll need to do is if this feed is showing SIP, you want to make sure unless you have a premium subscription, you want to make
sure you change DEX, or you're going to get an error when you go to run the request. So So you have all
that information. Go ahead and copy
this response here. And we'll come over to
a Jupiter notebook. I am just in the same
Jupiter notebook I used for the prior lecture, but you can just open a
blank one if you want to. Like I said, we're going to
show you all the code here. So I'm going to replace this, and what we're going to do is import JSan as always
and JSan dot loads, and we're going to shift
enter to run that. And it's going to fire
back with us the data. You can see it
starts in 2020 here. And if we scroll down, you're going to see that
there is a next page token. So what that means is we didn't get all the
data up to today. You can see it stops at July 7, sorry, July 17 of this year. But it provides the
next page token, meaning we need to
utilize this token, run another request to
get the rest of the data. So just to break that down a little bit
further so you can see exactly how the
dictionary is separated. I'm just running a quick. You can choose to do
this if you want to, but I just figured for visualization purposes,
I want to show you. I'm going to run a fore loop in this response to show you the highest items
within the dictionary, the dictionary of hierarchy. That first one, of course, is going to be the bars,
but then the second one, which we've pointed to before, but didn't get into is
that next page token. So shift enter to run this. You can see we've got the bars, which is here in the dictionary. And then on the same hierarchy, we have, at the end here
this next page token. So that's just what we
were showing you there. Now, I want to show you how the next page request is done. So we're utilizing
essentially the same exact, request that we have up here, but we're doing it with
one extra parameter, which is that next page token. And we can see that next
page token is here. We're going to go
ahead and copy that. And then we can actually come
over to the API reference, and there is a field where we can insert this page token and it's going to
update our Git request. So I'm going to
paste that in here, and you can see that
this endpoint was updated with the page token, and it has that page token
value that we had just pulled. So I'm going to copy this and then come back
to our Jupiter notebook, and you'll be able
to see when I paste this and we Jason
dot loads this. This is going to show it should show that second page of data, which is beyond, I think it
was July 17 of this year, all the way until today's date. So we're going to shift
enter to run that. I ran and you could
see it starts, just like I said at the 18th, and then it's going to
give us all the way until the market hasn't
opened yet today, it's going to give us all
the way until yesterday. So the close price yesterday
of Apple was $222.85. The high was $223.50
3.5 cents and so on. So that's how that works. Now, the way to do it, whereas if you have a bunch of pages is you essentially
want to loop through, Um, so at the bottom
here, like I said, just try to follow along
with what I've got. It might be a lot. You might have to
pause the video. Um But I would suggest trying to code this
out yourself as I'm doing it. So we're going to start with
from the beginning here, the initial request
that we did at the top import request. We are going to utilize Pandas. So import Pandas PD. That's just the alias that we utilize when we call
the Pandas functions. And then if you haven't
already import SN. This request is
what you should be getting originally from Alpaca. I'm going to get rid of this. It'll just be this
original request that doesn't have the
next page token on it, and you can copy
that, and you can start right here, paste that in. And then it's going to
return to you that response. We're actually going to
set this response equal to a variable so we can hold it and utilize it
within our wile loop. So I just chose the
variable name of Json Bars. You can choose
whatever you want, whatever makes the
most sense to you. But we are setting
the original request, which is this in the
response equal to variable. We'll utilize that in a sec. We want to create an
empty data frame. So I just created the
variable name of DF. It's pretty standard. It's
equal to Pd data frame. It's a blank data frame. The reason we want to do
this is because we are going to be adding to the
data frame while we loop. So we need somewhere to add this data that we're
pulling through to, and that's an empty data frame. The last thing is
the loop dependency. So we're going to go
ahead and actually, this loop dependency
we don't need. I just realize, so you can go
ahead and just remove that. So what we're going
to do is create a wile loop where While true, it's going to continue to loop. So until it's broken
essentially is what that means. We're going to continue
to loop through. So you can end a while loop
using the phrase break. We'll get down to that
in a second here. But while true, we are going to first get
the current page. So we had ran this request. This is the original request. We need to get that data and create a temporary
data frame out of it. So I labeled this
data frame as Ad DF. That's just For now, you can give it any variable
name that you want to, but you have to
label it something. It's going to get
recreated over and over again as you
create new pages. So the first page, we're taking this temporary
data frame of Ad DF, we're taking that we should
utilize this JSN dot bars. And we're going to go into the bars section
of the dictionary, and within that, we're going
to go into the Apple symbol. Like I said, we're only using
Apple for this example, but we need to specify
where we're going in, especially if there's
more than one symbol. So this is our
temporary data frame that's getting created. It's going to look just like this data frame that
we have created above, but it's only showing up
until 17 July of this year, just like this request
is showing here. So that's our
temporary data frame, and what we want to do with
that data frame is we want to add it to our
empty data frame. So our current data
frame that we have, which is going to be
our final product is there's nothing in it. We want to re establish it. So we're taking the new value of DF is equal to and what
you want to do is PD, which is the Pandas
function dot CAT. What KCAT does, the KCAT
function allows you to essentially do that catenate
two data frames together. So we want to take first
our empty data frame, and then add to it the Ad DF. So we want to add all of
the values that we got For the first page
of this request. So that's been done. Now the new data frame has
the first page worth of data, then we want to
create the next page. So the first thing we
want to do is check if the next page token
is equal to none. If it's not, then that means that there is data
on the next page. If there is or if the next
page token is equal to none, then we're going to break it. That's what I was talking about. So For now, the next
page token is equal to JS bar or the JSI bars within the dictionary,
the next page token. You can see that here. The next page token, it's
going to be a value. Whatever that value is,
we need to take that, and we need to insert
that into the end point. Now, it's going to
change each time. So with that happening, what we need to do is we
need to create a variable, which has already been done
of next page token and add that as part of the
string of the request. So this request here is just
like I had shown you prior. When you add this page 123, within the URL here, you're going to see that
page token is added, and then the value
is being displayed. That value that
we want to insert changes with each
loop because the next page token value
changes on each page. So we will need to within this, create a variable add it
to the string next page, it's going to run the
proper page then. We're going to re establish the JSON bars variable with the new request
for the current page, and then it'll start
to loop over again. Like I said, if
once this is done, the as it's going through
this if statement, I first, this next
page token is none, it's going to break and that's
going to be the end of it. This has already been done. If not, then what will happen is we're going to establish the JSON bars
value for the next loop. So it's going to go
ahead and loop around. So I know that was
a lot, like I said, if you need to pause
it or slow it down, whatever it may be,
by all means do so. But at the end of
it, we should get this data frame that has
combined each of the pages. In this instance, it
looks like there's just one additional page
to the current one. But if we go ahead and run this, our code should work to where
it gives us, of course, our start in 2020 here, and this may be a limitation on the period of time
that you can grab for, and that's why I didn't
start at the first. I'll have to look into
that. But the biggest thing here is that you can see now we have grabbed all the way up until
yesterday's date, all the values for it, getting our closes, highs open, lows, whatever it may be, the pages have been
combined together. So in a nutshell, that's how the next
page token works, and how you can ensure that
you're grabbing all of the data and not just getting a part of it when you're going to do your analysis. It may be that you think
you're grabbing all of it without realizing that there is additional pages of data that need to be grabbed.
33. Alpaca - Stocks - Latest Bars: All right. Next, we're
going to get into the latest bars request. So this is the latest multi
bars endpoint returns the latest minute aggregated
historical bar data for the ticker symbols provided. So it's going to just
do exactly as it says, provides the latest
bars here. So we're going to use Apple, and we need to change the SIP
IEX, based on our account. We've already got our key
and our secret key in there. The request is created. This is a pretty simple one based off of everything
else we've done before. I'm going to go ahead
and paste this, import JSN, change
this to JSN, dotads. And then it should give
us the latest bar. Now the market's not open, so it might give us something
from yesterday, but shift enter. We're
going to run it. Right. Yeah, so it gives us
from yesterday. That's okay. If the market was open, which it will be in 7 minutes, it would just give us the latest bar, including, you know, all the close high open
and the volume metrics. But for now, we just get
yesterday's end of day numbers. So that is the latest bars.
34. Alpaca - Stocks - Historical Quotes & Condition Codes: All right, for this lecture, we're going to combine two
of these get requests here. So that's going to be looking at the historical quotes
and the condition codes. So the historical quotes, it's the historical quotes, API provides que data for a list of stock symbols
between the specified dates, and it goes on the
return results are sorted by symbol first, then by time stamp. So it's in chronological order. This means that
you're likely to see only one symbol in
your first response, if there are enough
quotes for that symbol to hit the limit you
requested on that request. Situations, you would utilize
that next page token. If you haven't
reviewed this lecture, I would go ahead and do
that so you understand how that works to ensure
you're getting all the data. We're going to keep this
very basic for now. So we're going to go ahead and get historical quotes for Apple. We are going to specify a date so we get more than just today because the default is just the beginning
of the current day. So we're going to do just
the first of this month, and then we'll do it
through yesterday. In my time zones here. So we'll need to change
the SIP to I X as always, and then we'll see if that
is good enough from now. So as long as you have your
key in your secret key, go ahead and copy the request. We'll head over to a blank
Jupiter notebook here. I just have the markdown code split up here so I
can separate the two, but we will go ahead
and paste this, and we want to import
JSO so that we can make this look nice and
easy to understand, and we will shift
enter to run that. Then it should
give us for Apple, the historical quotes here. So you can see it
provides you with information on the historical
quotes when it was. But more importantly
for this lecture, this is the condition code. So this is an R,
and you'll see what that means in a second here. So I'm going to go ahead and now run the condition codes request, so we'll come back up here. And you can see that
you have to select between two of these parameters. We're just going to
do it for quotes, since we're looking at
historical quotes here. And then you can leave this the one character
name of the tape. It's going to auto
generate the request. I'll come back here and grab
that. We'll paste that here. We already have
in this notebook. The JSN library imported, so you don't have to
add that in again. But we're going to do the
Json dot load Shift Enter. And you can see it gives you
all the condition codes. So this R here that
we were showing you up above for each of these
quotes that you're seeing, that means the regular
market maker open. So that is how you can understand the information within these historical quotes, what those condition codes mean.
35. Alpaca - Stocks - Exchange Codes: All right, so real quick, similar to the prior lecture, there's also exchange code, so this returns the
mapping between the stock exchange codes and the corresponding
exchange names. So this is just going to
be there's no parameters. If you've got your key
and your secret key, go ahead and grab that, we're just going to
utilize the same your notebook, we were in prior. We can go ahead and paste that and changes to the
JSN dot loads, and it's going to return all of the exchanges and
their key, their code. So we were using the
parameter for the X. So that's V. So if we come up here and look at
those quotes again, you can see that V
is displayed there. So real basic, but those are the exchange codes and
what each of them mean.
36. Alpaca - Stocks - Latest Quotes: All right. Moving right
along to the latest quotes. So similar to the latest
bars that we showed you, the latest Multi quotes
endpoint provides the latest bid and ask prices for each
given ticker symbol. Now, this is going to show
the actual latest quote. Now that the market is open, when we had showed you
the bars, it wasn't, but we're going to
do it for Apple, ensure that the fee
is the IEX here. The investors exchange,
and then you can go ahead and copy this and come over
to a blank Jupiter notebook. Paste that in, import JSon so that we can use
the Json dot loads. And then it's 945 right now, when we run this, it
should give us exactly. So this is giving us
a quote for 9:45 A.M. This is displaying,
I believe, in UTC. So that's just the
standard for a server, but it is 945. If I run it again, I should see the seconds
change there exactly. So it's at 40 seconds, and it's giving
you the ask price, $2,222.49 and the
bid price, $222.43.
37. Alpaca - Stocks - Snapshots: All right, next, we're going
to get into snapshots. So the snapshot endpoint for
multiple tickers provides, and that's comms separated. The latest trade latest
quote minute bar daily bar, and previous daily bar data
for each given ticker. So it's essentially
a combination of a bunch of things that we've already gone through here. So we're just going to run
it for Apple, the feed. We're going to make
sure it's IE X. The investors Exchange, and we as long as the are key
and secret here in there, we will copy this request
that's auto generated, come over to an empty
Jupiter notebook. Paste that. Going to import JSN. And then we'll walk
through this and see if it gives us exactly
what it says it does, so we'll shift enter to run. There's the daily bar, so I believe it said, it gives you the daily bar. We've got the latest quote. So it says, the latest quote. Should have the latest trade. Yep, that's the
first part of it. Latest trade data. It says that right here. The minute bar and the
previous daily bar. So minute bar daily bar. All of that is what's
displayed here with the applicable information. So if you're looking to get
all of that data in one spot, this is where you can
use the snapshot tool.
38. Alpaca - Stocks - Historical Quotes & Latest Trades: All right, to conclude this
section of the course. We're going to go through
the historical trades and the latest trades. The rest of these requests
are all single symbol. So for a lot of these, we really did just
use one symbol. So it's essentially
the same process. Just utilizing the procedures that we've shown you throughout this entire course so
far for a single symbol. I'm not going to go
through each one of those, but if you click into m, I'm sure you can follow
parameters to run those requests. Now, the historical
trades will run first, so the historical stock
trades API provides trade data for a list of stock symbols between
the specified dates. Let's do multiple symbols
for this one, might as well. Obviously, if you need to use the next page token,
go ahead and do that. The default for this is
just the current day, so we're going to run
it for this month, so far, and we will do
24 today's the 13th, and we will get this
historical trades data. We want to make sure that
we change the SIP to IEX. And we can go ahead
and pull this request, as long as you have
your key in secret key. We'll come over to a blank
Jupiter notebook. Paste that. We want to import Jan and
then change this to JS, shift enter to Run, and it's going to give us
those historical trades. You can see there. There's the next page
token at the top. Uh, if you need to go
ahead and utilize that, but for Apple, the Apple trades, it's going to give you
a bunch of information, the timestamp for these
trades. You can see. These are all trades
that occurred. Right as the market open, this is in UTC time. Make sure you're paying
attention to that. Depending on how much
was given to us. Yeah, we're not going to be
able to see the rest of it. We have to paginate through
in order to get we're only at 9:49 on this
for Apple trades, and that's on the
third of this month, which must have been
the first trading day. So, um For time's sake, I'm not going to go
through and paginate it, but if you need to, you can either refer back to
the next page token lecture, or if you know how
to do it, just go ahead and do that
to make sure you can pull all the data for
these historical trades. Now, we'll get into
the latest trades. So let's come back over to the API reference
to Latest trades. The latest multi trades endpoint provides the latest
historical trade. Data for multiple
given ticker symbols. We'll use Apple and Meta again. And then the feed, we
need to change dX. And then we'll go ahead and copy that request. We will paste it. We don't need to
import Jason again, since we've already done that within this Jupiter notebook, Jason dot load shift
enter to run that, and it's going to give
us the latest trades for each of these symbols. So Met's most recent trade. You can see it's 1030 right now. This is the most recent trade. What the price was
at for that trade, $522.04 and for Apple. Um, it's about the same time, just slightly off there. But the latest price for
it was $222 and 2.5 cents. So that is the historical
trades and latest trades. As I had mentioned, this
is going to be a wrap on the stocks section of the
Alpaca market data API.
39. Alpaca - Screener: All right. Moving on to the next section of the
Alpaca market data API, we're skipping over the
crypto four X and logos just because of this
course's main focus and the way our
account is set up. Currently don't have access to that logo section
or the four X. But Um, we'll come down
to the screener. The screener shows you
most active stocks, so as it says, returns the most active stocks by
volume or trade count. By default, returns the
top ten symbols by volume. So this will probably
change each time. You run this just
because like it says, it's based off of that top
ten by volume or trade count, and that seems to change throughout the day
week and month. So we're going to come over
to empty Jupiter notebook. We're going to go
ahead and paste this request that we had just copied, if
you don't have your key and secret key already in
here. Go ahead and do that. If you wanted to, right now, the default like it
says is ten for this, let's say, let's just
change it. Let's do 50. This is going to give us the
top 50 most active stock. So we'll come down and
copy this request. You can change to buy trades instead of
volume if you want to. We're going to
leave it as volume. I'm just going to get rid
of this and paste that in. Import JSN as always so that
we can JS loads to make shift enter to run it, and it's going to give you the top trades by volume
years, as you can see. You know, I lists out all of the trade counts for
that specific symbol. So the top one here in Nvidia, and it's going to give you
the volume for it as well. And just as we
specified in order, there is 50 of them. So it does give it to
you in looks like it's descending order here of highest volume all
the way down to the lowest volume
for that top 50. So that is how you
use the screener.
40. Alpaca - News: All right, next, we're
going to move into news. The news articles here returns the latest news articles across stocks and
crypto by default, returns latest ten
news articles. So you can obviously
expand that limit. Just going through
the parameters here. You can pick the date range
that you want that for, how you want it to be sorted, and that's by the date. So either oldest to newest
or newest to oldest symbols, if you want to specify exactly which stocks
you're looking for, otherwise, it's just
going to default to any. Like I just mentioned the limit. And then there's a few
other options as well. What we're going to do is,
we're just going to run it without adding any
parameters in, and then we can add a few
parameters in and take a peek. So what you would use this for, maybe if there's certain
information that you want to pull from these news articles, maybe if you are creating
a large language model, and you want to use
the information within this for some sort of machine learning algorithm,
that could be it as well. But either way, we're going to come to a
new Jupiter notebook. We're going to paste in that
request. We just copied. Import JS and as
always, JSon doads. Shift enter to run. And then you can see
it's going to give us the ten latest news articles. So top one here, Goldman Sachs maintains buy on Maderna lowers price
target to 139. Tells you the source
gives you a couple of different pieces of
information as well as the URL that links it directly
to that specific article. So like I said, we'll run through one more of these where we add
in some parameters. It's pretty
straightforward, though, the information that you would need from a specific article, and then you get linked to it
if you want to pull more of the information beyond
just the headline there. So let's do it for let's see what we had
on the first of this month. And Yeah, the fault
is the current times. What we'll do is we'll
just do till the next day. So, the second. And we're going to do it for let's see if we get
anything for Apple. I don't know, maybe
it's limited. You know, if you only
did it for one day, if there's nothing
written about that, now it's likely that
there's something written about Apple every day. But I guess we'll see
here in a second. We'll just leave
that a fault as ten. And then for now,
we'll use that. I'm going to go ahead
and paste this in there. We've already got Jason imported into this
Jupiter notebook. So we'll just change the
print to Jason Dt loads, shift enter to run,
and we got it. So it looks like there's
one article here. Two articles. Yeah,
we got two headlines. We got this one, iPhone
16 anticipation layoffs, Apple's Intelligence
Impact and more, and this was from Benzinga
and this one as well, Appi Open AI state,
VIDAs Blackwell Delay, US AI warfare preparedness
and More this week in AI. So it's pretty straightforward. You know, if you just
use the parameters that are given to you in
the API reference, but this is how you can get the latest news articles
for whatever the purpose you would be using
it for whether creating that large language model or if it's just reviewing information, finding it all in one place
for a specific symbol.
41. Alpaca - Corporate Actions: All right. Next,
we're running get into the corporate actions. This is slightly different under the market data than it is
under the trading API data, which we looked at earlier. This endpoint provides data
about the corporate actions for each given symbol over
a specified period of time. So let's just get
right into it here. Make sure you've
got your key and your secret key loaded
up here so that it automatically gets placed into this request that's
being generated. We're going to type in symbol. So we'll do exactly what
they did, Apple and Tesla. Types. You can see there's
a ton of different types. If there's a forward split, reverse split, unit
split, cash dividends, stock dividend, a
lot more options than the other corporate action. Pull. The start date and the current date
are the end date. Sorry, default to
the current day. There's a limit on how
much you can pull. What I'm going to
do is I'm going to do let's just do
the cash dividend. Now, let's do a forward split, see if we have any forward
split for this year. 2409. Now we're going to start with the
first of this year, and then the end date
we'll do is today. We'll see if we get anything
back on this, if not, we might have to come back here, choose a different type. But for now, we're
going to copy this. Head over to an empty
Jupiter notebook, paste it. We already had a file
name corporate action, so I just put V two in there. But the naming convention is totally up to you as to
how you want to do that. We're going to import JS, JS, dot loads, shift
enter to run it. And it looks like there's
nothing for this. Now, let's see if
there was let me see if I broaden the time range. Let me do 2020,
see if that helps. So let's copy this again. And actually, if we
really wanted to, we didn't want to
recopy in, everything, we can just come into
the endpoint and change that from 24, 2024 to 2020. So let's shift, run that again. Okay. We did get something here. We've got Apple had a forward split looks
like September 1. It's kind of funny this month. But of 2020. That's
the redemption date executed on the 31st
of the date prior, and it was a four to one split. Tesla had one in 2020, same date, actually,
it looks like. A five to one split, and then one in 2022, as well, three to one split. So you could come in and
whatever you may be looking for. There's a bunch of
different options here for you to go
ahead and pull it, just put in whatever
parameters you want. As many symbols as you want to for what
you're looking for, could be one, could be, I'm
not sure what the limit is. Maybe it's 100. Maybe there
is no limit, either way. You might just get bogged down. With this limit over here, you'll probably have
to use that next page if you're pulling
a large amount. But that is the
corporate actions under the market data API.
42. Alpaca - Options: All right, to moving on to the
final lecture of this part two of the Alpaca
Market Data API. The final section
is the options. We're not going to get too
far in the weeds here, but we'll at least just go
through one request on this. This is going to function the same as some of the other
stuff we've done for, you know, pulling
historical bars, exchange codes, and so on. But obviously it will
contain options data. So the one thing we will
do here is I'll just show you how to pull
an option chain if you're familiar with options. This will make sense. If not, then you'll have to do
some additional research if you are curious about it. I'm going to use
Apple as always. That's the one required
parameter here. You will have to change
this to indicative, everything else if you
care to put parameters in. Feel free by all means. I'm just going to go
ahead and run this. Like I said, I'm just doing it. For example, purposes, anyways, so I'm going to come to a
blank Jupiter notebook. Paste that. Import JSN. Son dot loads shift
enter to run this, and it's going to provide the option change based off of that the default parameters. You could see it's a long chain here of a ton of
different options. You know, it's going
to give you that ask price, the bid price. It just depends on
exactly what part of the chain you're looking at here as to what data
you're going to get. So I would suggest
organizing more probably will look better if you put
this into a data frame, easier to run through the chain, it'll look similar to
the UI that you would see on a website for a broker. But like I said, just a quick run through of what a request for
that looks like, all of the other requests here, you know how to run those based off of our prior lectures. So that will wrap up the Alpaca
Market data API section.
43. Polygon - Sign Up: All right, now we're
going to get into the polygon dot IO section
of the course here. This just expands upon the data that you can pull
makes a little bit easier. Some of the items
that we would have to create manually when pulling data directly from Alpaca are just offered
directly by Polygon. Um, so it's up to
you whether you want to consider
using polygon or not. I APAC is enough for
you, then by all means, but I still think it's
worth considering looking at the data that
you can get from Polygon. So first things first, come to Polygons
website polygon dot O. Make sure you're
at the right one. There's a few companies
named polygon. So like I said, just make
sure you're at polygon.io. This will be the page
that you come to. First things first, just
go ahead and sign up. It's free to sign up, so you'll get access
to some free data. And we'll get into that
in the next lecture. But for now, just add your
e mail address, password, any verifications that you
need to do through e mail, and once you get signed up, then you can proceed
to the next lecture.
44. Polygon - Pricing: All right, once
you've signed up, go ahead and get logged in, and this will be the page that you're taken to the
Min dashboard here. What we're going to review is the pricing that is
offered by Polygon here, as I had mentioned,
there is free options. But if you want more data, then you can go ahead
and look at this to see what else you might need. So, as you saw, come to the pricing page here, scroll down a little
bit. And you can see the four pricing
options listed. Note that this is
specifically for stocks. So if you want to buy
additional data for options, indices, currencies,
these are all separate. So say you wanted to buy the starter for stocks,
so that you get all this, that'd be 29 bucks a month, and if you wanted to get
currencies data as well, and you wanted the
starter, that's an additional 49 bucks a month. So the starter plan doesn't
go across all four. You have to buy them depending
on whether it's stocks, options, indices or
currencies individually. So that's just a heads up Now, four stocks, which is what this course is focused on. There is the basic plan. Like I said, five API calls
a minute, end to day data, so you're not going to get
it throughout the day, two years of historical data. So maybe that's enough
for you. Maybe it's not. You get the 100%
market coverage, which is across all plans, reference data, fundamentals
data, corporate actions, which we reviewed what corporate actions entails
in the Alpaca data, aggregates, and then you do
get technical indicators. So maybe while you're
taking this course, that's going to be
enough for you. Maybe it's up to you. If it's not, go ahead
and look through to see what extras you get
in the individual plans. I actually have the
starter plan for this, so you might see me pulling larger amounts of
data that maybe you get an error for
because it's too much. I'm going to try to avoid that, but if you do get those errors, then just know that that's
exactly why. You know, you get more data, so it's a
higher time frame, five years instead of two years. The data is only
delayed 15 minutes. So if you are do if you
are trading in real time, that real time data is
only going to come with this $200 a month plan. If you know you're going to utilize this for more
than just a month, if you know it's going
to be at least a year, looking at the annual plan
you can save per month, but know you'll be
paying upfront. So you're saving 60
bucks throughout the entire year by purchasing
the annual plan. So Just wanted to show everybody what the pricing options are. I make you aware of how each of these options indices and currencies are separate
purchases from the stock plans, when you buy, whether it's a starter developer or
advance, whatever it may be.
45. Polygon - Documentation: All right, in the last part
of this Polygon introsection, we're just going to quickly
review the documentation here and what we're going to be going over in the
future lectures. So under Docs, come to
documentation here, the Polygon IO Stocks API
provides rest endpoints that let you query the
latest market data from all US stock exchanges. Also find data on
company financials, stock market holidays,
corporate actions, and more. You can see here on
the left hand side, similar setup to how APAC is. We're going to go through all
of these market endpoints, and then all of the reference
data endpoints as well. On the right hand side, you
can see your current plan, as I had mentioned prior. I'm on that starter plan, the $29 a month. The different libraries. We're obviously using Python. There is a client library
that you can use. And then there's the different types of securities,
options, indices, four X, crypto that has
documentation on it. But as mentioned prior, we will be going through stocks because that is the main
focus of this course.
46. Polygon - Aggregates: All right. The first
part of this polygon Do documentation is the
market data endpoints. We're going to go
ahead and review that. This is a little bit more complicated than
doing it in Alpaca. Alpaca does a majority
of the work for you, but if you were able to follow along
with the Alpaca portion, this part should allow
you to do the same. So we're going to
start, like I said, with the aggregates here
pulling aggregate bars, get aggregate bars
for a stock over a given date range and
a custom time window. So there are the parameters, just like Alpaca Head, you can go ahead and change
those if you need to, you can change the time frame, whatever it may be, set the
limits, the sort order, and all that, now, all this is going to give
you is the API end points. You can see that's created here. I'm going to go
ahead and copy that, and then we are
going to head over to our Jupiter notebook, and we're going to go ahead
and start creating this. Now, if your API key is
not already in there. Then you can go
ahead and go find that by going to API keys, and then the API key
is going to show up, copy it, make sure
that it's in there. If you're signed in, it should automatically show up in
the documentation, though. So let's just head back
over to where we were. Give it a second to load
here, aggregate bars. We're going to leave
it just how it is. If you want to change the ticker you can, I'm just
going to leave it. I'm going to leave
this date frame. You can widen it, you can
shorten it whatever may be. But I'm going to
copy this endpoint. And in a blank Jupiter notebook, we're going to first, we have
to import three libraries. We want to import requests, which was auto generated
the last time, import JSI, which
we would always do. And then we're going
to use Pandas to create a data frame out
of this aggregate data. So we want to import
Pandas as PD. So we're going to shift
enter to run that. Then the next step is
we want to actually create the API request. So we're doing it for Apple. I'm just going to call
it using Apple's Ticker, API or Apple URL. We're going to open
up some quotes and paste in that endpoint
that we were given. We want to then create
the response variable, which is using that
request library. In a get request, and we're going to put in that this variable
we just created, which has the
endpoint, and then I'm going to go ahead and make
the response look nice. Usually, like you'd seen
when you just print it. It doesn't give
you a nice format, so we're going to create one more variable, the Apple data, and it's going to
be nicely formatted using the Json dots,
apple response text. All right. And then
we can go ahead and just write it one
more time so it shows up. And if we shift enter, it should provide us with Oh, it looks like I made
a mistake here. This should be Apple UL. Shift Enter, and then we get our apple data in that
specified time frame. It shows us the volume, the weighted volume,
open, close, high, low. The time, which is
in since Epoch. So we're going to show
you how to convert that. In a second, it's a
standard and a lot of programming languages
where it'll return the value since 1970, and you just have to convert it, and then the number of
transactions in that period. So we want to make
this data look nice. So we're going to
go ahead and use a little logic to create a
data frame out of this data. The first thing we want to do is actually create
the data frame. So we're going to call
it just Apple DF, and we are going to
set that equal to data frame and we want to use the data
that we had created, so it's that Apple data. But then if you take a look, we need to go a step down in the hierarchy
of the dictionary. We don't want this stuff. We want just what's
within the results here. So we're going to put results, and we'll see how this
runs. Let's do this. Actually, I'll put it
within the same cell. So we'll shift enter. And you can see we
get the data frame. So what you'll probably
notice is obviously, you know, we can relabel these, and we'll probably
do that later on, maybe not in this lecture, but there's no column that
specifies the ticker. So if we had multiple symbols within this that we're
showing data for, we'd want to be able to see what data corresponds
to which symbol. The other thing is this time, like I said, it's
showing it since EPOC. We're going to
convert both of them. We're going to add
the symbol column, and we're going to
convert the time column. So that this data frame is a little bit more useful for us. So the next thing we're
going to do is very simple to add the symbol column. We're just going to utilize the same data frame
to create a column, you just create a variable
that uses the data frame, and then the name
of the new column. So we're going to just
call this ticker. Set that equal to the
value that you want. So we want it to be Apple. Now, if I ran this again, shift Enter, you can see that we just created
this ticker column. Now, the next thing
that we want to do, and this one's going
to be a little bit more involved is to convert this here,
these seconds, SPAC. The way we're going
to do that is first, we need to convert that
column to a string. So the way we're
going to do that is we're going to take that column. And we're not creating a new
column with the same name, but we're re creating
the value within it. So we can use that same thing, the same column header, which is that just t, and we're going
to set that equal to the same data frame column, but we're going to
now take the type, use the as type built in
function as a string. So now we've converted
this column to a string. The reason we have to
do that is because this has three, too many zeros, which you would find
out as you went through this later on, you wouldn't
know that ahead of time, but you would find
out eventually that you have too much
data within this column. We need to remove
those. First, we're going to convert it to a string. There's a multitude
of ways to do this. This is just the way
I chose to do it. Now we want to remove those
last three characters within the values
of that column, and we're going to
do that by creating a function called
remove character, and the input is going
to be for the row. And all we want to do is
return row, the value t, and we want to return
everything except for the last three values
in that string. So we can go ahead
and move on down. And then the last thing
we have to do is we have to four that column, we have to apply the function
that we just created. So we're going to do Apple DF, and you just apply
it to the data frame as a whole because we
specified which column in the row and which column
we want it to be applied to what our function is, which is, and the axis
we want to happen on, which is the column. So axis equals one, and then the last
part of it would be to Then convert that to the
actual date time format. Once again, with that column, we keep working on it, the T, set it equal to PD, and we're using the
Pandas two data frame, and we want it four
E, Apple data frame, T column, and the unit is
equal to seconds here. All right. So that
should be good. You probably have to pause a couple of times if
you're following along. But if we go ahead and
then shift run this, it should apply converting
that column to a string, removing the last
three characters, applying that function that removes the last
three characters, and then applying the
date time conversion of the seconds count so that it's actually
a readable value. So we'll shift
enter to run this, Oh, this should
be two date time, not two data frame. That's my fault.
So two date time should enter one more time. And you can see that
it did convert that. Correctly, that was within
our time frame there. If we go back and look, you could see from the
ninth to 10 February. So you do get this
air. When you do that. The reason that it's providing that air is because it wants you to pass it to cast it
as an int or a float. Instead of a string, we
left it as a string. Um, if you want to remove that, especially if you're
using future versions. What we'll do is
before we convert this is we're going to just
as we had done up here, I might actually go ahead
and just copy this. We converted to a
string up there. We want to just convert
it back to an int. If we shift enter to run it, you can see that that goes away. So that is the proper way that you should do
it moving forward. But as you can see, we
pulled that aggregate data, added our ticker column, and then converted
the column values of the date time so that
it's actually a readable.
47. Polygon - Grouped Daily: All right, the next item
we're going to cover in the market data end points
is the grouped daily bars. So get the daily open
high, low end close, sometimes referred
to as the OHLC for the entire stock
slash equities market. So the only required parameter
here is just the date. So we'll do yesterday's date. And you can update the other
parameters if you want to. I'm just going to
leave it. I left our previous Jupiter
notebook open. I'll just make it
easier for stealing the logic like you saw
in the last lecture. It doesn't give us as
nice a request setup like Alpaca does. We have to do a little bit
of the work on our own. But it's not too terrible. So first, I'll just copy the libraries I need to import into this empty
Jupiter notebook. Ship to enter to run that. And then I'm going
to actually go and get this data as well, and we're going to make
some adjustments to it. So for one, we're going to
have to update this URL. And what we're going
to do is, we're going to go to get rid of the apple. Because this is not
specific to apple. And then we're going
to go ahead and get the endpoint that
we're given here, we're going to copy that, and
we'll come and paste that. And then we're going
to go ahead and run this, see what
it looks like. And you can see
it's going to give you a ton of data for
each specific ticker. The next thing we want
to do is we want to actually convert this
into a data frame. So we're just going to
call DF data frame, and we're going to use
that data and to enter, actually we want to run that with DF so that we can see exactly what
it looks like here. Oh, made a mistake. I need to it needs to be data, and I believe it's results. Yeah. All right. So we'll update that. There you go. It gives you
the actual ticker this time. The only thing we would need to do is to update this time. So let's go ahead
and grab that logic. We use last time again where We are converting
all of this. So copy and paste
that into here. Like I said, we're
going to remove the apple out of all of these. So get rid of this apple, get rid of this apple. Make sure you've got the
lower case t there because the ticker is defined
by an uppercase T. We will remove the
apple here here. And we'll just make sure we
get rid of all of these. Looks like we did. So then what we're doing
again here is we're converting that
column T to a string so that we can then get rid of the last three
characters with this function. We're going to
apply the function to that column in
the data frame. We're going to convert
the type back. And then we're going to convert
the column to date time. So let's go ahead and
run this shift enter, and you can see that we've
got that updated date time. So this is the group daily bars. You can see it's
specific for this date. Date doesn't change for all of these different
ticker symbols. If you wanted to, you could
look at just a specific one. If if you wanted to define, let's see if we can do MTA, if MTA is included in
here, which it should be. We're going to make
the Meta DF equals DF, and we want it where the Ticker column equal to meta. Shift. We're going to run this, with
that in there, shift enter, and, looks like we have
some misleading logic here. So let me redo this. What we want to do actually
is within this data frame, we want the Ticker column here, two equal meta, and then we're going
to close that bracket. So now, this should be
the update of logic. This should be correct.
That was a mistake. So let's do this one
more time, Shift Enter, and now it gives you just that Snippet where it's
the meta Column. So that is the
groups daily bars.
48. Polygon - Daily Open & Close: Alright, next, we're
going to cover the Daily pen enclosed. This is similar to
the group daily, but it's just for
one specific symbol. You can use any
symbol you want to. I just chose MDN here. It's for a specific date. So we're going to
just click on this. It'll give you this nice
interactive calendar, or you can type it in yourself. But to ensure the
Foma is correct, we're going to use this, choose yesterday's
date. And then Go back to that grouped daily Jupiter notebook we just worked on so that we can
copy some of this code. So we want to input their
libraries, shift enter, and then we're going to
grab the request as well. So the only thing
we'll need to change here on this is the
actual endpoint. So delete that. Come
back to polygon here. We're going to copy
this endpoint, and we will paste into the
URL shift enter to run, and it's going to give
you the information, the open high low closed volume after our hours in
pre market data. For Meda on whatever
specified date you choose.
49. Polygon - Previous Close: Alright, next, we're going
to do the previous clothe. This auto defaults to the
previous days Open High low close for the
specified stock ticker. So we'll do META again. This is going to
give us same data as we did in the last lecture, just because we picked
yesterday's date. But for this one, it
auto defaults for you. Leave that previous Jupiter
notebook open, if not. Go ahead and open it up so
we can go ahead and copy. Some of the code here,
import the libraries. I guess you don't
really need to import pandas for these if you're
not creating a data frame, but it doesn't hurt
to have it in there. And then we're
going to go and get this data as well
for the request, and we're just going to
update this URL end point. So let's go and grab
that from polygon. We're going to copy
it, paste it in here, and then we're going to
shift enter to run this. And there you go, gives you the open high load close
volume transaction and the time for it as well. You could convert the
time if you want. We know that it's
yesterday's date.
50. Polygon - Trades Last Trade Quotes and Last Quote: All right. So the next items in this market data endpoints
list is the trades. Last trade quotes
and last quote. Our current account doesn't
allow us to have this. So if you want to upgrade, if this is information
that you want, I'll show you in a second here, how you can see if it's
something you might want. You can go ahead and upgrade, but you need at least
a developer account, which I believe is it's
either 80 or $100 a month. So just something that
you can consider. But just so you can see
what kind of data you'll be getting on the right hand
side here at the response. This is for trades,
what you'll be getting. This gets trades
for a ticker symbol in a given time range. The last trade gets the most recent trade for a given stock and all of
the applicable information. The quotes is quotes for a ticker symbol in
a given time range, and then this is the last quote. So this information is something you think
you might need, you can consider upgrading. We're not going to utilize it, so we're just going to keep our current account
subscription.
51. Polygon - Snapshots: All right. Next
up, we're going to review the snapshot data. So Alpaca had something
similar here. There's a few different items
we're going to go through. If you have one of your
previous files handy, I would go ahead and grab that
so that you can first get the libraries and go ahead and put those on
a new Jupiter notebook. I put these markdown cells in there. You don't
have to do that. It's just my way of separating it for you to be able to see it. So we can shift enter
to run the libraries, and then we're going
to go ahead and grab this as well so that
we can form the request. We're going to
remove the endpoint, and then what I'm going
to do is I'm just going to place this in each of these, and we'll go get the respective endpoint so
that we can run these. So first is the A Tickers. So in Polygon, under Snapshots, you got all Tickers,
get the most up to date market data for all
traded stock symbols. So if you want to specify
the tickers, you can. We're just going to
go ahead and copy this and we're going to come back to our
Jupiter notebook, put the endpoint in,
shift enter to run it. It's a lot of data, so it's
going to take a second. But it goes ahead and runs for all Tickers
snapshot of data, a bunch of different fields. So if this is data
you're looking for, then go ahead and do
the A Ticker snapshot. The gainers are losers next, which is defined as
the most up to date market data for the
current top 20 gainers or losers of the day in the
stocks and equities market. So Um, you can choose
either gainers or losers. Let's say we'll just do losers, just so that we change
one of the parameters. We can go ahead and copy that end point here and paste it into our
Jupiter notebook, shift enter to run it, and it's going to
give us the top ten. It's going to show
you those changes. This one is down 56%. The next one looks
like it's down 43%. So these are huge losers. Just because let's
change this to gainers. See what that looks like. See what kind of
increase we have? Yeah. This is up
over 154% today. So that's the
gainers and losers. Next, we'll go to
a Ticker Snapshot, which is the most up
to date market data for a single traded
stock ticker. We'll do it for Meta, and
we will copy this endpoint. Head back to our
Jupiter notebook, paste that in here to
the request, ship Enter. And that's going to give us the snapshot for just
this single ticker here, all the information. That you're looking for
in one place if you don't want to return all
of the tickers like above. And then finally, we're going
to do universal snapshot, which is snapshot for
assets of all types. So it doesn't look like there's any required
parameters here. Let's see if we get
any pushback on that. So we'll copy the end point, come over here, paste it, ship enter to run it, and it's going to give us and I think this does have
specifications in it. Let's see here. Oh, yeah, we've got common separated. So this is just a
default values, but What we can do
is just take a peek at these specific ones that it gives us if you
want to be more specific, then you can do that
within the parameters. But that is the
snapshots on polygon.
52. Polygon - Technical Indicators: All right. The final lecture on this Market Data end points is on the technical indicators. This is one of the nice things about polygon here is that it automatically provides
this data to you instead of you having
to manually create it. If you do have to
manually create it, it's not the end of
the world, but this just makes it a lot easier. So go ahead and get that polygon aggregates
Jupiter notebook pulled up. Going to be easy for us
to go ahead and grab some of that data for what
we're going to do. Some of that code, excuse me, for what we're going to do
within this specific lecture. So get the libraries first
in a new Jupiter notebook, go ahead and put those in
and shift enter to run. I've got this split up by the
different indicators here. You don't have to do that, but it just helps with organization. So the first is the SMA, which is the simple
moving average. If you're not familiar with the simple moving
average, the MA, Mac Dean, RSI, go ahead and do some research on those to
see exactly what they are. For this lecture,
we're just going to go through how to
pull the data for it. So For the SMA, you're going to have
to put in a symbol, so we're going to do Apple. And then there's a
few other parameters you can go ahead and
fill in if you want to. We're just going to do we're
just going to leave it as the default here and see how many days worth
of data it gives us. The window is
calculating, you know, how any days of trading, we're going to average
the price over. This has it defaulted to 50. We'll just leave it
as that. And then the number of results
returned is ten for now. So we'll copy this endpoint. Actually, before we copy that, let's go ahead and grab
this request data here. We'll paste that in, and we
will remove the endpoint. We had created previously, and now we will grab
the new endpoint. And we'll go ahead and
paste that in here. It's a long one, and then we will shift enter to run that. You can see that it gives
us ten different values. What we're going
to do is actually, we will add a cell
underneath this one so that we can and
we will add a cell. So that we can convert
this into a data frame. So if we just create a
data frame DF equals, we've already got that
Pandas library imported. DF equals p data frame, and then we're going to take this apple data and get
the specific values. Nope, sorry. Yeah, no, that should be values.
Okay. So we'll grab that. And we will shift
enter to run that. No, it looks like we have
to do results the n values. So two steps in the
dictionary hierarchy. There you go. So
then it gives you those ten different values. It should be the last ten days, but what we'll do is to ensure that we know which
dates, these are four. We're going to utilize
that function to convert the timestamp into
readable format. So we'll come back to our
aggregates and we'll grab this code here that will
allow us to convert it, and we'll just have to
change it up a little bit. So paste that in there. The first thing is four, and we just have it named DF, so we will actually, we'll make it easy on ourselves. We'll re label this as Apple DF. And then the column name
is actually timestamp. So instead of t, we want
this to be timestamp, converting that to a string, and then we will
create the function. To remove the last three, we know now that
we need to remove those in order for this
to function properly. And then we will apply this
function to our data frame. We will then convert that column type back so that we don't get that warning
on the deprecation. And then finally, we will
perform the conversion. And this should provide us with the properly formatted
date shift enter to run that. And you can see, yes, it is for the last ten trading
days including today, we're in the middle
of the day here. So this value will
probably change. Let's hear it's 220-26-5604, if I rerun it,
It's not changing. So maybe it's doing it
based off of yesterday. So that we'll have to check out. Yeah, I might be taking
yesterday's date into effect. So we'd have to look further
into that either way, it's going to give
you less ten values if you want to be more specific, make sure you fill that
out within the parameters. I'm not going to do all this
for these other indicators, but I'll just run the
requests anyways. So let me copy this. Into here, and we're going
to remove this endpoint, and now we're going to get the exponential moving average, and we'll come down here and we'll go ahead and grab
the endpoint for this, and we're going to paste
that in there and run it. Then this is the
exponential moving average. And then the Mac D, I'm going to go ahead and
grab this data again. And if you want to
ensure that you are not re establishing
the variable, make sure you give these
different variable names rather than continuing to use the same one because once I created this
response right here, this SMA one
essentially went away. No longer is the
values for Apple data. It's now the EMA one. Now, for the MACD, we're going to get
the endpoint for it. And we'll come back to polygon and see if we need
anything inserted here. You can change the
windows if you want to. Otherwise, just
go ahead and grab that endpoint, paste in there. We're going to shift
enter to run it, and then it should
give us our values for those ten
different time frames. And then finally, the last
thing we're going to do is the relative strength
index indicator, and we will get rid of all this. And go grab the endpoint for it. And we've already
got Apple in there, and we're going to
just come down. You can change the
window if you want. We're going to leave it,
paste that endpoint, shift enter to run it,
and then you can see. It's going to give
you those values. So that is the
technical indicators, and that is going to wrap up the market data endpoints section in polygon
for this course.
53. Polygon - Tickers & Exchanges: All right, the next
part of the course, we're going to dive into the
reference data endpoints, starting with the tickers
and the exchanges, the two kind of go hand in hand for putting together some
of the parameters here. I'm going to show you what
I mean by that in a second. The first thing we want to do is if you have the data still, the code for one of
the prior lectures, I would go ahead and open that up so that you can easily just copy and paste some of the code. So first, the library's
request Jason and Pandas, we want to import that,
shift enter to run it. Then we'll actually start with the exchanges because
we're going to use the exchange parameter
within the Tickers request. So the first thing you want
to do is if this is blank, we're just focusing on stock,
so you can change that. You can change this
locale if you want to. We'll do US before I copy that, I'm going to grab this request here and we'll just
clean it up a little. So I'm going to paste
that. I'm going to get rid of all of the apple. So that it's just generic, and then we will remove the endpoint because we
want to put our new one in. So there's a request
all cleaned up. The template is
waiting for us to just grab this endpoint,
paste it in there. We're going to shift enter,
and it should provide us with the list of exchanges here and the applicable
information. The next thing we're going to
do is we're actually going to go to the Tickers
now, and actually, let's copy this and we'll paste it down here and
remove this endpoint, and this will just
be our template so that we can grab
the Tickers data. We're going to we'll just
use this first exchange. We need to grab this code
here as a parameter. And because we're going to get so much data
back from this, we need to be able to narrow
this down a little bit. So the market, if this isn't
already make that stocks, the exchange, we're going to use that code that we just got. And then the rest of it, I
think I'm going to leave. If this isn't maxed out,
you might want to do that just so you make sure
you don't miss anything. So now let's go ahead and
grab the end point for this. And we're going to paste
that here for Tickers, and we will shift enter, and it's going to
provide us all of the stock tickers that are on that exchange and
some applicable information. To make this easier to read, I'm just going to make a
data frame out of it. So data frame DF
equals pd data frame, and we'll add the
data data in there. And then we'll run that shift
Enter. And there you go. Now you can see, Oh As always, we need to find in the dictionary because
it's not doing that. We need to do it for results, and that'll give us
a cleaner table. So one more time,
and there you go. All the information
that's displayed within this request is now in a
nice clean data frame. So that is the tickers
and exchanges.
54. Polygon - Ticker Details: All right, next is the
Ticker details here. They have it designated
as the V three. So you can see that in
the end point there. We're going to go ahead and
set up just as we usually do based on the code
from prior lectures. We're going to take that in an empty data frame
and just kind of get the bones of this
Jupiter notebook. Sure you're in the cadence
by now doing that, but we want to get this request, template set up,
remove the end point, and then we just need to go and enter the
parameters for this. We'll do MTA. And then if
we want to specify a date, it says specify point in time to get information about the
ticker available on that date. We're just going to leave
it as the default here. That means the most
recent data available. So we're going to
copy this endpoint. We'll paste it in here, and then we will give it
a shift enter to run, and it is going to provide
ticket details about MEDA. There's a ton of different
information here. You can see the
description of M Meta is the world's largest
online social network with nearly 4 billion
family of apps, monthly active user,
so on ya ya yada. More information than you'll probably end up needing here, but if for whatever reason
you need some of it, something such as the shares outstanding, whatever it may be. This is exactly where
you can find that you can see the market cap here. Looks like we're into
the trillions is that? Yeah, 1.35 trillion. So that is ticker details.
55. Polygon - Ticker Events: All right, moving right along, we're to get into the
Ticker events endpoint. So let's go ahead and set up our new blank Jupiter notebook. Shift enter to run the libraries
that we want to pull in. And then we'll go grab
the template for request. And we're going to go ahead
and get rid of that endpoint, and then we want to
come back to Polygon, and we want to get
the end point here. The parameters that
required is the ID, the type you can put in
there if you want to. For the ID, it can currently be a ticker a CUSIP
or composite FIGI. So when a given ticker, we return event for the entity currently
represented by that ticker. So we have meta typed in here. That's just what we're going to use for this, makes it easy. We're going to come back here, put in this end point, shift enter to run it, and then we get returned
any recent events. So it looks like the most
recent event we're looking at here is the Ticker
changed from FB, when it changed from Facebook,
apparently, to Meta. So Facebook's parent
company is Meta, and that's the event.
We're looking at. This was back in 2022,
when that happened, it looks like the original
this might have been W. Facebook actually went
public with this Ticker. So that is Ticker Events.
56. Polygon - Ticker News: All right. Next up
is Ticker News. I get the most
recent news articles relating to a Stock
Ticker symbol, including a summary of the article and a link
to the original source. So this has a few
parameters you can fill in. I'm going to go ahead and
actually just use Boeing. So the Ticker symbol
for Boeing is BA. I'm going to set up our
new Jupiter notebook, just as we always do for
pulling this polygon data. So I'm going to import
to the libraries, and then I'm going
to get this template set up for the request. Remove the previous endpoint and go ahead and get
the new endpoint. So we'll copy this. We didn't fill in any other parameters. We're going to get
just ten news articles back here. We should. Let me put in the new endpoint, Shift Enter, run,
and there we go. So the top one here is
from the Motley Fool. It's got the home page
of the Motley Fool. It's got the Logo
URL, the favicon URL. But more importantly,
it's got the Article URL. The title of the article is
Boeing stock going to 240. One Wall Street
analysts thinks so. It gives us the image URL
in a short description. Boeing is facing an
extended strike by the International Association of Machinists and
Aerospace workers, which could significantly impact its cash flow and
production ramp up. The company needs to
resolve the dispute quickly to avoid further
financial strain. And as you go further
and further down, of course, there's
related Tickers. So this I recognize
is Southwest, but then it moves
into eventually, you'll get the next article. So that is how the
Ticker news works. You can specify
which company you're looking at and get
the latest news. Maybe, as I've mentioned, something similar for AlPACA. You can utilize this for
creating a large language model, pulling in a bunch of
news related data. So that is Ticker news.
57. Polygon - Ticker Types: All right. Next is
the ticker types. So list all ticker types
that polygon dot IO has. So there's a bunch
of different options for the asset class here. We're just going to
leave that blank. We're going to set up our
blank Jupiter notebook, as we always do with the libraries first
shift enter to run, and then we are
going to grab the request to use as
a template here. We're going to get rid of the
current endpoint in there and go and grab the
ticker types endpoint. We'll copy that,
paste it in here, shift enter run, and you can see it's going to list
out all of these. We can, if we want to. We can turn this
into a data frame. It's easier to see data frame. And we will use data. We got to use the
results portion of the dictionary,
close the parenthese. We will shift enter and run
that and you can see all of the different assets
that we have here, the description,
stocks, indices. You can see common
stock preferred stock, warrant rights, corporate
bond, and so on. That is the ticker types.
58. Polygon - Market Holidays & Status: All right. Next, we're
going to go through the market holidays and
market status get requests. So starting with the holidays, going to do the same setup as always in a blank
Jupiter notebook. We'll import those libraries, shifted enter to run those, and then we will grab the
request template here, get rid of the current endpoint. Now, this one is going to
be the Market Holidays. And we'll go to Polygons
documentation here. There is no parameters
to even put in, so we're just going to
copy this endpoint here. We'll paste it,
and we'll run it, and then you'll get a list
there of all of these. Now, if we wanted to,
we could turn this into a data frame. So why not? Let's just do it within
the same cell here. So what we'll do
is the data frame. We'll call it the Holiday
data frame. How about that? Holiday DF equals
p data frame data. And then we will run this
shift enter, and there you go. You are going to get all
of the dates for it. And this is in ascending order, and you'll get
exactly what it is. And what the market status is. Early close, looks like the
next one is Thanksgiving. It's close on Thanksgiving. Both the NASDAQ and New
York Stock Exchange. And there's an early close. This looks like
it's Black Friday. It says Thanksgiving here, but it's the day
after Thanksgiving, and it tells you when. So that is the market holidays. Now, let's move on
to market status. So market status. What we'll do is we'll
come up here and just grab this and we'll go ahead
and paste This in there, we'll remove this endpoint, and we'll go and get
the market status endpoint from Polygons
documentation. Once again. There's no parameter here, so we're just going to go
ahead and grab the endpoint. We'll paste it in here, shift enter to run, and you're going to get the
current status of the market. As you can see the
documentation, it says, get the current
trading status of exchanges in overall
financial markets. And you can see just that. It's not after hours right now. It's not early hours. It's currently open. So you can see NASDAQ, the Dow, the market
itself. They're all open. What the server time is, in general, says it's 3:07 P.M. And that's Eastern
time. It's going to end up closing in
about 53 minutes or so. So that is the market
holidays and market status.
59. Polygon - Stock Splits: All right. Next up,
we've got stock splits. Get a list of historical
stock splits, including the Ticker symbol, the execution date, and the
factors of the split ratio. So there is something
within ALPACA. I know we've done this before, but this is polygon's
way of doing it. So if we want to
specify the symbol, Yeah, we'll go with the Apple because I know
Apple's done splits. I'm not sure if
Boeing has So we're going to go ahead and get in
a blank Jupiter notebook. We're going to get the
template setup as always. So we'll import our libraries, shift enter to run, and then we'll get our
request template here. Paste that and
remove the endpoint that we currently
have in there to grab the new one stock splits. Come and copy that. And
then we'll come back here. We'll paste that in
there and Shift Enter, we will run to see
the stock splits, just so that we can make this
look a little bit nicer. We're going to turn
it into a data frame. Data, and this is in the result section of
the dictionary here. And we will close that and
we will run the data frame. So you can see here, there's been since 2005, there's
been three of them. We've got in 05, there was a two to
one split in 2014, there was a seven to one split, and then most recently
back in 2020, there was a four to one
split for Apple stock. So that is stock splits.
60. Polygon - Dividends: All right. Next up is dividends. Get a list of historical
cash dividends, including the Ticker symbol, declaration date, dividend date, record date, pay date,
frequency, and amount. So we're going to do this. We'll do dividends for Boeing. Let's first set up our blank
Jupiter notebook, utilizing. Code, we've used previously, shift enter to run to
import those libraries, and then we're going to get just this request template here and remove the
previous endpoint. So then we need to
come over to Polygon. We've already put in
Boeing as the ticker. If we wanted to put any additional
parameters in we could. Maybe we want to look at
25 different dividends. So we'll change that, as well, and we'll do it in order
of pay date. Why not? So we're going to copy this. We'll come back here
past that endpoint, shift enter to run this, and then we will convert this into a data frame so
that it's easier to see. As always, it's the results
section of the dictionary, and we will go ahead and
run that and take a peek. And you can see all of
these different dividends for Boeing looks like Boeing got rid of their
dividend in 2020, right after the pandemic
really hit everything. So must have made sense there. They had to make some decisions. I know it was a super
volatile stock. So they haven't paid out
a dividend since then. But this is the list of the last 25 dividends
paid out by Boeing. You can see the
amounts for each of these declaration date and any other applicable
information.
61. Polygon - Stock Financials: All right. Next is
the stock financials. So get historical financial
data for a stock ticker. The financials data
is extracted from XBRL from company SEC filings using the methodology outlined, and you can click here
to check that out. It says, this API
is experimental. It seems to provide a lot
of very valuable data, especially if you're trading
off something that has to do with any sort of financials, such as the income statement
or the balance sheet. Let's go ahead and just
test this out here. First, we need to
set up our files. So as always, we're
going to import our libraries and we'll
shift enter to run that and then get our
template for the request. We're going to remove
that end point here because we need
to put our new one in. I just put Apple here
in the parameters. You can put whatever
you want to. There's any other
specifications you'd like to add by all means, do so. But I'm just going
to leave it as is. Limits going to be ten,
meaning it's going to get us the ten most recent filings. So I'm going to copy this, and we will come back here
and insert this Shift Enter, and you can see the
most recent filing is, through June 30 of 2023
to June 29 of 2024. Within it, it's got for
Apple, in the financials. It has the cash flow statement, income statement,
and a few others, just to make sure that we know exactly what's in each of these. We're just going to run some quick code to
see what we've got. Four item in data, which is what we
call this is data, we need to get into
the results section, and we'll just run it for
the most recent item. So there's ten in here. We'll do it for the most
recent one and see which financial, statements
we've got within this. So we're going to
type in financials, and we'll just loop
through the items, so we want to print
out what the item is, and this is going to tell us which financial
statements we have to look at from the most
recent filing, shift enter. We've got the cash flow
statement, income statement, balance sheet, and the
comprehensive income. Now, if it helps you
you can go through and loop and set up a data frame that pulls through this data and makes it
look nice and organized. We're not going to do that now, but just know that you have all of this data
available to you. So that is the stock financials.
62. Polygon - Conditions: All right, quick one here. Conditions. List all conditions
that polygon dot IO uses. Let's go ahead and set up our plan Jupiter
notebook as always, shift run the libraries. Then we'll go and
grab the template for the request. Add that in here. We will remove the
current endpoint, and we will look
to grab this one. We're not going to add
any parameters or change any come back here, drop in the endpoint,
shift enter, to run it, and we've got a
list of conditions here. And let's actually put
this in a data frame. So DF equals p data
frame data results. And we'll close that and we will shift enter to
run and there you go. You have your
conditions list here. If you wanted to, you
could dive further into the update rules, but it's going to
list each condition out and what it is
and the mapping, each of the applicable fields.
63. Polygon - Related Companies: All right. Last item
in the reference data endpoints on polygon here
is the related companies, get a list of tickers related to the queried ticker based
on news and returns data. So we're just going to do
Apple, make it easy here. We've got a blank
Jupiter notebook. As always, we'll get
our libraries in there. Shift enter to run that, and then we will get
the template for the request and remove
the current endpoint. So that we can go ahead
and grab the new one. There's only one parameter. It's just the ticker for which companies you
would like to see related to or which company you would like to see other
companies related to. So we will go ahead and enter
this end point in there, shift enter to run this, and we are going to
get this list here. We can make it look
nice in a data frame, even though this is
definitely eligible. We'll just for good
measure and practice, we'll put it in a data frame. And Microsoft, Google,
Amazon, Google. This must be Alphabet, Tesla, Nvidia, Meta, Netflix, Disney,
and Berkshire Hathaway. This is the B class. So those are the top ten. Related companies for Apple, that's how I use the
related companies endpoint.
64. Basic Trading Strategy - Get Data: In this section of the course, we're going to dive into how to set up a basic
trading strategy. So there is a bunch of different ways that
you could do this. I just wanted to
provide an example, so you had an idea, and you can kind of
build off of that. We're going to go through my
five steps of getting there. Like I said, you know,
whatever works for you. There's not necessarily a
correct way to do this. But this is one of the ways
that you can get it set up. So we're going to start
with just getting the data. So that's where I usually begin is grabbing the
data that I need. So we're going to add a
few different cells here. And the first cell we want to import as always the
libraries that we use. So requests JSN,
and Pandas as PD. I'm going to use
polygon to grab data. It just has a
cleaner feel to it, and it has a little
bit more data, so that's what I'm
comfortable with. So I'm going to go
ahead and start setting up the template for
the request from Polygon. So we're going to
call this the URL, and we'll grab that URL in a second to grab
the aggregate data. So we're just going to
start with the OHLC data. And then we'll
expand upon that in later sections when
we want to grab additional fields
indicators, all that. We want to get the response. So that response is going
to be the request dot G, and that'll be this URL up here. And then we want to
define that data and that request as the JSI dot
loads of the Apple response. Text. That text. There you go. So let's go ahead and grab the endpoint for the aggregate. So we want to do it for Apple. We want to keep it
as the one day. I do want to do it from the beginning of 2023 up until today's market
is still open. You can see it's 226
here on a Wednesday. So I'm going to do it up until yesterday because I want
to get some recent data. I want to make sure I'm
getting enough data, so we'll do 917. And we'll go ahead and
copy this endpoint, and we'll drop that in here. And then I'm going to run this first cell and
the second cell. We didn't print out
what that looks like. Just to keep it clean for now, you've seen it in
prior lectures. What I can do is I can just show you if that makes it easier. There's what it looks
like in the JSON format. So I'm going to get rid of that. And then I'm going to go ahead and start to create
the actual data frame. So we're going to call it
this is the aggregate data. The Apple ag DF equals
pd dot data frame. You've seen this before
when creating a data frame. It's the Apple data, and as always, if you need to
go ahead and look at this, then be sure to just
run this up here you can see the JSon
structure in a dictionary. We just know off the top of our heads here because we've done
it quite a few times that we need to get the result section
of the dictionary from that JSon response. So that'll be our data frame. If I just ran that, You can see what that dictionary
that data frame looks like. I want to add in a column. We're going to add additional
fields in the future here, but just so I don't forget, I'm going to add a column, and we're going to
just call it Ticker. And this is for Apple. That's what we had created the end point out of was Apple. So we just want to make sure
we dropped that in there. And now, if I ran this,
You'll be able to see that. We'd added the ticker
column in there for Apple. We're going to go ahead and organize that stuff
later, but for now, the other thing I want to
do is to just run through that code we had done in prior lectures to convert
this into a real date time. So the first thing
we're going to do is for this data frame. We want to for the
date time column, which is labeled as
T. We want to convert that to this but as type of string. That's going to make
this right now, it's an integer. We want
to make it a string. Then we want to create
the function to remove the last three characters
because that always messes up our when
we our conversion. So we will return everything in this column ops besides
the last three characters. So everything up
until the last three, is what that is
saying right there. So then we need to apply
this to the data frame. We'll keep adding in
that data frame there, and we want it specifically
for this column. And then what we want to do
is take that data frame. Ply the name of our
function on axis one. Don't forget that part there. Then, of course, because we get that new deprecated feature of not converting it
back to an integer, it'll cause problems
in future versions. We want to then just
essentially do this. I'm going to make
this easy on myself. But instead of converting
it to a string, we want the type to be in. And then we will finally here
do the actual conversion. So that's done by
PD that data frame. P is a pan dysfunction,
two date time. I've messed that up
for two date time, and then we want to
grab this data frame. And that column, and
we want to convert that utilize the unit
equals S. Then finally, we'll just go ahead and print
the final version of this, and hopefully this T column
will be converted to the new format shift
enter to run that O, looks like I messed up. Where does it right here. So this is going
to be not DF DF, but Ag, because it's aggregates, and now this column has been converted to
the new date type. So that is it for the
first part of this, which is just the
G data section.
65. Basic Trading Strategy - Add Additional Fields: All right. The next thing
we want to do is add additional fields to this
data frame that we've pulled. So we've got the aggregates. We've got the open high low closed volume
all of that data. But we said we want to
drop in some other stuff. We want to create
a strategy based off of a technical indicator. We would need to go
and grab that data. So we're going to
use the 25 period simple moving average, so we need to go and grab that. So here's what we'll do.
We're going to start setting up the request
for the SMA 25. And how we're going to do
that is estimate 25 URL. As always, we're going to
leave that blank just for now. Actually, here's what we'll do. We'll go and get
it from Polygon, make sure you're under
technical indicators, simple moving average, Apple, make sure the window is 25, and then make sure this limit is a higher
number so that you're capturing more than enough data when we go to combine that
with the last two years, almost two years of data
that we had pulled before. So get that endpoint copied
and go ahead and paste that. And we won't have to
worry about that later. Now, we want to get the SMA 25 response variable equal to, as always, the requests. We've already got the request
library imported into this. We did earlier when
we get the aggregates into this Jupiter notebook. I don't worry about adding
the import requests again. SMA 25, we want the
data, which is equal to. We use that nice JS dot loads formatting SMA 25 response text. Then finally, we want to create
a data frame out of this, and we're going to call it
the Apple MA 25 data frame equals p data frame, and this is where we
will utilize this data, and we have to go
twice if you remember into the dictionary for
this into the results, and then into the
values section. So let's go ahead
and see what this looks like. B that up. Shift Enter. We
never closed this. Close that shift enter. All right. So here's what
that looks like for now. We want to convert
this time stamp. So what we'll do is start to
create the code for that, so convert date time. And I'm going to go ahead and copy the code from up above. There's just going to be two things that we're
going to need to do in order to change this. The first one is to change this actually
to time stamp, right? So It's currently labeled as
time stamp, as you can see. We're also going to change
it to be the T so that it aligns with the way
that it's labeled up here. So, and then we want
to relabel all these. So now what's going to happen is we're going to have two columns. One is going to be this
time stamp in this format, and the other one is
this new T column we're creating that's based off
of this time stamp one, but this T column is going to
have the proper conversion. So let's make sure we change all of these data frame labels out with the
proper variable name, and that should be
good enough for that. Let's see if we run that, what that looks like,
shift enter to run. So like I said, we
were creating it with the new new column
with the label of T so that it aligns
when we go to merge, but this time stamp
one is still here. So we're just going to do one last thing and I'm
going to squeeze that in here, which is to and we'll show
you how to do this again, but I want to for now
so we don't forget. This column is labeled as value. Say we were pulling multiple
simple moving averages. They would all be
labeled as value. We don't want that,
so we want to relabel the column name. So we're going to do that by let me just make
it easy on myself. We're going to pull
this data frame name, and we're going to set it
equal to a renamed data frame, where the columns, and
this is a dictionary, but we only need to
do it for one value is now going to be
relabeled to SA 25. We might change that later, but for now, that's where
we're going to leave it, so we'll shift
enter to run that. And you can see that
that value column is now relabeled as SEMA 25. I'm going to do the merge now
for these two data frames. So the SMA 25 data and all
of our aggregate data. Reason we want to do that so
that it's all in one place. The way we're going to merge
it is on this time column. So since we already know that it's only for Apple,
that's fine, if not, you would have to use
some logic so that you would be looking at the
Ticker name and the time. But we don't have to do that. So the merge is going
to be pretty simple. We're going to utilize
Pandas for it, and the way we'll do that is, I'm going to create
the Apple data frame by using PDs so the
Pandas, merge function. And the way we'll do
this is We're going to take first what we're
merging the other data into. So this is our main
apple ag data frame. We want to merge this with the data frame
that we just created, which was the Apple
SMA 25 data frame. We want to merge. What
do we want to merge on? We want to merge on that column. So that is T here is the
same data type as T here. And then we want to
do it as an inner so that it only returns
where they both have data. That's the reason
we set up the first one with a specific time
frame the other one, we just grabbed as much as we could to ensure we
captured all of it. So this should merge
the two together and we'll just take a peek
at it when it's done, so shift enter to run that. Forgot a comma here,
more time shift enter. Now you can see our aggregate
data is all in there. And then we have
the columns from the simple moving average
data frame as well, dropped in there for
the correct date. This time stamp is in
there as well just because it was in
that data frame. We'll show you how to drop that in the future when we're
cleaning everything up. But for now, we're just
going to do one more thing, which is when we're taking a
peek at the logic for this, we want to look at the
prior days close and SMA. So we want the previous close, and we want the previous SMA 25. So within each row, we don't only want
to look at the SMA, but what was the prior days SMA. So how we do that is we
will take our data frame, and we're going to create a
new column in the data frame. Called previous close. And then we'll take
our data frame the column that we
want to shift on, which is C. It's the close
and shift function built in. And then how many do
we want to shift? We want to shift one,
which means we want to look one back. So for this date right here, we want to be looking at the
close that was one prior. So it's going to show
up at the end of here, previous close as $222.66, and you'll see what I
mean by that in a second. And then we want to do
this for the SMA as well. So we're going to do pre SMA 25, and we want to do
it on the SMA 25. That's this and we to
shift it one time. And then what we'll do is we'll just show you
what that looks like. We'll shift enter to run
that. And now you can see. So like I said,
this previous close for this date is 12507, and you can see that the close for the
prior day is 12507. So I think that's enough data for now
in the next lecture. We're just going to go through how we can get this cleaned up because this data frame is a little bit of a
mess right now.
66. Basic Trading Strategy - DataFrame Cleanup: All right. The next part of this is the data frame cleanup. So that's taking this
data that we've pulled together to a little out of
sorts and cleaning it up. The first thing we're
going to do is actually just drop some data, so anything that we don't need. It looks like this time stamp column we're
not going to need. We already converted that to this T column in the
proper readable date time. And we're also not going
to utilize this n, which has to do with the
number of transactions. We're just going
to utilize volume. And actually, I don't even
know if we'll utilize it, but we'll keep it in there just for reference purposes for now. So how we can drop columns is just by utilizing
the drop function. So we're going to make
the new data frame, which uses the same
name equal to drop, and then we need to outline the columns
that we want to drop. And we do that in an array, so time stamp and n. Those are the two
that we want to drop, and then we will
just run this to see what that looks like to ensure
those are no longer there. And you can see that time stamp and the n are no longer here. So now the next
thing we're going to do is we are going to
rename these columns. They've got just letters, they could look a
little bit nicer, so we'll show you how to rename. So that Apple data frame, equal to that, and we
want to rename it. The reason we're setting it
equal to the same name is because we want to
keep that data frame, but just clean it up instead of creating a new data frame
and then a new data frame. Sometimes it's worth doing that so that you don't screw up. But for now, we kind of
know what we're doing, so we're just going to relabel
it with the same name. So the columns that
we want to rename. This is going to
be a dictionary. So we will start this off with the volume, which is the B. We want to relabel this. And the way we do that
is in dictionary format. We're going to give it
a nice label of volume. And then, we'll move
on to the next one, and I'm just going to kind
of fly through these. So the weighted volume. We will re label
weighted volume, then it is the open, and I'm going to take these
and make it easier myself. Just copy a bunch of them. This will be open H is the high the low and then the close. Then I'm going to relabel the ticker column to just
give it an upper case. It's going to be ticker. And then we want to do the
SMA 25 is upper case as well. And then I think we've
got a couple more here. Then we need to do
the previous close and the previous SMA. We'll do pre close. We're going to make
this labeled like that. So it looks a little nicer. Reve SA 25. I believe that's how
it's labeled, yep. And we'll do the same
kind of format here. Reve SMA 75 or 25. And then the last
thing is this T. That's actually our date time, so that's exactly how we're going to label it.
Is the date time. So now that shod rename
all of these columns, and we're just going to run
that to ensure that it has. And Shift Enter. Looks
like we never closed this. Glad that they're
now Shift Enter. And boom, you've got them all
relabeled, nice new labels. I would just say the last thing is they look a
little out of order. Like, it'd be nice
probably to just have this ticker as the
very first column. So what we're going to do is we'll show you how
to reorder it. For this one, I actually
am going to create a new data frame name so that we can know that
this is the final one. We'll just call it
final Apple data frame. This is the data we are
going to use when we're back testing and
executing strategy. So the way you do this is
you take that data frame and within two arrays, you just type out your order. So what we can do is
copy all of these. And we'll just
grab all of these. If you hold down
Control and click, it allows you to add
multiple cursors. So we're going to copy all this. Oh, actually, that's not
going to work because there's multiple spaces in between these. So here's what we'll do. That's fine. We're just
going to type it out. So first thing I want is the ticker and then we'll
just run through these. So this is just what makes the most sense
for me looking at it. It doesn't really matter
at the end of the day. If you didn't want to rename
these, it's totally fine. I just like to look
at my data frame when it's set up in somewhat
of an organized fashion. So not a required step, but it might help you. We're showing you how to
do that here at the volume weighted volume SMA 25. The previous close. The previous SMA 25. And I think that's it. Okay. So we can go ahead and run that and looks
like we made a mistake here. EMA 25. Oh, it looks like we never
properly relabeled this. That's why. So let's
try this one more time. We're going to run that.
Now we've got that. So then now for the reorder. This Estimate 25, that's the way it's labeled
in their shift enter. And now everything's
been reordered, so that tickers up at
the front date time, and then it just makes a little bit more sensors
more of a flow. So that is going to be
our final data frame. And next, we can then move into the back
testing strategy.
67. Basic Trading Strategy - Backtest Strategy: Alright, now that we've got our data all set up and cleaned, we need to move into the back
testing portion of this. So B testing is just
checking to see how a strategy would perform
based off historical data. So it's a little backwards
because you don't create your strategy until
you've back tested it. So you sort of create that
strategy within the B test, but in terms of execution, that's going to have to be
a whole new set of codes. So that's why that comes last. For now, though, we'll start to create this back
testing strategy. What we're going to do is
we're going to test to see if the previous close is below the previous
the previous EMA 25, and the current open, so the day's current open is
above the current SEMA 25, then we're going to
place a buy order. So if that's the
kind of strategy, we're going to be testing. It's going to be a
lot of code here, so just try to follow along positive video
if you need to. The first thing we need to do is because we had these shifts, we've got these two rows
that have not a number in for the previous close in the previous SMA, we just
want to remove those. So We want to remove first row. We could have done this
in the cleanup stage, but we're doing it here. For that data frame we created, all we need to do is just reset it equal to
the same data frame, but for everything
beyond the first row. So this ILOC in the first row. That's the index locator. So now that we have that, we just need a few variables. This is up to you, how
exactly you want to do these. You don't necessarily
have to hard code. Some of these things,
some of it you do, but either way, we're just
going to make it easier. So, if we're going to start
with the balance of $10,000. Remember, this is
just back testing, it's not real money, so it's up to you. I mean, e something that's
sort of realistic if you do plan on trying
to create a strategy, If you're just messing around, it can be whatever you want. We're just going to use
10,000 as a starting point, the number of shares we're
going to trade each time we enter a trade. We're
going to leave this as ten. The reason we're
creating a variable out of it is because
it's going to make it easy for us to
change that if we need to. And the same for these next two, which is our profit amount. So we if the trade gains 10%, we want to take our profit
and if if the trade loses, 5%, we want to cut our losses. So those are our
starting variables. Next, we're going to move into the actual trade
strategy BC test here. And The way we'll do
this is we're going to iterate through
each row of data to see if we need to enter a trade, and we'll do that by
using a four loop. So in order to iterate
through a data frame, you set it up where there's essentially
two dimensions of it. There's the index, which
is this and the row. So that's to grab the
column within each row. So for row in, and we're going to
utilize this data frame, the last thing you
have to do is use this function of I a rows. So it's going to iterate
through each row on the loop. So we're going to create the
logic to enter the trade. So as we had set up here, if and we're going
to open this up. There's going to be
two pieces to it because we have
if this and this. So we'll just kind of
get the bones in there, and then we'll come back here and actually put in the data. So I and this is where
that row comes in. So for the current
row that we're on, the column we're looking for is referenced as the previous close is less than the
previous SMA 25. And the current row, the open, assuming that this
trade would execute right at market open is
greater than the current. SMA 25. Then we will enter the trade. We want to take a few
variables from this. So they're going to come
in handy in a minute here, but we want to set our
take profit value, so not just that we
want to take 10%, but what does that
look like based off of the current price? So we're going to do the
take profit is equal to, and we're going to do
that open price times one plus the profit amount. So that's our take profit, and then our stop loss So when the trade is
going to stop at a loss, if we don't hit our profit, is the open times one minus the loss amount. So this is going
to give us a value that's 10% above the open. This is going to give
us a value that's 5% below the open. And then the last
thing we want to do, we're going to have a loop
within a loop because what's going to happen is
say we're going through, we're iterating,
no, no, no. Yes. This one wants to open a trade. If that's the case, we then have to analyze
the data based off of everything in the future
to figure out which day we then close the trade at. So we're going to create
a data frame that is only everything in
the future based off of when we actually
open the trade. So it's based off
the current loop. What we're going to do is take create this
data frame based on the final Apple data
frame where it is everything from the
current index forward. So that's where we can
utilize this end right here. And then we need to
create our second loop. So this is see how the current trade performs. So the other reason
you need to do this is because this is loop
through row by row, say you have two consecutive
rows that open stuff up. You don't want to
have this overlap you want this one
to go through and look first through every
row that comes after, and then the next one
to do the same thing. So that's how this is
going to function. This is going to get to a row. It's going to do the loop. It's going to go
through everything after that specific index, and then it's going to
head back to the next row. So that's why we have to
do this nested loop here. So this loop, we want
to so that we don't get our variables confused with
the four loop designations, we're going to just call
this x n and x row in, and that's just this
current dF here, and that we have to use
that same it rows to iterate and the logic for this is going to be to close the trade if
we have to take profit or to close the trade
if we have to stop loss, otherwise, just keep going. I row the close, as we're iterating
through each of these, it's greater than
the take profit, actually will do greater than or equal to because
if it's equal to, we want to close it as
well once it hits it. Then we're going to create
this gain loss variable. So that's going to be how much we would gain on the trade. We're going to call it gain loss because we're going
to use the same thing for when we're doing
the stop loss. So this is the calculated
by taking the close of the current four
loop and subtracting the close of the
original four loop row. So then we need to
update our balance if this take profit does hit, and the balance is
equal to the balance, the current balance
plus the gain loss. Now, if this hits the
take profit, that's it. We want to break it. We don't want this to keep
looping through. That'll be the stopping point. It doesn't need to
go all the way to the end for whatever reason. We don't want to go ahead
and iterate through again so that it picks up some other form of the code
if it fell back down to the stop loss even after it hit the take profit or
whatever it may be. So we have to break it. Next is ECIF, The row close, and this is going
to be for hitting the stop loss is less than the stop loss
that we had created up top, which is 5% below the
current day's open price. The gain loss then is going to equal the reverse
of what we just did. So it's the row close,
the original one. Minus x row close. The balance is then going to be the same equation as above. So we're adding that
gain loss to it. If this is a negative number, that means it's
technically subtracting. Then we want to break that. Otherwise, we're just
going to pass and continue to search the rows to see until we
hit one of those. To kind of visualize this. I'm going to add
a print statement for each of the original loops. So how we'll do that is and
I'll take this down a row. We want to print,
and I'm going to use an F string literal, which allows me to add
variables within a string, utilizing the curly brackets. So I'm going to say the trade. I'm going to label when
the trade happens. So this is pulling the
clothes for each row. I'm going to pull
the date so that I can see when a trade happened, so row date time, and we can oops, need to add that at
the end of here, curly bracket with let's
say gain or loss of, and then what we want
to do is add in here. O gain loss variable so that we can see how much
we actually gained your loss. And the one other thing
I actually want to do we can't forget to close that is I want to round this so
that we only show. It's going to give us a ton
of points after the decimal, a ton of values after the
decimal, I should say. I want this to only show 22
values after the decimal, so Run the nearest sent there. Then the last thing we'll do is close off this if
statement with an else pass. So if we're not going
to open up a trade, you can just go ahead and pass. And then the final
thing I want to do is print the final balance, and so we'll use
string literal again. We'll say final balance. And we'll pull through that
balance variable. Balance. Actually, just so that we
can get a little spacing. This is just to give
you a line break. You can type in print and then just add in
an empty string. But now we're going to
go ahead and run this, see if we have any issues here. This should hopefully print out each of our trades in
the final balance. So shift, run that. Looks like we do have an error. We're going to have
to go and fix this. So that loss shod
say loss amount. All right. Let's
check one more time. Shift E, another err. Uh, we're missing an L here. So current DF. Here's that shift enter. This is what happens
with your hard code, and now that's good to go. So we fix those up. We can see all of
our trades here. When they happened,
what the gain was, looks like there was no losers. So none of them
hit the stop loss. And we ended with the final
balance of $10,123.46. So that is the back
testing of it. Now we will show you how you can actually execute
the strategy.
68. Basic Trading Strategy - Execute Strategy: All right, in this final lecture of this section on the creating
a basic trading strategy, we're going to
create the code to actually execute the strategy. So for purposes of this course, we're just doing it within
the same Jupiter notebook that we've been using for
all of the other lectures. But something you'll
probably want to get as a scheduled task
using some sort of website, whether you have
it hosted on like Python anywhere or you're using data breaks or
any other website. Maybe digital ocean allows
you to run scheduled scripts, where it will run
every day at 9:30 A.M. And you don't have to actually manually execute it yourself. Or 930 is just the open time for the market or
maybe you wanted to execute it at a
different time or always be looking to open a
trade, whatever it may be, Like I said, you know, you're probably not going to
want it all to be in the same place as all of your other code that you've
done for back testing, but we're going to
keep it in here for now just so we can
outline the code for you, and then you can choose what
you want to do with it. So, like I said, this is for a buy order where
you would run this, whether you're
doing it manually, which is not suggested or if you have a scheduled task
on some sort of server, it would run at market open. We want to first create
the variables for it. So we want this just trade ten shares
per trade when it opens. The reason we outlined that
is because then you can use this variable within
your code and easily change it instead of having to go and change
it within the code. It's simple for you to find. Same with the profit amount, which we're going to do at 10%, just like we did
in the back test and the loss amount at 5%, just like we did before. What you want to do is
ensure that you are, especially if we're using the same strategy as this back test. We want to grab the data
before the market opens. So before market open, get data so that
it's ready to go, and we want the previous days close because that's going
to help us make a decision. Technically, you could
run this at market open. This just might make it
a little bit faster. T is everything in
terms of trading. But we want the previous close only looking at the
final value for that. Close boom. There's that and
the previous SMA is equal to this final and
we'll do the same thing here. All right. Change
that to the SMA. There are those values
that you would want to. The next thing we want
to do is actually, I'm going to open up a new cell here and split this apart. So now, when the market opens, we want to get data. So this is previous data here. We want to get the
current days data. So we're going to
do that through setting up a request
from Polygon. Let me get the
template created here, and we'll get the endpoint
for current days data. So in Polygon, we're going to be looking for daily open close. Will be for the current day if it runs once the market opens. So we want it for Apple. We want it. You can
hard code this. We're going to do it for today. But I'd suggest having a
today function in there, you can pull the today's date, and then you won't have to worry about updating this endpoint, but we're just going
to add in there. The manual form of it. The current response equals
requests dot G as always, and we're going to
take this current URL. And the current data is
equal to JCN dot loads, and we want to grab this text, the current open will
be from this data. We want it to be open. And we can actually
test to ensure we're pulling that
correctly real quick here. So let's do this. Yeah, that's the open. That's what we
want to pull here. Let's get rid of that.
Let's get rid of that. And we can go ahead and move
on then to the current days. SMA 25. We can copy this code, but we can change this to SMA, so we're updating
that and then we want that for here for
here and for here. What we want to do is then get
the endpoint from Polygon, so we'll come to
simple moving average. We want to do it for today. Like I said, we're
hard coding this, but I would suggest not
doing that. 25 window. We're going to copy this, and
we will paste that in here. And then what we'll do is we're actually going to check to make sure we're
pulling that data correctly. Shift enter run that. Okay. So we're just
getting it for today, so we can get rid of that, and the other thing we
need to do then is to just make sure we're grabbing
the correct value there. So if you saw from
what I just did, and maybe I'll just
walk through it. You need to first go in the
dictionary to get results. Then we need to grab the values. There's only one value. We
want to grab the first one. This is in an array,
this right here, so we have to get we have to utilize the actual index for it. And then the last thing we want to get is the value we don't
care about the time stamp, we want the value of it, oops. And that should
be good for that. And so we can go
ahead and run that. And then the last thing on this execution is actually
running the strategy. So we can go ahead and
start plotting that out. And run strategy, and then we create our if
statement. All right. And actually, before we continue with this, I just realized, this is grabbing the
first row we want, the value for the
most previous row. So you get that using a
minus one, it goes reverse. So that's going to get us
our correct values for the most previous from
the data frame from what we had
already pulled before. You'd want to do this before the current day actually opened up so that you're not pulling the current days as the most
previous values for these. If you did, for whatever reason, then you would just make
sure that those are twos, but for this, it just
needs to be a one. So Back to the strategy here. So we need to create
the if statement, which is going to tell us if
we can enter into a trade. So we'll get the bones in here and just like
our back test, but we're going to use the
variables that we've created. So the previous SMA is less
than the previous close. Sorry. Previous close is
less than the previous SMA, and the current open is
greater than the current SMA, and it looks like we
actually labeled this as current SMA open. We just wanted to label this as we'll call current SMA 25. Current EMA 25. Sorry for moving around so
much here. It's a lot of code. So if you need to pause, then by all means, do so you can understand
what we're doing here. Once we've done this,
if this is true, then we're going to
open up that trade. We need to define
our take profit, which is the current open times one plus the profit amount
that we had defined up here. And our stop loss equal
to the current open. So assuming this is ran right
at the open of the market. Times one minus the loss amount. So that's going to give
us stop loss of 5% below the current days open
and a take profit of 10% above the
current days open. So now let's execute
this by order. First thing we need to
do is come to Alpaca, and this is where we can actually create
the code for this. It's going to make
it nice and easy, as you had seen earlier. So let's go ahead and come to Alpacas API reference under
orders, create order. We're going to do it for Apple. The quantity. We
might hard code that, but for now, put in ten just
like we did within our code. The type market, and we'll
leave these all the same. The one thing that I
do want to add here, is Z Bta open is a take
profit and a stop loss. So the way you have to set
these up is by adding them. So we need to add the field. You need to define
for the take profit, a limit price, and you have
to type it in just like that. We're going to update this
value within our code. And then for the stop loss, you need to add in a stop price. So once we have that, then we should be good
to go to copy this. So we'll copy that request. We'll come back over,
and we'll paste it, make sure everything is
indented as it should. I'm going to remove this request an import because
it's already in here. We don't need it.
Now, the one thing we need to update is
the take profit value. So what we'll do is
because this is a string, we want to make sure we
keep the same data type. So we're going to
create a string. Within that, we're going to
put our take profit value that we had created up here. And then we're going
to do the same thing for the stop loss. And this will be the stop loss that we had created up here. And then that should
be good to go. The last thing is,
we will just end this if statement with the pass, and Then it will pass if these are not true
and will not enter a trade. So I would execute this. It's past market close. This should work here as
just a basic strategy. I all values are true here. This is how you would execute
a basic trading strategy. As I've said in the course, don't take these as something that you should
go ahead and just perform. This probably won't be
a winning strategy. I just wanted to
give you an idea of how you can set it up. Create your own strategies to hopefully become profitable, but always make sure
you're testing. It's best when you're doing
this stuff to utilize a paper account so that you're
not losing your own money. This is it's difficult, can be done, but it's difficult. So make sure you take all
the proper precautions. But that is going to wrap up this section on creating
a basic trading strategy. I recommend that you go
back for any parts that you don't understand and pause
and review it and test, run the code yourself to
see how it's functioning. And that should give you a better idea as
to how to do this. But come up with other ideas, pull in different indicators, whatever it may be,
have some fun with it. So that will be the end of the basic
trading strategy lecture.
69. BONUS: Stop Loss & Take Profit: Right, I'm going
to show you how to utilize a take profit and a stop loss when
placing an order on the Alpaca Markets API. We're going to do this on Navida currently trading at 1:36 48 in order to build out
the request for this. We're going to head
over to the API here. And first, we're
just going to take a look at the documentation. Now, they call this
a bracket order. So if we go look at
the bracket order, it's going to show us
the actual structure that our payload needs to be, because what this is doing is it's placing your
original order, and then it's placing
one cancels other order. So whether the take profit
hits or the stop loss hits, it's going to cancel
the other one out. So let's build the request
based off of this right here. I'm actually going to just
copy this to ensure that we have the right structure, and I'm going to just
paste it in here for now just as a reference because I'm going to be switching
this documentation over to the API reference for um, in order to build a
request, like I said. So there's a few things we
have to pay attention to. The first thing, we have
to type in the ticker, and ALPACa makes it nice. It just starts to build
out your request here. Before we forget,
let's get our key and our API key directly
on the dashboard. If you don't have them,
you can regenerate them. So go ahead and click your key, copy that over and then go grab the secret key and
then copy that over, and that's going to populate
down here in the request. Now, let's do this
for a quantity of ten. Going to do a buy. It'll be a market buy
of Navida ten shares right away with the stop
loss and take profit. We're going to do a good till canceled order. So
leave this open. This market order
until it is canceled. And then this is where we can begin to build out
some of the other items. So we do want to make sure
that we have bracket in here. Um, you need that order
class or the stop loss and take profit are not going
to be placed correctly. So do not forget to this. I know it's kind of
confusing because it has it kind of great
out in the beginning. You need to click on Bracket. So then the next piece of it is we can build the T profit. So, like I said, what are
we trading at right now? 13662, let's say we want
to take profit at 1:40. So very specifically,
you have to type this in exactly how I do. So in the new key,
it'll be a limit order. So you type in limit price. And like I said, 140 is the value on that
for the take profit, and then the stop loss is
going to be a stop limit. So there's actually
two different values we have to place in here. The first is the stop price. So like I said, it's trading
at 1:36 or whatever that is, whatever I said, we'll have
a stop price of 13050. And then the limit price after that stop hit, this
is a stop limit. After that stop hits
is going to be 130. Like I said, you need to
type in this limit price, stop price and limit price right here exactly
how I have it. Make sure you have
it placed in here. That's the way it's
required to do. Why they don't give
you presets for it? I'm not sure, but just make sure you're
paying attention to that. So that should be good. Now if we go ahead and
copy this request over, we can Paste that in there, make sure that we
have all the pieces. So we have the side by
the symbol, the type, so side, the symbols down here in the type
quantity, time and force. So we've got a quantity. We have a time and
force. We have the order class, important one. That's the last item, and then we have our take
profit and our stop loss. So I'm going to get rid of this, and we should be actually, I'm going to do one more thing. I'm going to import JSON because when you print the
return response, it looks just in paragraph
format. I like JSON. It shows you in JSON format. So import that JCO dot
loads, Shift Enter Run. It's going to give you
this long return message because it's technically
placing three different orders. And if we come to our
dashboard and scroll down, we can see that the Navdia
market By was placed, and we have this
stop limit at 1:30, and we have this limit
to sell at 1:40. That's our take profit
there. So, you know, that's kind of the way you
have to look at it to see that your stop loss and take
profit are actually placed. But if you have the three
trades placed right there, one of them being the
actual original order, and then these other two
orders that are contingent on the price moving up or
down, then you're good to go. So that is the take profit and stop loss in Alpaca Markets API.
70. Course Conclusion: All right, you have made it to the conclusion
of this course. I want to say, thank you. We appreciate you
taking the course. If you do have any questions, feel free to reach out. We'll be sure to address those. Any suggestions as well, things that might
need to be added, changed, expanded upon,
whatever it may be. We do plan on updating
the course as need be, whether it's something that we realize or something
that you realize. And finally, congratulations, you did it. You
completed the course.