Skip to content
Advertisement

Get the average difference between two values in time period

What I have: A single table with ids and prices for date and time.

What I want to do: To get the average difference of price for every id between the first and 15 minute of every day. Conditions: I also want to use the last available price in 15 minutes if the 15 is missing. For example if 15 is missing, use the price in 14 minutes.

What I did: My first step was to get the price after 15 minutes of every day for every id.

My code (I did a lot of tests with it, sorry if it doesn’t look good and optimised enough) to get the last price(but not last available) in the 15 minutes interval:

What I didn’t do:

  • get the last AVAILABLE price in that interval.
  • get the first price in that interval and use it in the same query with the last price in the interval
  • If I got both prices then I can use AVG and Group By to get the needed value.

Expected result (example): Table:

Result:

I have never used “Partition By”, but maybe here is the place to start with it? It’s my own project, where I want to test some statistical ideas for the stock market. Thanks in advance!

You can use this link where it’s a sample for testing: http://sqlfiddle.com/#!17/83597/1

Advertisement

Answer

If I have understood correctly, you want to:

  1. List the prices of each stock from each day during the first 15 minutes of the day
  2. Identify the first and last (as defined by date_value) of the prices listed in step 1
  3. Calculate the difference between the prices identified in step 2, by stock and day
  4. Calculate the average of the differences calculated in step 3, by stock

If I have interpreted your question correctly, then:

You may find that you need to wrap the calculation of open_price_diff with ABS, but I have not done that in the example above.

sqlfiddle

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