Skip to content

Commit

Permalink
Changed Quanld source to correctly retrieve csv data, along with simp…
Browse files Browse the repository at this point in the history
…le cleanup of import statements and use of Decimal
  • Loading branch information
simonsonjack committed Mar 4, 2019
1 parent cf1b6c3 commit 0d963cc
Show file tree
Hide file tree
Showing 12 changed files with 30 additions and 42 deletions.
5 changes: 2 additions & 3 deletions Algorithm.Python/CustomModelsAlgorithm.py
Expand Up @@ -24,7 +24,6 @@
from QuantConnect.Securities import *
from QuantConnect.Orders.Fills import *
import numpy as np
import decimal as d
import random

### <summary>
Expand Down Expand Up @@ -102,7 +101,7 @@ def GetOrderFee(self, parameters):
# custom fee math
fee = max(1, parameters.Security.Price
* parameters.Order.AbsoluteQuantity
* d.Decimal(0.00001))
* 0.00001)
self.algorithm.Log("CustomFeeModel: " + str(fee))
return OrderFee(CashAmount(fee, "USD"))

Expand All @@ -112,6 +111,6 @@ def __init__(self, algorithm):

def GetSlippageApproximation(self, asset, order):
# custom slippage math
slippage = asset.Price * d.Decimal(0.0001 * np.log10(2*float(order.AbsoluteQuantity)))
slippage = asset.Price * 0.0001 * np.log10(2*float(order.AbsoluteQuantity))
self.algorithm.Log("CustomSlippageModel: " + str(slippage))
return slippage
4 changes: 1 addition & 3 deletions Algorithm.Python/ETFGlobalRotationAlgorithm.py
Expand Up @@ -23,9 +23,7 @@
from QuantConnect.Algorithm import *
from QuantConnect.Indicators import *
from System.Collections.Generic import List
import decimal as d
from datetime import datetime, timedelta
from decimal import Decimal

### <summary>
### Strategy example using a portfolio of ETF Global Rotation
Expand Down Expand Up @@ -89,7 +87,7 @@ def OnData(self, data):
if (self.Portfolio[bestGrowth[0]].Quantity == 0):
self.Log("PREBUY>>LIQUIDATE>>")
self.Liquidate()
self.Log(">>BUY>>" + str(bestGrowth[0]) + "@" + str(Decimal(100) * bestGrowth[1].Current.Value))
self.Log(">>BUY>>" + str(bestGrowth[0]) + "@" + str(100 * bestGrowth[1].Current.Value))
qty = self.Portfolio.MarginRemaining / self.Securities[bestGrowth[0]].Close
self.MarketOrder(bestGrowth[0], int(qty))
else:
Expand Down
1 change: 0 additions & 1 deletion Algorithm.Python/FractionalQuantityRegressionAlgorithm.py
Expand Up @@ -27,7 +27,6 @@
from QuantConnect.Data.Market import *
from QuantConnect.Data.Consolidators import *

import decimal as d
from datetime import timedelta
from math import floor

Expand Down
3 changes: 1 addition & 2 deletions Algorithm.Python/FuturesMomentumAlgorithm.py
Expand Up @@ -21,7 +21,6 @@
from QuantConnect.Algorithm import *
from QuantConnect.Securities import *
from datetime import timedelta
import decimal as d
import numpy as np

### <summary>
Expand All @@ -43,7 +42,7 @@ def Initialize(self):
self.SetCash(100000)
fastPeriod = 20
slowPeriod = 60
self._tolerance = d.Decimal(1 + 0.001)
self._tolerance = 1 + 0.001
self.IsUpTrend = False
self.IsDownTrend = False
self.SetWarmUp(max(fastPeriod, slowPeriod))
Expand Down
9 changes: 4 additions & 5 deletions Algorithm.Python/IndicatorWarmupAlgorithm.py
Expand Up @@ -25,7 +25,6 @@
from QuantConnect.Indicators import *
from QuantConnect.Orders import *
from QuantConnect.Securities import *
import decimal as d

### <summary>
### Regression test for history and warm up using the data available in open source.
Expand Down Expand Up @@ -111,7 +110,7 @@ def __init__(self, symbol, algorithm):
def Update(self):
self.IsReady = self.Close.IsReady and self.ADX.IsReady and self.EMA.IsReady and self.MACD.IsReady

tolerance = d.Decimal(1 - self.PercentTolerance)
tolerance = 1 - self.PercentTolerance
self.IsUptrend = self.MACD.Signal.Current.Value > self.MACD.Current.Value * tolerance and\
self.EMA.Current.Value > self.Close.Current.Value * tolerance

Expand Down Expand Up @@ -147,7 +146,7 @@ def TryExit(self):

limit = 0
qty = self.Security.Holdings.Quantity
exitTolerance = d.Decimal(1 + 2 * self.PercentTolerance)
exitTolerance = 1 + 2 * self.PercentTolerance
if self.Security.Holdings.IsLong and self.Close.Current.Value * exitTolerance < self.EMA.Current.Value:
limit = self.Security.High
elif self.Security.Holdings.IsShort and self.Close.Current.Value > self.EMA.Current.Value * exitTolerance:
Expand All @@ -164,8 +163,8 @@ def OnOrderEvent(self, fill):

# if we just finished entering, place a stop loss as well
if self.Security.Invested:
stop = fill.FillPrice*d.Decimal(1 - self.PercentGlobalStopLoss) if self.Security.Holdings.IsLong \
else fill.FillPrice*d.Decimal(1 + self.PercentGlobalStopLoss)
stop = fill.FillPrice*(1 - self.PercentGlobalStopLoss) if self.Security.Holdings.IsLong \
else fill.FillPrice*(1 + self.PercentGlobalStopLoss)

self.__currentStopLoss = self.__algorithm.StopMarketOrder(self.Symbol, -qty, stop, "StopLoss at: {0}".format(stop))

Expand Down
3 changes: 1 addition & 2 deletions Algorithm.Python/LiveFeaturesAlgorithm.py
Expand Up @@ -27,7 +27,6 @@

import numpy as np
from datetime import datetime
import decimal
import json


Expand Down Expand Up @@ -103,7 +102,7 @@ def Reader(self, config, line, date, isLiveMode):
liveBTC = json.loads(line)

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

coin.Time = datetime.now()
Expand Down
5 changes: 2 additions & 3 deletions Algorithm.Python/MarginCallEventsAlgorithm.py
Expand Up @@ -21,7 +21,6 @@
from QuantConnect.Orders import *
from QuantConnect.Algorithm import QCAlgorithm
import numpy as np
import decimal as d
from datetime import datetime, timedelta

### <summary>
Expand Down Expand Up @@ -61,7 +60,7 @@ def OnMarginCall(self, requests):
for order in requests:

# liquidate an extra 10% each time we get a margin call to give us more padding
newQuantity = int(np.sign(order.Quantity) * order.Quantity * d.Decimal(1.1))
newQuantity = int(np.sign(order.Quantity) * order.Quantity * 1.1)
requests.remove(order)
requests.append(SubmitOrderRequest(order.OrderType, order.SecurityType, order.Symbol, newQuantity, order.StopPrice, order.LimitPrice, self.Time, "OnMarginCall"))

Expand All @@ -74,6 +73,6 @@ def OnMarginCallWarning(self):
# a chance to prevent a margin call from occurring

spyHoldings = self.Securities["SPY"].Holdings.Quantity
shares = int(-spyHoldings * d.Decimal(0.005))
shares = int(-spyHoldings * 0.005)
self.Error("{0} - OnMarginCallWarning(): Liquidating {1} shares of SPY to avoid margin call.".format(self.Time, shares))
self.MarketOrder("SPY", shares)
3 changes: 1 addition & 2 deletions Algorithm.Python/MovingAverageCrossAlgorithm.py
Expand Up @@ -21,7 +21,6 @@
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Indicators import *
import decimal as d

### <summary>
### In this example we look at the canonical 15/30 day moving average cross. This algorithm
Expand Down Expand Up @@ -75,7 +74,7 @@ def OnData(self, data):
# we only want to go long if we're currently short or flat
if holdings <= 0:
# if the fast is greater than the slow, we'll go long
if self.fast.Current.Value > self.slow.Current.Value * d.Decimal(1 + tolerance):
if self.fast.Current.Value > self.slow.Current.Value *(1 + tolerance):
self.Log("BUY >> {0}".format(self.Securities["SPY"].Price))
self.SetHoldings("SPY", 1.0)

Expand Down
29 changes: 14 additions & 15 deletions Algorithm.Python/OrderTicketDemoAlgorithm.py
Expand Up @@ -21,7 +21,6 @@
from QuantConnect.Algorithm import *
from QuantConnect.Orders import *
from QuantConnect.Data import *
import decimal as d

### <summary>
### In this algorithm we submit/update/cancel each order type
Expand Down Expand Up @@ -113,11 +112,11 @@ def LimitOrders(self):

# submit a limit order to buy 10 shares at .1% below the bar's close
close = self.Securities[self.spy.Value].Close
newTicket = self.LimitOrder(self.spy, 10, close * d.Decimal(.999))
newTicket = self.LimitOrder(self.spy, 10, close * .999)
self.__openLimitOrders.append(newTicket)

# submit another limit order to sell 10 shares at .1% above the bar's close
newTicket = self.LimitOrder(self.spy, -10, close * d.Decimal(1.001))
newTicket = self.LimitOrder(self.spy, -10, close * 1.001)
self.__openLimitOrders.append(newTicket)

# when we submitted new limit orders we placed them into this list,
Expand All @@ -133,8 +132,8 @@ def LimitOrders(self):
return

# if niether order has filled, bring in the limits by a penny
newLongLimit = longOrder.Get(OrderField.LimitPrice) + d.Decimal(0.01)
newShortLimit = shortOrder.Get(OrderField.LimitPrice) - d.Decimal(0.01)
newLongLimit = longOrder.Get(OrderField.LimitPrice) + 0.01
newShortLimit = shortOrder.Get(OrderField.LimitPrice) - 0.01
self.Log("Updating limits - Long: {0:.2f} Short: {1:.2f}".format(newLongLimit, newShortLimit))

updateOrderFields = UpdateOrderFields()
Expand Down Expand Up @@ -165,12 +164,12 @@ def StopMarketOrders(self):
# a long stop is triggered when the price rises above the value
# so we'll set a long stop .25% above the current bar's close
close = self.Securities[self.spy.Value].Close
newTicket = self.StopMarketOrder(self.spy, 10, close * d.Decimal(1.0025))
newTicket = self.StopMarketOrder(self.spy, 10, close * 1.0025)
self.__openStopMarketOrders.append(newTicket)

# a short stop is triggered when the price falls below the value
# so we'll set a short stop .25% below the current bar's close
newTicket = self.StopMarketOrder(self.spy, -10, close * d.Decimal(.9975))
newTicket = self.StopMarketOrder(self.spy, -10, close * .9975)
self.__openStopMarketOrders.append(newTicket)

# when we submitted new stop market orders we placed them into this list,
Expand All @@ -184,8 +183,8 @@ def StopMarketOrders(self):
return

# if neither order has filled, bring in the stops by a penny
newLongStop = longOrder.Get(OrderField.StopPrice) - d.Decimal(0.01)
newShortStop = shortOrder.Get(OrderField.StopPrice) + d.Decimal(0.01)
newLongStop = longOrder.Get(OrderField.StopPrice) - 0.01
newShortStop = shortOrder.Get(OrderField.StopPrice) + 0.01
self.Log("Updating stops - Long: {0:.2f} Short: {1:.2f}".format(newLongStop, newShortStop))

updateOrderFields = UpdateOrderFields()
Expand Down Expand Up @@ -224,7 +223,7 @@ def StopLimitOrders(self):
# so make the limit price a little higher than the stop price

close = self.Securities[self.spy.Value].Close
newTicket = self.StopLimitOrder(self.spy, 10, close * d.Decimal(1.001), close * d.Decimal(1.0025))
newTicket = self.StopLimitOrder(self.spy, 10, close * 1.001, close * 1.0025)
self.__openStopLimitOrders.append(newTicket)

# a short stop is triggered when the price falls below the
Expand All @@ -233,7 +232,7 @@ def StopLimitOrders(self):
# gauranteed to get at least the limit price for our fills,
# so make the limit price a little softer than the stop price

newTicket = self.StopLimitOrder(self.spy, -10, close * d.Decimal(.999), close * d.Decimal(0.9975))
newTicket = self.StopLimitOrder(self.spy, -10, close * .999, close * 0.9975)
self.__openStopLimitOrders.append(newTicket)

# when we submitted new stop limit orders we placed them into this list,
Expand All @@ -247,10 +246,10 @@ def StopLimitOrders(self):

# if neither order has filled, bring in the stops/limits in by a penny

newLongStop = longOrder.Get(OrderField.StopPrice) - d.Decimal(0.01)
newLongLimit = longOrder.Get(OrderField.LimitPrice) + d.Decimal(0.01)
newShortStop = shortOrder.Get(OrderField.StopPrice) + d.Decimal(0.01)
newShortLimit = shortOrder.Get(OrderField.LimitPrice) - d.Decimal(0.01)
newLongStop = longOrder.Get(OrderField.StopPrice) - 0.01
newLongLimit = longOrder.Get(OrderField.LimitPrice) + 0.01
newShortStop = shortOrder.Get(OrderField.StopPrice) + 0.01
newShortLimit = shortOrder.Get(OrderField.LimitPrice) - 0.01
self.Log("Updating stops - Long: {0:.2f} Short: {1:.2f}".format(newLongStop, newShortStop))
self.Log("Updating limits - Long: {0:.2f} Short: {1:.2f}".format(newLongLimit, newShortLimit))

Expand Down
5 changes: 2 additions & 3 deletions Algorithm.Python/ParameterizedAlgorithm.py
Expand Up @@ -22,7 +22,6 @@
from QuantConnect.Algorithm import *
from QuantConnect.Indicators import *
from QuantConnect.Parameters import *
import decimal as d

### <summary>
### Demonstration of the parameter system of QuantConnect. Using parameters you can pass the values required into C# algorithms for optimization.
Expand Down Expand Up @@ -62,7 +61,7 @@ def OnData(self, data):
fast = self.fast.Current.Value
slow = self.slow.Current.Value

if fast > slow * d.Decimal(1.001):
if fast > slow * 1.001:
self.SetHoldings("SPY", 1)
elif fast < slow * d.Decimal(0.999):
elif fast < slow * 0.999:
self.Liquidate("SPY")
3 changes: 1 addition & 2 deletions Algorithm.Python/QCUWeatherBasedRebalancing.py
Expand Up @@ -22,7 +22,6 @@
from QuantConnect.Data import SubscriptionDataSource
from QuantConnect.Python import PythonData
from datetime import datetime, timedelta
import decimal

### <summary>
### Using weather in NYC to rebalance portfolio. Assumption is people are happier when its warm.
Expand Down Expand Up @@ -86,7 +85,7 @@ def Reader(self, config, line, date, isLive):
weather.Time = datetime.strptime(data[0], '%Y-%m-%d') + timedelta(hours=20) # Make sure we only get this data AFTER trading day - don't want forward bias.
# If the second column is an invalid value (empty string), return None. The algorithm will discard it.
if not data[2]: return None
weather.Value = decimal.Decimal(data[2])
weather.Value = data[2]
weather["Max.C"] = float(data[1]) # Using a dot in the propety name, it will capitalize the first letter of each word:
weather["Min.C"] = float(data[3]) # Max.C -> MaxC and Min.C -> MinC

Expand Down
2 changes: 1 addition & 1 deletion Common/Data/Custom/Quandl.cs
Expand Up @@ -137,7 +137,7 @@ public override BaseData Reader(SubscriptionDataConfig config, string line, Date
/// <returns>STRING API Url for Quandl.</returns>
public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode)
{
var source = @"https://www.quantconnect.com/api/v2/proxy/quandl/api/v3/datasets/"
var source = @"https://www.quantconnect.com/api/v3/proxy/quandl/api/v3/datasets/"
+ config.Symbol.Value + ".csv?order=asc&api_key=" + _authCode;
return new SubscriptionDataSource(source, SubscriptionTransportMedium.RemoteFile);
}
Expand Down

0 comments on commit 0d963cc

Please sign in to comment.