Research/KitchenSinkQuantBookTemplate.ipynb
The following example is ready to be used in our Docker container, reference the readme for more details on setting this up.
In order to use this notebook locally you will need to make a few small changes:
Either create the notebook in your build folder (bin/debug) or set working directory of the notebook to it like so in the first cell:
%cd "PathToLean/Lean/Launcher/bin/Debug/
Run the following command in another cell to load in QuantConnect libraries:
%run start.py
# Load in our startup script, required to set runtime for PythonNet
%run ../start.py
# Create an instance of our QuantBook
qb = QuantBook()
Our script start.py automatically loads an instance of the web API for you to use.**
Look at Lean's Api class for more functions to interact with the cloud
config.json# Show that our api object is connected to the Web Api
print(api.Connected)
# Get our list of projects from the cloud and print their names
projectResponse = api.ListProjects()
for project in projectResponse.Projects:
print(project.Name)
Checkout the QuantConnect docs to learn how to select asset data.
spy = qb.AddEquity("SPY")
eur = qb.AddForex("EURUSD")
btc = qb.AddCrypto("BTCUSD")
fxv = qb.AddData[FxcmVolume]("EURUSD_Vol", Resolution.Hour)
We can use the QuantConnect API to make Historical Data Requests. The data will be presented as multi-index pandas.DataFrame where the first index is the Symbol.
For more information, please follow the link.
# Gets historical data from the subscribed assets, the last 360 datapoints with daily resolution
h1 = qb.History(qb.Securities.Keys, 360, Resolution.Daily)
# Plot closing prices from "SPY"
h1.loc["SPY"]["close"].plot()
# Gets historical data from the subscribed assets, from the last 30 days with daily resolution
h2 = qb.History(qb.Securities.Keys, datetime(2014,1,1), datetime.now(), Resolution.Daily)
# Plot high prices from "EURUSD"
h2.loc["EURUSD"]["high"].plot()
# Gets historical data from the subscribed assets, between two dates with daily resolution
h3 = qb.History([btc.Symbol], datetime(2014,1,1), datetime.now(), Resolution.Daily)
# Plot closing prices from "BTCUSD"
h3.loc["BTCUSD"]["close"].plot()
# Only fetchs historical data from a desired symbol
# NOTE: This will return empty when ran locally because this data is not included
h4 = qb.History([spy.Symbol], timedelta(360), Resolution.Daily)
# or qb.History(["SPY"], 360, Resolution.Daily)
# Only fetchs historical data from a desired symbol
# NOTE: This will return empty when ran locally because this data is not included
h5 = qb.History([eur.Symbol], timedelta(30), Resolution.Daily)
# or qb.History(["EURUSD"], 30, Resolution.Daily)
goog = qb.AddOption("GOOG")
goog.SetFilter(-2, 2, timedelta(0), timedelta(180))
option_history = qb.GetOptionHistory(goog.Symbol, datetime(2015, 12, 24))
print (option_history.GetStrikes())
print (option_history.GetExpiryDates())
h7 = option_history.GetAllData()
es = qb.AddFuture("ES")
es.SetFilter(timedelta(0), timedelta(180))
future_history = qb.GetFutureHistory(es.Symbol, datetime(2013, 10, 7))
print (future_history.GetExpiryDates())
h7 = future_history.GetAllData()
We will get a pandas.DataFrame with fundamental data.
data = qb.GetFundamental(["AAPL","AIG","BAC","GOOG","IBM"], "ValuationRatios.PERatio")
data
We can easily get the indicator of a given symbol with QuantBook.
For all indicators, please checkout QuantConnect Indicators Reference Table
# Example with BB, it is a datapoint indicator
# Define the indicator
bb = BollingerBands(30, 2)
# Gets historical data of indicator
bbdf = qb.Indicator(bb, "SPY", 360, Resolution.Daily)
# drop undesired fields
bbdf = bbdf.drop('standarddeviation', 1)
# Plot
bbdf.plot()
# For EURUSD
bbdf = qb.Indicator(bb, "EURUSD", 360, Resolution.Daily)
bbdf = bbdf.drop('standarddeviation', 1)
bbdf.plot()
# Example with ADX, it is a bar indicator
adx = AverageDirectionalIndex("adx", 14)
adxdf = qb.Indicator(adx, "SPY", 360, Resolution.Daily)
adxdf.plot()
# For EURUSD
adxdf = qb.Indicator(adx, "EURUSD", 360, Resolution.Daily)
adxdf.plot()
# Example with ADO, it is a tradebar indicator (requires volume in its calculation)
ado = AccumulationDistributionOscillator("ado", 5, 30)
adodf = qb.Indicator(ado, "SPY", 360, Resolution.Daily)
adodf.plot()
# For EURUSD.
# Uncomment to check that this SHOULD fail, since Forex is data type is not TradeBar.
# adodf = qb.Indicator(ado, "EURUSD", 360, Resolution.Daily)
# adodf.plot()
# SMA cross:
symbol = "EURUSD"
# Get History
hist = qb.History([symbol], 500, Resolution.Daily)
# Get the fast moving average
fast = qb.Indicator(SimpleMovingAverage(50), symbol, 500, Resolution.Daily)
# Get the fast moving average
slow = qb.Indicator(SimpleMovingAverage(200), symbol, 500, Resolution.Daily)
# Remove undesired columns and rename others
fast = fast.drop('rollingsum', 1).rename(columns={'simplemovingaverage': 'fast'})
slow = slow.drop('rollingsum', 1).rename(columns={'simplemovingaverage': 'slow'})
# Concatenate the information and plot
df = pd.concat([hist.loc[symbol]["close"], fast, slow], axis=1).dropna(axis=0)
df.plot()
# Get indicator defining a lookback period in terms of timedelta
ema1 = qb.Indicator(ExponentialMovingAverage(50), "SPY", timedelta(100), Resolution.Daily)
# Get indicator defining a start and end date
ema2 = qb.Indicator(ExponentialMovingAverage(50), "SPY", datetime(2016,1,1), datetime(2016,10,1), Resolution.Daily)
ema = pd.concat([ema1, ema2], axis=1)
ema.plot()
rsi = RelativeStrengthIndex(14)
# Selects which field we want to use in our indicator (default is Field.Close)
rsihi = qb.Indicator(rsi, "SPY", 360, Resolution.Daily, Field.High)
rsilo = qb.Indicator(rsi, "SPY", 360, Resolution.Daily, Field.Low)
rsihi = rsihi.rename(columns={'relativestrengthindex': 'high'})
rsilo = rsilo.rename(columns={'relativestrengthindex': 'low'})
rsi = pd.concat([rsihi['high'], rsilo['low']], axis=1)
rsi.plot()