Skip to content

Commit

Permalink
Added tags to python algorithms
Browse files Browse the repository at this point in the history
  • Loading branch information
jaredbroad committed Sep 21, 2017
1 parent 98d77fa commit dc27c4e
Show file tree
Hide file tree
Showing 37 changed files with 590 additions and 429 deletions.
2 changes: 1 addition & 1 deletion Algorithm.CSharp/CustomChartingAlgorithm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
using System;
using QuantConnect.Data.Market;

namespace QuantConnect.Algorithm.Examples
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Algorithm demonstrating custom charting support in QuantConnect.
Expand Down
2 changes: 2 additions & 0 deletions Algorithm.CSharp/DataConsolidationAlgorithm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ namespace QuantConnect.Algorithm.CSharp
/// When a new 'consolidated' piece of data is produced by the IDataConsolidator, an event is fired
/// with the argument of the new data.
/// </summary>
/// <meta name="tag" content="using data" />
/// <meta name="tag" content="consolidating data" />
public class DataConsolidationAlgorithm : QCAlgorithm
{
private TradeBar _last;
Expand Down
17 changes: 10 additions & 7 deletions Algorithm.Python/CustomBenchmarkAlgorithm.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
Expand All @@ -20,19 +20,22 @@
from QuantConnect import *
from QuantConnect.Algorithm import *


### <summary>
### Shows how to set a custom benchmark for you algorithms
### </summary>
### <meta name="tag" content="using data" />
### <meta name="tag" content="benchmarks" />
class CustomBenchmarkAlgorithm(QCAlgorithm):
'''Basic template algorithm simply initializes the date range and cash'''

def Initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

self.SetStartDate(2013,10,07) #Set Start Date
self.SetEndDate(2013,10,11) #Set End Date
self.SetCash(100000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
self.AddEquity("SPY", Resolution.Second)

self.SetBenchmark("SPY");

def OnData(self, data):
Expand Down
25 changes: 17 additions & 8 deletions Algorithm.Python/CustomChartingAlgorithm.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
Expand All @@ -28,14 +28,23 @@
import decimal as d
from datetime import timedelta, datetime


### <summary>
### Algorithm demonstrating custom charting support in QuantConnect.
### The entire charting system of quantconnect is adaptable. You can adjust it to draw whatever you'd like.
### Charts can be stacked, or overlayed on each other. Series can be candles, lines or scatter plots.
### Even the default behaviours of QuantConnect can be overridden.
### </summary>
### <meta name="tag" content="charting" />
### <meta name="tag" content="adding charts" />
### <meta name="tag" content="series types" />
### <meta name="tag" content="plotting indicators" />
class CustomChartingAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2016,1,1)
self.SetEndDate(2017,1,1)
self.SetCash(100000)
self.AddEquity("SPY", Resolution.Daily)

# In your initialize method:
# Chart - Master Container for the Chart:
stockPlot = Chart("Trade Plot")
Expand All @@ -44,7 +53,7 @@ def Initialize(self):
stockPlot.AddSeries(Series("Sell", SeriesType.Scatter, 0))
stockPlot.AddSeries(Series("Price", SeriesType.Line, 0))
self.AddChart(stockPlot)

avgCross = Chart("Strategy Equity")
avgCross.AddSeries(Series("FastMA", SeriesType.Line, 1))
avgCross.AddSeries(Series("SlowMA", SeriesType.Line, 1))
Expand All @@ -54,7 +63,7 @@ def Initialize(self):
self.slowMA = 0
self.resample = datetime.min
self.resamplePeriod = (self.EndDate - self.StartDate) / 2000

def OnData(self, slice):
if slice["SPY"] is None:
self.lastPrice = 0
Expand All @@ -70,7 +79,7 @@ def OnData(self, slice):
self.resample = self.Time + self.resamplePeriod
self.Plot("Strategy Equity", "FastMA", self.fastMA);
self.Plot("Strategy Equity", "SlowMA", self.slowMA);

# On the 5th days when not invested buy:
if not self.Portfolio.Invested and self.Time.day % 13 == 0:
self.Order("SPY", (int)(self.Portfolio.MarginRemaining / self.lastPrice))
Expand Down
43 changes: 23 additions & 20 deletions Algorithm.Python/CustomDataBitcoinAlgorithm.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
Expand All @@ -27,12 +27,15 @@
import numpy as np
import json


### <summary>
### Demonstration of using an external custom datasource. LEAN Engine is incredibly flexible and allows you to define your own data source.
### This includes any data source which has a TIME and VALUE. These are the *only* requirements. To demonstrate this we're loading in "Bitcoin" data.
### </summary>
### <meta name="tag" content="using data" />
### <meta name="tag" content="custom data" />
### <meta name="tag" content="importing data" />
### <meta name="tag" content="crypto" />
class CustomDataBitcoinAlgorithm(QCAlgorithm):
'''3.0 CUSTOM DATA SOURCE: USE YOUR OWN MARKET DATA (OPTIONS, FOREX, FUTURES, DERIVATIVES etc).
The new QuantConnect Lean Backtesting Engine is incredibly flexible and allows you to define your own data source.
This includes any data source which has a TIME and VALUE. These are the *only* requirements.
To demonstrate this we're loading in "Bitcoin" data.'''

def Initialize(self):
self.SetStartDate(2011, 9, 13)
Expand All @@ -41,29 +44,29 @@ def Initialize(self):

# Define the symbol and "type" of our generic data:
self.AddData(Bitcoin, "BTC")


def OnData(self, data):
if "BTC" not in data: return

close = data["BTC"].Close

# If we don't have any weather "SHARES" -- invest"
if not self.Portfolio.Invested:
# Weather used as a tradable asset, like stocks, futures etc.
# Weather used as a tradable asset, like stocks, futures etc.
self.SetHoldings("BTC", 1)
self.Debug("Buying BTC 'Shares': BTC: {0}".format(close))

self.Debug("Time: {0} {1}".format(datetime.now(), close))


class Bitcoin(PythonData):
'''Custom Data Type: Bitcoin data from Quandl - http://www.quandl.com/help/api-for-bitcoin-data'''

def GetSource(self, config, date, isLiveMode):
if isLiveMode:
return SubscriptionDataSource("https://www.bitstamp.net/api/ticker/", SubscriptionTransportMedium.Rest);

#return "http://my-ftp-server.com/futures-data-" + date.ToString("Ymd") + ".zip";
# OR simply return a fixed small data file. Large files will slow down your backtest
return SubscriptionDataSource("http://www.quandl.com/api/v1/datasets/BCHARTS/BITSTAMPUSD.csv?sort_order=asc", SubscriptionTransportMedium.RemoteFile);
Expand All @@ -72,19 +75,19 @@ def GetSource(self, config, date, isLiveMode):
def Reader(self, config, line, date, isLiveMode):
coin = Bitcoin()
coin.Symbol = config.Symbol

if isLiveMode:
# Example Line Format:
# {"high": "441.00", "last": "421.86", "timestamp": "1411606877", "bid": "421.96", "vwap": "428.58", "volume": "14120.40683975", "low": "418.83", "ask": "421.99"}
try:
liveBTC = json.loads(line)

# If value is zero, return None
value = decimal.Decimal(liveBTC["last"])
if value == 0: return None

coin.Time = datetime.now()
coin.Value = value
coin.Value = value
coin["Open"] = float(liveBTC["open"])
coin["High"] = float(liveBTC["high"])
coin["Low"] = float(liveBTC["low"])
Expand All @@ -102,10 +105,10 @@ def Reader(self, config, line, date, isLiveMode):
# Date Open High Low Close Volume (BTC) Volume (Currency) Weighted Price
# 2011-09-13 5.8 6.0 5.65 5.97 58.37138238, 346.0973893944 5.929230648356
if not (line.strip() and line[0].isdigit()): return None

try:
data = line.split(',')

# If value is zero, return None
value = decimal.Decimal(data[4])
if value == 0: return None
Expand All @@ -120,7 +123,7 @@ def Reader(self, config, line, date, isLiveMode):
coin["VolumeUSD"] = float(data[6])
coin["WeightedPrice"] = float(data[7])
return coin;

except ValueError:
# Do nothing, possible error in json decoding
return None
39 changes: 21 additions & 18 deletions Algorithm.Python/CustomDataNIFTYAlgorithm.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
Expand All @@ -27,12 +27,15 @@
import math
import json

### <summary>
### This demonstration imports indian NSE index "NIFTY" as a tradable security in addition to the USDINR currency pair. We move into the
### NSE market when the economy is performing well.
### </summary>
### <meta name="tag" content="strategy examples" />
### <meta name="tag" content="using data" />
### <meta name="tag" content="importing data" />
### <meta name="tag" content="custom data" />
class CustomDataNIFTYAlgorithm(QCAlgorithm):
'''3.0 CUSTOM DATA SOURCE: USE YOUR OWN MARKET DATA (OPTIONS, FOREX, FUTURES, DERIVATIVES etc).
The new QuantConnect Lean Backtesting Engine is incredibly flexible and allows you to define your own data source.
This includes any data source which has a TIME and VALUE. These are the *only* requirements.
To demonstrate this we're loading in "Nifty" data. This by itself isn't special, the cool part is next:
We load the "Nifty" data as a tradable security we're calling "NIFTY".'''

def Initialize(self):
self.SetStartDate(2008, 1, 8)
Expand All @@ -42,11 +45,11 @@ def Initialize(self):
# Define the symbol and "type" of our generic data:
self.AddData(DollarRupee, "USDINR")
self.AddData(Nifty, "NIFTY")

self.minimumCorrelationHistory = 50
self.today = CorrelationPair()
self.prices = []


def OnData(self, data):
if "USDINR" in data:
Expand All @@ -61,7 +64,7 @@ def OnData(self, data):
self.prices.append(self.today)
if len(self.prices) > self.minimumCorrelationHistory:
self.prices.pop(0)

# Strategy
if self.Time.weekday() != 2: return

Expand All @@ -82,28 +85,28 @@ class Nifty(PythonData):
'''NIFTY Custom Data Class'''
def GetSource(self, config, date, isLiveMode):
return SubscriptionDataSource("https://www.dropbox.com/s/rsmg44jr6wexn2h/CNXNIFTY.csv?dl=1", SubscriptionTransportMedium.RemoteFile);


def Reader(self, config, line, date, isLiveMode):
if not (line.strip() and line[0].isdigit()): return None

# New Nifty object
index = Nifty();
index.Symbol = config.Symbol

try:
# Example File Format:
# Date, Open High Low Close Volume Turnover
# 2011-09-13 7792.9 7799.9 7722.65 7748.7 116534670 6107.78
data = line.split(',')
index.Time = datetime.strptime(data[0], "%Y-%m-%d")
index.Time = datetime.strptime(data[0], "%Y-%m-%d")
index.Value = decimal.Decimal(data[4])
index["Open"] = float(data[1])
index["High"] = float(data[2])
index["Low"] = float(data[3])
index["Close"] = float(data[4])


except ValueError:
# Do nothing
return None
Expand All @@ -122,13 +125,13 @@ def Reader(self, config, line, date, isLiveMode):
# New USDINR object
currency = DollarRupee();
currency.Symbol = config.Symbol

try:
data = line.split(',')
currency.Time = datetime.strptime(data[0], "%Y-%m-%d")
currency.Value = decimal.Decimal(data[1])
currency["Close"] = float(data[1])

except ValueError:
# Do nothing
return None
Expand Down
21 changes: 14 additions & 7 deletions Algorithm.Python/CustomDataRegressionAlgorithm.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
Expand All @@ -24,17 +24,24 @@
from QuantConnect.Data.UniverseSelection import *
from datetime import datetime


### <summary>
### Regression test to demonstrate importing and trading on custom data.
### </summary>
### <meta name="tag" content="using data" />
### <meta name="tag" content="importing data" />
### <meta name="tag" content="custom data" />
### <meta name="tag" content="crypto" />
### <meta name="tag" content="regression test" />
class CustomDataRegressionAlgorithm(QCAlgorithm):

''' Regression algorithm for custom data '''

def Initialize(self):

self.SetStartDate(2014,04,01) #Set Start Date
self.SetEndDate(2015,04,30) #Set End Date
self.SetCash(50000) #Set Strategy Cash

self.AddData[Bitcoin]("BTC", Resolution.Daily)

def OnData(self, data):
Expand Down
Loading

0 comments on commit dc27c4e

Please sign in to comment.