Hello all,
I am trying to compare volume at one point in the day to volume over the last few days. I am having trouble calculating volume at a single point in time (in my case, 17 minutes from the close).
I can see the data, but I don't know how to access it and work with it. The code below:
from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Common")
AddReference("QuantConnect.Algorithm")
from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
class BasicTemplateAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2018,5,25) #Set Start Date
self.SetEndDate(2018,5,29) #Set End Date
self.SetCash(20000) #Set Strategy Cash
self.AddEquity("SPY", Resolution.Second)
# schedule an event to fire every trading day, 17 minutes before market close
# Use SPY to represent the active market here in the US
self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.BeforeMarketClose("SPY", 17), self.TradeBeforeMarketClose)
def TradeBeforeMarketClose(self):
minHistory = self.History(["SPY"], 400, Resolution.Minute).sort_index(level='time', ascending=True)
for k,v in minHistory.items():
self.Debug(k)
self.Debug(v)
results in the following output:
Launching analysis for 45e868156b94757135cc0d4c81e4b26b with LEAN Engine v2.4.0.0.3824
27 | 12:50:53:
close
28 | 12:50:53:
symbol time
SPY 2018-05-24 15:34:00 272.970
2018-05-24 15:35:00 273.010
2018-05-24 15:36:00 272.930
2018-05-24 15:37:00 272.880
2018-05...
29 | 12:50:53:
high
30 | 12:50:53:
symbol time
SPY 2018-05-24 15:34:00 273.085
2018-05-24 15:35:00 273.020
2018-05-24 15:36:00 273.060
2018-05-24 15:37:00 272.970
2018-05...
31 | 12:50:53:
low
32 | 12:50:53:
symbol time
SPY 2018-05-24 15:34:00 272.940
2018-05-24 15:35:00 272.970
2018-05-24 15:36:00 272.920
2018-05-24 15:37:00 272.870
2018-05...
33 | 12:50:53:
open
34 | 12:50:53:
symbol time
SPY 2018-05-24 15:34:00 273.050
2018-05-24 15:35:00 272.970
2018-05-24 15:36:00 273.005
2018-05-24 15:37:00 272.940
2018-05...
35 | 12:50:53:
volume
36 | 12:50:53:
symbol time
SPY 2018-05-24 15:34:00 93906.0
2018-05-24 15:35:00 56311.0
2018-05-24 15:36:00 77790.0
2018-05-24 15:37:00 120558.0
...
37 | 12:50:53:
close
38 | 12:50:53:
symbol time
SPY 2018-05-25 15:34:00 272.150
2018-05-25 15:35:00 272.210
2018-05-25 15:36:00 272.180
2018-05-25 15:37:00 272.220
2018-05...
39 | 12:50:53:
high
40 | 12:50:53:
symbol time
SPY 2018-05-25 15:34:00 272.240
2018-05-25 15:35:00 272.210
2018-05-25 15:36:00 272.200
2018-05-25 15:37:00 272.250
2018-05...
41 | 12:50:53:
low
42 | 12:50:53:
symbol time
SPY 2018-05-25 15:34:00 272.130
2018-05-25 15:35:00 272.130
2018-05-25 15:36:00 272.130
2018-05-25 15:37:00 272.150
2018-05...
43 | 12:50:53:
open
44 | 12:50:53:
symbol time
SPY 2018-05-25 15:34:00 272.220
2018-05-25 15:35:00 272.150
2018-05-25 15:36:00 272.200
2018-05-25 15:37:00 272.180
2018-05...
45 | 12:50:53:
volume
46 | 12:50:53:
symbol time
SPY 2018-05-25 15:34:00 104094.0
2018-05-25 15:35:00 44736.0
2018-05-25 15:36:00 47857.0
2018-05-25 15:37:00 58802.0
...
47 | 12:50:54:
Algorithm Id:(45e868156b94757135cc0d4c81e4b26b) completed in 1.05 seconds at 45k data points per second. Processing total of 47,601 data points.
48 | 12:50:54:
Backtest deployed in 15.716 seconds
49 | 12:50:55:
Your log was successfully created and can be retrieved from: https://www.quantconnect.com/backtest/54505/1435476/45e868156b94757135cc0d4c81e4b26b-log.txt
How do I add up all of the volume so far today? Thanks!
Jing Wu
Hi Ted,
self.History() returns a pandas dataframe. You could get the volume series and add them up
hist = self.History(["SPY"], 400, Resolution.Minute) volume = hist.loc["SPY"]["volume"] sum = sum(volume)
Ted Murphy
I ended up doing something like:
def load_data(self): dayHistory = self.History(self.MySymbols, 5, Resolution.Daily) minHistory = self.History(self.MySymbols, TimeSpan.FromDays(1), Resolution.Minute) self.vols = {} for symbol in self.MySymbols: self.vols[symbol.Value] = list(dayHistory.loc[symbol.Value]['volume']) # add up the volume for the day dayVolume = 0 try: for k,v in minHistory.loc[symbol.Value]['volume'].items(): if k.day == self.Time.day: dayVolume = dayVolume + v except: pass # append the summed volume self.vols[symbol.Value].append(dayVolume)
James Parrish
Could you provide an example for average volume (say 10 or 30 days averaged)? Would greatly appreciate it!
Jing Wu
To calculate the average volume of the last N days, you can use the rolling window to save the volume and use np.mean() to compute the mean. For example
class BasicTemplateAlgorithm(QCAlgorithm): '''Basic template algorithm simply initializes the date range and cash''' def Initialize(self): self.SetStartDate(2018, 1, 1) self.SetEndDate(2018, 1, 10) self.spy = self.AddEquity("SPY", Resolution.Daily).Symbol self.volume_win = RollingWindow[Decimal](10) hist = self.History([self.spy], 30, Resolution.Daily) # initialize the rolling window for tuple in hist.loc[str(self.spy)].itertuples(): self.volume_win.Add(tuple.volume) def OnData(self, data): self.volume_win.Add(data[self.spy].Volume) if self.volume_win.IsReady: volume = [i for i in self.volume_win] ave_vol = np.mean(np.array(volume)) self.Debug(str(ave_vol))
James Parrish
Wow- very fast response. Thanks so much!
James Parrish
Jing- I implemented the code you provided and am testing a few things out.
Just curious as to what the difference between OnData(self, data) and EveryDay(self) is.
My end goal is to run this at a few specific times per day in EveryDay, instead of running constantly in OnData. When I attempt to use EveryDay(self), there is no data, but when I try to use EveryDay(self, data), it doesn't work either. Any guidance you can provide is appreciated!
Jing Wu
OnData(self, data) is called based on the resolution you set when you request the data with self.AddEquity(symbol, resolution).
In scheduled event,
self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.BeforeMarketClose("SPY", 10), self.Rebalance) def Rebalance(self): # this method is called at 10 minutes before the market closes every day
EveryDay() is used to specify the event should fire every day. It is not an event handler method. You need to add a method in schedule event like "Rebalance()" in this example. This "Rebalance" method is scheduled to be called 10 minutes before the market closes.
To run this method at a few specific times within a day, you can add multiple scheduled event. Please see the documentation
The "Rebalance()" method here does not contain the slice data like in OnData(self, data). You can save the slice in OnData(). Once the slice is updated, you'll get the new slice in Rebalance method.
def OnData(self, data): self.slice = data def Rebalance(self): # self.slice
Sheikh Pancham
Hi QC Support,
I am trying to get daily volume for BTCUSD. However, when I do this:
I get this:
Please advise.
Thanks.
Sheikh
Louis Szeto
Hi Sheikh
The QuoteBars which default to obtain in data slice does not contain volume data of the trading volume of certain crypto in that exchange. You could use TradeBars to obtain that instead.
Hope this helps
Cheers
Louis
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 QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect 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. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
Sheikh Pancham
Awesome, thanks Louis, that works!
Sheikh
Ted Murphy
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 QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect 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. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!