Back to Community
daily volume value, just before the close

Hi fellow Quantopians,
quick question regarding new Q2 platform.

Have an algo where I'm evaluating some stock parameters 5 minutes before the close and then making decision.

Problem that I'm facing is that, based on available documentation:
1) using history function like:
data.history(context.security,fields='volume',bar_count=1,frequency='1d')
would give me volume for previous day, not info for that particular day (up until 5 mins before the close).

I was thinking that one solution would be to sum up all minute values from open until that moment and then use .mean().

Anyone knows how to it by some more elegant way?

2) if I want to evaluate average volume for last 3 days, INCLUDING volume for that particular day ((day-2)+(day-1)_(day-0 (but up to 5 mins BC)), what would be someone's simple solution?

thanks in advance

5 responses

Hi Saki,
Attached is some quick code to try and show how to do this. I use the pipeline dollar volume factor to get some high volume stocks. I then schedule my history_vol function to run once per day 5 minutes before the market close.

In my history_vol function, I call data.history(context.security_list,fields='volume',bar_count=3,frequency='1d') and log the results for the first security in the list.

What you see looks something like this,

2016-01-04 history_vol:53 INFO 

Equity(24 [AAPL])  
2015-12-30 00:00:00+00:00           20647576  
2015-12-31 00:00:00+00:00           34407332  
2016-01-04 00:00:00+00:00           46231809  

This is the full volume for 12/30/15 and 12/31/15 and the sum of all traded volume for 1/4/16 up to 5 minutes before the close.

Let me know if you have any questions.

KR

Clone Algorithm
7
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
"""
This is a template algorithm on Quantopian for you to adapt and fill in.
"""
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.factors import AverageDollarVolume
 
def initialize(context):
    """
    Called once at the start of the algorithm.
    """   
  
    # Record tracking variables at the end of each day.
    schedule_function(history_vol, date_rules.every_day(), time_rules.market_close(minutes=5))
     
    # Create our dynamic stock selector.
    attach_pipeline(my_pipeline(context), 'my_pipeline')
         
def my_pipeline(context):
    """
    A function to create our dynamic stock selector (pipeline). Documentation on
    pipeline can be found here: https://www.quantopian.com/help#pipeline-title
    """
    pipe = Pipeline()
     
    # Create a dollar volume factor.
    dollar_volume = AverageDollarVolume(window_length=1)
    pipe.add(dollar_volume, 'dollar_volume')
 
    # Pick the top 1% of stocks ranked by dollar volume.
    high_dollar_volume = dollar_volume.percentile_between(99, 100)
    pipe.set_screen(high_dollar_volume)
     
    return pipe
 
def before_trading_start(context, data):
    """
    Called every day before market open.
    """
    context.output = pipeline_output('my_pipeline')
  
    # These are the securities that we are interested in trading each day.
    context.security_list = context.output.index
     
def history_vol(context, data):
    """
    Assign weights to securities that we want to order.
    """
    
    history_df = data.history(context.security_list,fields='volume',bar_count=3,frequency='1d')
    
    log.info(history_df.iloc[0:3,1:2])
 

There was a runtime error.
Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

Hi Karen,
thanks a lot for your feedback.

In this case, I used history and volume field, the way you suggested.

Could you please briefly describe meaning of :
log.info(history_df.iloc[0:3,1:2]) , especially ranges inside.

What is 1:2 or which of these values is related to volume up to 5 mins before the close?

Thanks a lot of your time

Karen,
since I see from other posts that you are expert in Q topics, can pipeline somehow work on list of predefined stocks, instead of whole universe?
Meaning having a list of known securities, can you apply those pipeline factors and ranks?

thanks in advance

Saki,
The log line log.info(history_df.iloc[0:3,1:2]) was just trying to limit the logs to one security of data. adding .iloc to the dataframe produced by the call to history lets me limit the results.

I was able to get the volume for the entire day 5 minutes before the close because I scheduled the function history_vol to happen 5 minutes before the end of the day. The help documentation on daily history might be useful.

Pipeline does not work with a list of predefined stocks. It's main goal is for dynamically selecting groups of stocks.

Karen,
Thanks a lot