def test_is_same_time(self): candle1 = Candle.from_string("01042017;100001;200;200;200;200;123") candle2 = Candle.from_string("01042017;100001;100;100;100;100;123") self.assertTrue(candle1.is_same_time(candle2), "equal dates") candle2 = Candle.from_string("01042017;100002;100;100;100;100;123") self.assertFalse(candle1.is_same_time(candle2), "not equal dates")
def test_should_calculate_earnings(self): self.executor.account_balance = 1000 self.executor.consume(Market("BUY", 1000)) self.executor.consume(Tick(Candle(1, 1, 1, 1), 'H')) self.executor.consume(Market("SELL", 1000)) self.executor.consume(Tick(Candle(2, 2, 2, 2), 'H')) self.assertEqual(self.executor.account_balance, 2000)
def test_make_spread(self): candle2 = Candle.from_string("01042017;100001;100;100;100;100;123") candle1 = Candle.from_string("01042017;100001;200;200;200;200;123") spread = Candle.make_spread(candle1, 1, candle2, 1) self.assertEqual(spread.close, 100, "subtraction without coefficients") spread = Candle.make_spread(candle1, 1.5, candle2, 0.8) self.assertEqual(spread.close, 220, "subtraction with coefficients")
def test_is_older(self): candle1 = Candle.from_string("01042017;100001;200;200;200;200;123") candle2 = Candle.from_string("01042017;120001;100;100;100;100;123") self.assertTrue(candle1.is_older(candle2), "older, 2 hours") candle2 = Candle.from_string("30042017;100001;100;100;100;100;123") self.assertTrue(candle1.is_older(candle2), "older, 29 days") candle2 = Candle.from_string("30032017;100001;100;100;100;100;123") self.assertFalse(candle1.is_older(candle2), "younger")
def test_convert_str_to_time(self): time = datetime.time(0, 0, 0) self.assertEqual(datetime.time(10, 15, 55), Candle.convert_str_to_time("101555"), "normal time") self.assertEqual(time, Candle.convert_str_to_time("101566"), "wrong time") self.assertEqual(time, Candle.convert_str_to_time("1015666"), "too long time") self.assertEqual(time, Candle.convert_str_to_time("1015"), "too short time") self.assertEqual(time, Candle.convert_str_to_time("AABBCC"), "letters time")
def test_from_string(self): candle = Candle.from_string("01042017;100001;150;151.5;149;121;79844") self.assertEqual(candle.filled, True, "normal string") self.assertEqual(candle.close, 121) candle = Candle.from_string("010420171;100001;150;151.5;149;121;79844") self.assertEqual(candle.filled, False, "invalid date") candle = Candle.from_string("01042017;100001;150;151.5;abc;121;79844") self.assertEqual(candle.filled, False, "invalid float value") candle = Candle.from_string( "01042017;100001;150;151.5;149;121;79844;45") self.assertEqual(candle.filled, False, "too much data") candle = Candle.from_string("01042017;150;151.5;149;121;79844") self.assertEqual(candle.filled, False, "no time")
def test_should_exit(self): self.executor.consume(Market("BUY", 1000)) self.executor.consume(Tick(Candle(1, 1, 1, 1), 'H')) self.assertTrue(self.executor.in_market()) self.executor.consume(Market("SELL", 1000)) self.executor.consume(Tick(Candle(1, 1, 1, 1), 'H')) self.assertFalse(self.executor.in_market()) # Now test the opposite self.executor.consume(Market("SELL", 1000)) self.executor.consume(Tick(Candle(1, 1, 1, 1), 'H')) self.assertTrue(self.executor.in_market()) self.executor.consume(Market("BUY", 1000)) self.executor.consume(Tick(Candle(1, 1, 1, 1), 'H')) self.assertFalse(self.executor.in_market())
def test_to_string(self): candle = Candle.from_string( "01042017;100001;150.12345;151.54321;149.123456;151.9874651;79844") self.assertEqual( candle.to_string(), "01042017;100001;150.1234;151.5432;149.1235;151.9875;79844", "string conversion's format")
def next_candles(self, command): candles = command.split(';') for strCandle in candles: candle = strCandle.split(',') if (candle[0] == "BTC_ETH"): self.btc_eth_candles.append(Candle(candle)) if (len(self.btc_eth_candles) > candle_memory + 1): self.btc_eth_candles.pop(0) elif (candle[0] == "USDT_BTC"): self.usdt_btc_candles.append(Candle(candle)) if (len(self.usdt_btc_candles) > candle_memory + 1): self.usdt_btc_candles.pop(0) elif (candle[0] == "USDT_ETH"): self.usdt_eth_candles.append(Candle(candle)) if (len(self.usdt_eth_candles) > candle_memory + 1): self.usdt_eth_candles.pop(0)
def getCandlesToSMA(): try: data = json.load( urllib2.urlopen( 'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=NFLX&interval=1min&apikey=4NAVVQWAXRE1SGGY' )) dataList = data['Time Series (1min)'] closeAdding = 0.0 now = datetime.datetime.now() now += datetime.timedelta(hours=1) j = 3 global candleList candleList = [] for x in range(20): candle = Candle( float( dataList[str(now - datetime.timedelta(minutes=j - 1))[:16] + ":00"]['1. open']), float( dataList[str(now - datetime.timedelta(minutes=j - 2))[:16] + ":00"]['4. close']), str(now - datetime.timedelta(minutes=j - 2))[:16] + ":00") candleList.append(candle) print("o " + str(candle.c_open) + "c " + str(candle.c_close) + " - " + candle.c_id) j += 2 candleList.pop(0) except KeyError: print("Unreturned SMA key") time.sleep(10) getCandlesToSMA() except socket.error: time.sleep(10) getCandlesToSMA() except IndexError: time.sleep(10) getCandlesToSMA() except urllib2.HTTPError: time.sleep(10) getCandlesToSMA() candleList = candleList[::-1] return candleList
def baseline_daily_returns(): """daily returns of stock on avg, like if i were to just hold it""" days = 5 # easier to just harcode it here df = pd.read_csv('amd.csv', index_col='timestamp', parse_dates=True) candles = Candle.dayCandlesFromDataframe(df) percent_gain = (candles[-1].close - candles[0].open) / candles[0].open - 1 dr = percent_gain**( 1.0 / days) if percent_gain > 0 else -1 * (percent_gain * -1)**(1.0 / days) print "Daily Returns of this STOCK:\n", dr, "%"
def test_from_candle(self): source = Candle() source.date = "30092017" source.time = "154523" source.init_datetime() candle = Candle.from_candle(source) self.assertTrue(candle.filled, "candle not filled") self.assertTrue(candle.is_same_time(source), "date&time copying")
def baseline_swing_daily_returns(): """daily returns of market on avg, like if i were to just hold it""" days = 252 df = pd.read_csv('^GSPC.csv', index_col='Date', parse_dates=True).tail(days) candles = Candle.swingCandlesFromDataframe(df) percent_gain = (candles[-1].close - candles[0].open) / candles[0].open - 1 print candles[-1].close print candles[-0].open print percent_gain dr = percent_gain**( 1.0 / days) if percent_gain > 0 else -1 * (percent_gain * -1)**(1.0 / days) print "Swing Baseline Daily Returns:\n", dr, "%"
def handleData(self, data): if (time.time() - self.start < TIMEFRAME): if (data.startswith("TYPE=PRICE")): print("New Data") bidPrice, askPrice = self.getPrices(data) self.bidPrices.append(bidPrice) self.askPrices.append(askPrice) else: if len(self.bidPrices) > 0: self.bidCandles.append( Candle(self.bidPrices[0], self.bidPrices[-1], min(self.bidPrices), max(self.bidPrices))) if len(self.askPrices) > 0: self.askCandles.append( Candle(self.askPrices[0], self.askPrices[-1], min(self.askPrices), max(self.askPrices))) self.midpoint = sum(self.askPrices) / len(self.askPrices) #Setup for next Candle self.start = time.time() self.bidPrices.clear() self.askPrices.clear()
def last_remaining(self): """ returns [Candle] of the last year (if excluding_last = 252 days) """ df = pd.read_csv('^GSPC.csv', index_col='Date', parse_dates=True) df = df[-1 * self.excluding_last:] # for example, past 252 days # for 2017 # years_to_chop_off = 10 # 1: chop off 2018 to get just 2017 # df = df[:-252*years_to_chop_off] # print "self.excluding_last", self.excluding_last return Candle.swingCandlesFromDataframe(df)
def test_convert_str_to_date(self): empty = datetime.date(2001, 1, 1) self.assertEqual(datetime.date(2017, 10, 30), Candle.convert_str_to_date("30102017"), "normal date") self.assertEqual(empty, Candle.convert_str_to_date("efaffef"), "letters in input") self.assertEqual(empty, Candle.convert_str_to_date("20171030"), "reverse format") self.assertEqual(empty, Candle.convert_str_to_date("20170230"), "invalid date") self.assertEqual(empty, Candle.convert_str_to_date("201723"), "too short date") self.assertEqual(empty, Candle.convert_str_to_date("20170230"), "too long date")
df = pd.read_csv( 'https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv' ) closing_average = df['AAPL.Close'].mean() print(closing_average) candle_list = [] for index, row in df.iterrows(): candle_index = index candle_close = row['AAPL.Close'] candle_open = row['AAPL.Open'] candle_high = row['AAPL.High'] candle_low = row['AAPL.Low'] candle = Candle(open=candle_open, high=candle_high, low=candle_low, close=candle_close, order=index, average=closing_average) candle_list.append(candle) def get_doji_count(candle_collection): doji_count = 0 for i in candle_collection: if i.is_doji: doji_count += 1 return doji_count def print_red_doji_green_count(candle_collection):
from Candle import Candle import time import RPi.GPIO as GPIO sleep_ms = lambda ms: time.sleep(ms / 1000.0) candle = Candle() candle.create(24) candle.shuffle(0, 1000) for times in range(2000): candle.refresh() sleep_ms(10) GPIO.cleanup()
importer = CSVDataImporter('/Users/jared/Dev/Tim/data/EUR_USD.csv') turtle = Turtle(ShortBreakout(length=20, exit_length=6), LongBreakout(length=30, exit_length=10)) candles = [] last_price = None last_day = None for index, row in importer.data.iterrows(): date = datetime.strptime(index, "%Y-%m-%dT%H:%M:%S") if last_day is None: last_day = date.day if last_day != date.day: turtle.tick_day(Tick(Candle.from_list(candles), 'D')) candles = [] last_day = date.day candles.append( Candle(row['open'], row['high'], row['low'], row['close'])) turtle.tick_hour(Tick(candles[-1], 'H')) # print(date.day, row['close']) if turtle.in_market: turtle.exit(candles[-1].close) turtle.print_pnl()
def ejecuteScript(): now = datetime.datetime.now() one_minute = datetime.timedelta(minutes=1) two_minute = datetime.timedelta(minutes=2) one_hour = datetime.timedelta(hours=1) now_minus_one = now - one_minute now_minus_two = now - two_minute now_minus_one += one_hour now_minus_two += one_hour now_minus_one_str = str(now_minus_one)[:16] + ":00" now_minus_two_str = str(now_minus_two)[:16] + ":00" try: data = json.load( urllib2.urlopen( 'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=NFLX&interval=1min&apikey=4NAVVQWAXRE1SGGY' )) timeSeries1min = data['Time Series (1min)'] ticker = data['Meta Data']['2. Symbol'] print("-----") candle = Candle(float(timeSeries1min[now_minus_two_str]['1. open']), float(timeSeries1min[now_minus_one_str]['4. close']), now_minus_one_str) global candleList candleList.append(candle) print("o " + str(candle.c_open) + "c " + str(candle.c_close) + " - " + candle.c_id) print(candle.getColor()) sma = 0.0 lastCandlesColor = "" if len(candleList) > 19: sma = float(getSMAV2(candleList)) lastCandlesColor = getLastCandlesColor(candleList) candleList.pop(0) if candle.getColor( ) == "R" and candle.c_open > sma and candle.c_close < sma and lastCandlesColor == "R": print("***************************************** RED RED RED") sendEmail(ticker) toaster = ToastNotifier() toaster.show_toast("MALANGA Alert ! " + ticker) elif candle.getColor( ) == "G" and candle.c_open < sma and candle.c_close > sma and lastCandlesColor == "G": print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ GREEN GREEN GREEN") sendEmail(ticker) toaster = ToastNotifier() toaster.show_toast("MALANGA Alert ! " + ticker) print("-----") except KeyError: print("Unreturned key") time.sleep(10) candleList = getCandlesToSMA() ejecuteScript() except socket.error: time.sleep(10) candleList = getCandlesToSMA() ejecuteScript() except urllib2.HTTPError: time.sleep(10) candleList = getCandlesToSMA() ejecuteScript() except urllib2.URLError: time.sleep(10) candleList = getCandlesToSMA() ejecuteScript()
def mock(): data = json.load( urllib2.urlopen( 'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=QCOM&interval=1min&apikey=E5KJEEWP24PU8BH7&outputsize=full' )) timeSeries1min = data['Time Series (1min)'] ticker = data['Meta Data']['2. Symbol'] j = 52 y = 9 ch = "09" candleList = [] for x in range(185): curr = str(j) curr1 = str(j - 1) if j <= 9: curr = "0" + str(j) curr1 = "0" + curr1 elif j == 60: curr = "00" curr1 = "59" j = 0 if curr1 == "9": curr1 = "09" now_minus_two_str = "2019-05-21 " + ch + ":" + curr1 + ":00" if j == 0: y = y + 1 ch = str(y) now_minus_one_str = "2019-05-21 " + ch + ":" + curr + ":00" print(now_minus_one_str) print(now_minus_two_str) #getSMA(20, timeSeries1min) try: print("-----") candle = Candle( float(timeSeries1min[now_minus_two_str]['1. open']), float(timeSeries1min[now_minus_one_str]['4. close'])) candleList.append(candle) print("o " + str(candle.c_open)) print("c " + str(candle.c_close)) print(candle.getColor()) sma = 0.0 lastCandlesColor = "" if len(candleList) > 19: sma = float(getSMAV2(candleList)) lastCandlesColor = getLastCandlesColor(candleList) candleList.pop(0) if candle.getColor( ) == "R" and candle.c_open > sma and candle.c_close < sma and lastCandlesColor == "R": print("***************************************** RED RED RED") sendEmail(ticker) toaster = ToastNotifier() toaster.show_toast("MALANGA Alert ! " + ticker) elif candle.getColor( ) == "G" and candle.c_open < sma and candle.c_close > sma and lastCandlesColor == "G": print( "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ GREEN GREEN GREEN" ) sendEmail(ticker) toaster = ToastNotifier() toaster.show_toast("MALANGA Alert ! " + ticker) print("-----") except KeyError: print("Unreturned key") #time.sleep(2) j += 2
def test_should_enter(self): self.assertFalse(self.executor.in_market()) self.executor.consume(Market("BUY", 1000)) self.executor.consume(Tick(Candle(1, 1, 1, 1), 'H')) self.assertTrue(self.executor.in_market())