Skip to content
Advertisement

How to get prior close when you have all stocks in a single DF?

Sorry for the noob question. I have a bunch of stocks in a sqlite3 database:

JavaScript

When I print the df, it gives me the following (where each stock_id refers to a unique stock, e.g APPL):

JavaScript

I need to target each unique stock_id individually, and get the prior close.

I know if each stock was in its own separate dataframe, I could do something like this:

JavaScript

But when I’ve tried that, because everything in one dataframe, then you get one stock getting the previous close of an entirely different stock, which isn’t what I want.

So my question:

What’s the best to achieve splitting out all these different stocks from one single dataframe and being able to target them individually, and get the previous close price of each stock?

Advertisement

Answer

If I understand the question correctly, you just want the close of the previous row within each stock group. You can do that easily:

JavaScript

or, before setting the index to stock_id:

JavaScript

On your data sample:

JavaScript

Side note: try to not use inplace=True all over the place. It will cause you trouble in the long run (see e.g. here).

Personally, I would prefer this format:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement