Back to Lean

Load in our startup script, required to set runtime for PythonNet

Research/KitchenSinkQuantBookTemplate.ipynb

2.4.0.17.7 KB
Original Source

Welcome to The QuantConnect Research Page

Refer to this page for documentation https://www.quantconnect.com/docs/research/overview#

Contribute to this template file https://github.com/QuantConnect/Lean/blob/master/Research/KitchenSinkQuantBookTemplate.ipynb

QuantBook Basics

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:

  1. 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/

  2. Run the following command in another cell to load in QuantConnect libraries:

    %run start.py

Start QuantBook

  • Add the references and imports
  • Create a QuantBook instance
python
# Load in our startup script, required to set runtime for PythonNet
%run ../start.py
python
# Create an instance of our QuantBook
qb = QuantBook()

Using the Web API

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

**Note: This will only connect if you have your User ID and Api token in config.json
python
# Show that our api object is connected to the Web Api
print(api.Connected)
python
# Get our list of projects from the cloud and print their names
projectResponse = api.ListProjects()
for project in projectResponse.Projects:
    print(project.Name)

Selecting Asset Data

Checkout the QuantConnect docs to learn how to select asset data.

python
spy = qb.AddEquity("SPY")
eur = qb.AddForex("EURUSD")
btc = qb.AddCrypto("BTCUSD")
fxv = qb.AddData[FxcmVolume]("EURUSD_Vol", Resolution.Hour)

Historical Data Requests

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.

python
# Gets historical data from the subscribed assets, the last 360 datapoints with daily resolution
h1 = qb.History(qb.Securities.Keys, 360, Resolution.Daily)
python
# Plot closing prices from "SPY" 
h1.loc["SPY"]["close"].plot()
python
# 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)
python
# Plot high prices from "EURUSD" 
h2.loc["EURUSD"]["high"].plot()
python
# 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)
python
# Plot closing prices from "BTCUSD" 
h3.loc["BTCUSD"]["close"].plot()
python
# 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)
python
# 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)

Historical Options Data Requests

  • Select the option data
  • Sets the filter, otherwise the default will be used SetFilter(-1, 1, timedelta(0), timedelta(35))
  • Get the OptionHistory, an object that has information about the historical options data
python
goog = qb.AddOption("GOOG")
goog.SetFilter(-2, 2, timedelta(0), timedelta(180))
python
option_history = qb.GetOptionHistory(goog.Symbol, datetime(2015, 12, 24))
print (option_history.GetStrikes())
print (option_history.GetExpiryDates())
h7 = option_history.GetAllData()

Historical Future Data Requests

  • Select the future data
  • Sets the filter, otherwise the default will be used SetFilter(timedelta(0), timedelta(35))
  • Get the FutureHistory, an object that has information about the historical future data
python
es = qb.AddFuture("ES")
es.SetFilter(timedelta(0), timedelta(180))
python
future_history = qb.GetFutureHistory(es.Symbol, datetime(2013, 10, 7))
print (future_history.GetExpiryDates())
h7 = future_history.GetAllData()

Get Fundamental Data

  • GetFundamental([symbol], selector, start_date = datetime(1998,1,1), end_date = datetime.now())

We will get a pandas.DataFrame with fundamental data.

python
data = qb.GetFundamental(["AAPL","AIG","BAC","GOOG","IBM"], "ValuationRatios.PERatio")
data

Indicators

We can easily get the indicator of a given symbol with QuantBook.

For all indicators, please checkout QuantConnect Indicators Reference Table

python
# 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()
python
# For EURUSD
bbdf = qb.Indicator(bb, "EURUSD", 360, Resolution.Daily)
bbdf = bbdf.drop('standarddeviation', 1)
bbdf.plot()
python
# Example with ADX, it is a bar indicator
adx = AverageDirectionalIndex("adx", 14)
adxdf = qb.Indicator(adx, "SPY", 360, Resolution.Daily)
adxdf.plot()
python
# For EURUSD
adxdf = qb.Indicator(adx, "EURUSD", 360, Resolution.Daily)
adxdf.plot()
python
# 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()
python
# 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()
python
# 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()
python
# 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()
python
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()