def setUpClass(self): Logger.pushLogData("unitTesting", __name__) forceWorkingDirectory() pyswing.globals.potentialRuleMatches = None pyswing.globals.equityCount = None pyswing.database.overrideDatabase("output/TestMarketRule.db") pyswing.constants.pySwingStartDate = datetime.datetime(2014, 1, 1) deleteFile(pyswing.database.pySwingDatabase) args = "-n %s" % ("unitTesting") createDatabase(args.split()) pretendDate = datetime.datetime(2015, 9, 1) with patch.object(Equity, '_getTodaysDate', return_value=pretendDate) as mock_method: self._equity = Equity("WOR.AX") self._equity.importData() indicatorADI = IndicatorADI() indicatorADI.updateIndicator() self.rule = MarketRule("Indicator_ADI", "ADI > 0") self.rule.evaluateRule()
class TestSimpleRule(unittest.TestCase): @classmethod def setUpClass(self): Logger.pushLogData("unitTesting", __name__) forceWorkingDirectory() pyswing.globals.potentialRuleMatches = None pyswing.globals.equityCount = None pyswing.database.overrideDatabase("output/TestSimpleRule.db") pyswing.constants.pySwingStartDate = datetime.datetime(2014, 1, 1) deleteFile(pyswing.database.pySwingDatabase) args = "-n %s" % ("unitTesting") createDatabase(args.split()) pretendDate = datetime.datetime(2015, 9, 1) with patch.object(Equity, '_getTodaysDate', return_value=pretendDate) as mock_method: self._equityCBA = Equity("WOR.AX") self._equityCBA.importData() indicatorROC = IndicatorROC(self._equityCBA.dataFrame(), "WOR.AX") indicatorROC.updateIndicator() self.rule = SimpleRule("Indicator_ROC", "ROC_5 > 10") self.rule.evaluateRule("WOR.AX") @classmethod def tearDownClass(self): deleteFile(pyswing.database.pySwingDatabase) def test_IndicatorSMA(self): dataPointMatch = self.rule._ruleData.ix['2015-04-27 00:00:00'] self.assertEqual(dataPointMatch['Match'], 1) dataPointNoMatch = self.rule._ruleData.ix['2015-04-28 00:00:00'] self.assertEqual(dataPointNoMatch['Match'], 0) def test_getEquityCount(self): equityCount = self.rule._getEquityCount() self.assertEqual(equityCount, 1) potentialRuleMatches = self.rule._getPotentialRuleMatches() self.assertEqual(potentialRuleMatches, 434) def test_analyseRule(self): self.rule.analyseRule() self.assertAlmostEqual(self.rule._matchesPerDay, 0.032, 3)
def importData(argv): """ Import Share Data. :param argv: Command Line Parameters. -n = Name Example: python -m pyswing.ImportData -n asx """ Logger.log(logging.INFO, "Log Script Call", {"scope":__name__, "arguments":" ".join(argv)}) Logger.pushLogData("script", __name__) marketName = "" try: shortOptions = "n:dh" longOptions = ["marketName=", "debug", "help"] opts, __ = getopt.getopt(argv, shortOptions, longOptions) except getopt.GetoptError as e: Logger.log(logging.ERROR, "Error Reading Options", {"scope": __name__, "exception": str(e)}) usage() sys.exit(2) for opt, arg in opts: if opt in ("-d", "--debug"): Logger().setLevel(logging.DEBUG) elif opt in ("-h", "--help"): print("?") usage() sys.exit() elif opt in ("-n", "--marketName"): marketName = arg if marketName != "": pyswing.database.initialiseDatabase(marketName) Logger.log(logging.INFO, "Import Market Data", {"scope":__name__, "market":marketName}) tickerCodesRelativeFilePath = "resources/%s.txt" % (marketName) market = Market(tickerCodesRelativeFilePath) for index, row in market.tickers.iterrows(): equity = Equity(row[0]) equity.importData() TeamCity.setBuildResultText("Imported Data from Yahoo") else: Logger.log(logging.ERROR, "Missing Options", {"scope": __name__, "options": str(argv)}) usage() sys.exit(2)
class TestCrossingRule(unittest.TestCase): @classmethod def setUpClass(self): Logger.pushLogData("unitTesting", __name__) forceWorkingDirectory() pyswing.database.overrideDatabase("output/TestCrossingRule.db") pyswing.constants.pySwingStartDate = datetime.datetime(2015, 1, 1) deleteFile(pyswing.database.pySwingDatabase) args = "-n %s" % ("unitTesting") createDatabase(args.split()) pretendDate = datetime.datetime(2015, 9, 1) with patch.object(Equity, '_getTodaysDate', return_value=pretendDate) as mock_method: self._equityCBA = Equity("WOR.AX") self._equityCBA.importData() indicatorSMA = IndicatorSMA(self._equityCBA.dataFrame(), "WOR.AX") indicatorSMA.updateIndicator() indicatorEMA = IndicatorEMA(self._equityCBA.dataFrame(), "WOR.AX") indicatorEMA.updateIndicator() @classmethod def tearDownClass(self): deleteFile(pyswing.database.pySwingDatabase) def test_CrossingRule(self): rule = CrossingRule("Indicator_SMA","SMA_5","Indicator_SMA","SMA_10") rule.evaluateRule("WOR.AX") dataPointMatch = rule._ruleData.ix['2015-08-28 00:00:00'] self.assertEqual(dataPointMatch['Match'], 1) dataPointMatch = rule._ruleData.ix['2015-08-31 00:00:00'] self.assertEqual(dataPointMatch['Match'], 0) anotherRule = CrossingRule("Indicator_SMA","SMA_5","Indicator_EMA","EMA_50") anotherRule.evaluateRule("WOR.AX") dataPointMatch = anotherRule._ruleData.ix['2015-07-03 00:00:00'] self.assertEqual(dataPointMatch['Match'], 1) dataPointMatch = anotherRule._ruleData.ix['2015-07-06 00:00:00'] self.assertEqual(dataPointMatch['Match'], 0)
class TestExitValuesTrailingStop(unittest.TestCase): @classmethod def setUpClass(self): Logger.pushLogData("unitTesting", __name__) forceWorkingDirectory() pyswing.database.overrideDatabase( "output/TestExitValuesTrailingStop.db") pyswing.constants.pySwingStartDate = datetime.datetime(2013, 1, 1) deleteFile(pyswing.database.pySwingDatabase) args = "-n %s" % ("unitTesting") createDatabase(args.split()) pretendDate = datetime.datetime(2015, 9, 1) with patch.object(Equity, '_getTodaysDate', return_value=pretendDate) as mock_method: self._equityWOR = Equity("WOR.AX") self._equityWOR.importData() @classmethod def tearDownClass(self): deleteFile(pyswing.database.pySwingDatabase) def test_ExitValues(self): exitValues = ExitValuesTrailingStop("WOR.AX", 0.03, 2) exitValues.calculateExitValues() dataPointBuyWin = exitValues._buyExitValueDataFrame.ix[ '2015-07-02 00:00:00'] self.assertAlmostEqual(dataPointBuyWin['ExitValue'], 1.581, 3) dataPointBuyLose = exitValues._buyExitValueDataFrame.ix[ '2015-07-13 00:00:00'] self.assertAlmostEqual(dataPointBuyLose['ExitValue'], -1.741, 3) dataPointSellWin = exitValues._sellExitValueDataFrame.ix[ '2015-07-03 00:00:00'] self.assertAlmostEqual(dataPointSellWin['ExitValue'], 6.000, 3) dataPointSellLose = exitValues._sellExitValueDataFrame.ix[ '2015-07-14 00:00:00'] self.assertAlmostEqual(dataPointSellLose['ExitValue'], -4.832, 3) strategies = getExitStrategies() self.assertTrue(len(strategies) == 1)
class TestExitValuesYesterday(unittest.TestCase): @classmethod def setUpClass(self): Logger.pushLogData("unitTesting", __name__) forceWorkingDirectory() pyswing.database.overrideDatabase("output/TestExitValuesYesterday.db") pyswing.constants.pySwingStartDate = datetime.datetime(2013, 1, 1) deleteFile(pyswing.database.pySwingDatabase) args = "-n %s" % ("unitTesting") createDatabase(args.split()) pretendDate = datetime.datetime(2015, 9, 1) with patch.object(Equity, '_getTodaysDate', return_value=pretendDate) as mock_method: self._equityWOR = Equity("WOR.AX") self._equityWOR.importData() @classmethod def tearDownClass(self): deleteFile(pyswing.database.pySwingDatabase) def test_ExitValues(self): exitValues = ExitValuesYesterday("WOR.AX", 0.02, 3) exitValues.calculateExitValues() # Gapped Above Limit (10.308780) on Day 2 (Open=9 and Close=10.358178) dataPointBuyWin = exitValues._buyExitValueDataFrame.ix[ '2015-06-30 00:00:00'] self.assertAlmostEqual(dataPointBuyWin['ExitValue'], 6.508, 3) # Gapped Below Stop (9.453822) on Day 3 (Open=9.580096 and Close=9.453336) dataPointBuyLose = exitValues._buyExitValueDataFrame.ix[ '2015-07-17 00:00:00'] self.assertAlmostEqual(dataPointBuyLose['ExitValue'], -1.323, 3) # Passed Stop (9.803891) on Day 3 (Open=10.212030 and Close=9.803891) dataPointSellWin = exitValues._sellExitValueDataFrame.ix[ '2015-06-26 00:00:00'] self.assertAlmostEqual(dataPointSellWin['ExitValue'], 3.997, 3) # Gapped Above Stop (9.628255) on Day 2 (Open=9.443470 and Close=9.745466) dataPointSellLose = exitValues._sellExitValueDataFrame.ix[ '2015-07-09 00:00:00'] self.assertAlmostEqual(dataPointSellLose['ExitValue'], -3.198, 3)
class TestExitValuesYesterday(unittest.TestCase): @classmethod def setUpClass(self): Logger.pushLogData("unitTesting", __name__) forceWorkingDirectory() pyswing.database.overrideDatabase("output/TestExitValuesYesterday.db") pyswing.constants.pySwingStartDate = datetime.datetime(2013, 1, 1) deleteFile(pyswing.database.pySwingDatabase) args = "-n %s" % ("unitTesting") createDatabase(args.split()) pretendDate = datetime.datetime(2015, 9, 1) with patch.object(Equity, '_getTodaysDate', return_value=pretendDate) as mock_method: self._equityWOR = Equity("WOR.AX") self._equityWOR.importData() @classmethod def tearDownClass(self): deleteFile(pyswing.database.pySwingDatabase) def test_ExitValues(self): exitValues = ExitValuesYesterday("WOR.AX", 0.02, 3) exitValues.calculateExitValues() # Gapped Above Limit (10.308780) on Day 2 (Open=9 and Close=10.358178) dataPointBuyWin = exitValues._buyExitValueDataFrame.ix['2015-06-30 00:00:00'] self.assertAlmostEqual(dataPointBuyWin['ExitValue'], 6.508, 3) # Gapped Below Stop (9.453822) on Day 3 (Open=9.580096 and Close=9.453336) dataPointBuyLose = exitValues._buyExitValueDataFrame.ix['2015-07-17 00:00:00'] self.assertAlmostEqual(dataPointBuyLose['ExitValue'], -1.323, 3) # Passed Stop (9.803891) on Day 3 (Open=10.212030 and Close=9.803891) dataPointSellWin = exitValues._sellExitValueDataFrame.ix['2015-06-26 00:00:00'] self.assertAlmostEqual(dataPointSellWin['ExitValue'], 3.997, 3) # Gapped Above Stop (9.628255) on Day 2 (Open=9.443470 and Close=9.745466) dataPointSellLose = exitValues._sellExitValueDataFrame.ix['2015-07-09 00:00:00'] self.assertAlmostEqual(dataPointSellLose['ExitValue'], -3.198, 3)
class TestExitValuesTrailingStop(unittest.TestCase): @classmethod def setUpClass(self): Logger.pushLogData("unitTesting", __name__) forceWorkingDirectory() pyswing.database.overrideDatabase("output/TestExitValuesTrailingStop.db") pyswing.constants.pySwingStartDate = datetime.datetime(2013, 1, 1) deleteFile(pyswing.database.pySwingDatabase) args = "-n %s" % ("unitTesting") createDatabase(args.split()) pretendDate = datetime.datetime(2015, 9, 1) with patch.object(Equity, '_getTodaysDate', return_value=pretendDate) as mock_method: self._equityWOR = Equity("WOR.AX") self._equityWOR.importData() @classmethod def tearDownClass(self): deleteFile(pyswing.database.pySwingDatabase) def test_ExitValues(self): exitValues = ExitValuesTrailingStop("WOR.AX", 0.03, 2) exitValues.calculateExitValues() dataPointBuyWin = exitValues._buyExitValueDataFrame.ix['2015-07-02 00:00:00'] self.assertAlmostEqual(dataPointBuyWin['ExitValue'], 1.581, 3) dataPointBuyLose = exitValues._buyExitValueDataFrame.ix['2015-07-13 00:00:00'] self.assertAlmostEqual(dataPointBuyLose['ExitValue'], -1.741, 3) dataPointSellWin = exitValues._sellExitValueDataFrame.ix['2015-07-03 00:00:00'] self.assertAlmostEqual(dataPointSellWin['ExitValue'], 6.000, 3) dataPointSellLose = exitValues._sellExitValueDataFrame.ix['2015-07-14 00:00:00'] self.assertAlmostEqual(dataPointSellLose['ExitValue'], -4.832, 3) strategies = getExitStrategies() self.assertTrue(len(strategies) == 1)
def setUpClass(self): Logger.pushLogData("unitTesting", __name__) forceWorkingDirectory() pyswing.database.overrideDatabase("output/TestRelativeRule.db") pyswing.constants.pySwingStartDate = datetime.datetime(2015, 1, 1) deleteFile(pyswing.database.pySwingDatabase) args = "-n %s" % ("unitTesting") createDatabase(args.split()) pretendDate = datetime.datetime(2015, 9, 1) with patch.object(Equity, '_getTodaysDate', return_value=pretendDate) as mock_method: self._equityCBA = Equity("WOR.AX") self._equityCBA.importData()
def test_importData(self): latestDate = self._equityCBA._getLatestDate() expectedLatestDate = datetime.datetime(2015, 4, 1) self.assertEquals(latestDate, expectedLatestDate) pretendDate = datetime.datetime(2015, 5, 1) with patch.object(Equity, '_getTodaysDate', return_value=pretendDate) as mock_method: self._equityCBA = Equity("CBA.AX") self._equityCBA.importData() self._equityTLS = Equity("TLS.AX") self._equityTLS.importData() latestDate = self._equityCBA._getLatestDate() expectedLatestDate = datetime.datetime(2015, 5, 1) self.assertEquals(latestDate, expectedLatestDate)
def setUpClass(self): Logger.pushLogData("unitTesting", __name__) forceWorkingDirectory() pyswing.database.overrideDatabase("output/TestEquity.db") pyswing.constants.pySwingStartDate = datetime.datetime(2015, 1, 1) deleteFile(pyswing.database.pySwingDatabase) args = "-n %s" % ("unitTesting") createDatabase(args.split()) pretendDate = datetime.datetime(2015, 4, 1) with patch.object(Equity, '_getTodaysDate', return_value=pretendDate) as mock_method: self._equityCBA = Equity("CBA.AX") self._equityCBA.importData() self._equityTLS = Equity("TLS.AX") self._equityTLS.importData()
class TestIndicatorADI(unittest.TestCase): @classmethod def setUpClass(self): Logger.pushLogData("unitTesting", __name__) forceWorkingDirectory() pyswing.database.overrideDatabase("output/TestIndicatorADI.db") pyswing.constants.pySwingStartDate = datetime.datetime(2014, 1, 1) deleteFile(pyswing.database.pySwingDatabase) args = "-n %s" % ("unitTesting") createDatabase(args.split()) pretendDate = datetime.datetime(2015, 9, 1) with patch.object(Equity, '_getTodaysDate', return_value=pretendDate) as mock_method: self._equityCBA = Equity("CBA.AX") self._equityCBA.importData() self._equityTLS = Equity("TLS.AX") self._equityTLS.importData() @classmethod def tearDownClass(self): deleteFile(pyswing.database.pySwingDatabase) def test_IndicatorSMA(self): indicatorADI = IndicatorADI() dataPoint = indicatorADI._indicatorDataFrame.ix['2015-08-31 00:00:00'] # These tests will fail if the Adjusted Close values change... self.assertAlmostEqual(dataPoint['ADI'], -2.00, 2) self.assertAlmostEqual(dataPoint['ADI_ROC'], 12.5, 2) self.assertAlmostEqual(dataPoint['ADI_EMA'], -1.16, 2) self.assertAlmostEqual(dataPoint['ADI_SUM'], -18.0, 2)
class TestIndicatorSMA(unittest.TestCase): @classmethod def setUpClass(self): Logger.pushLogData("unitTesting", __name__) forceWorkingDirectory() pyswing.database.overrideDatabase("output/TestIndicatorSMA.db") pyswing.constants.pySwingStartDate = datetime.datetime(2014, 1, 1) deleteFile(pyswing.database.pySwingDatabase) args = "-n %s" % ("unitTesting") createDatabase(args.split()) pretendDate = datetime.datetime(2015, 9, 1) with patch.object(Equity, '_getTodaysDate', return_value=pretendDate) as mock_method: self._equityCBA = Equity("CBA.AX") self._equityCBA.importData() @classmethod def tearDownClass(self): deleteFile(pyswing.database.pySwingDatabase) def test_IndicatorSMA(self): cbaIndicatorSMA = IndicatorSMA(self._equityCBA.dataFrame(), "CBA.AX") dataPoint = cbaIndicatorSMA._indicatorDataFrame.ix['2015-08-31 00:00:00'] # These tests will fail if the Adjusted Close values change... self.assertAlmostEqual(dataPoint['SMA_5'], 72.93, 2) self.assertAlmostEqual(dataPoint['SMA_10'], 72.96, 2) self.assertAlmostEqual(dataPoint['SMA_15'], 73.78, 2) self.assertAlmostEqual(dataPoint['SMA_20'], 74.80, 2) self.assertAlmostEqual(dataPoint['SMA_50'], 77.72, 2) self.assertAlmostEqual(dataPoint['SMA_200'], 78.98, 2)
class TestIndicatorSMA(unittest.TestCase): @classmethod def setUpClass(self): Logger.pushLogData("unitTesting", __name__) forceWorkingDirectory() pyswing.database.overrideDatabase("output/TestIndicatorSMA.db") pyswing.constants.pySwingStartDate = datetime.datetime(2014, 1, 1) deleteFile(pyswing.database.pySwingDatabase) args = "-n %s" % ("unitTesting") createDatabase(args.split()) pretendDate = datetime.datetime(2015, 9, 1) with patch.object(Equity, '_getTodaysDate', return_value=pretendDate) as mock_method: self._equityCBA = Equity("CBA.AX") self._equityCBA.importData() @classmethod def tearDownClass(self): deleteFile(pyswing.database.pySwingDatabase) def test_IndicatorSMA(self): cbaIndicatorSMA = IndicatorSMA(self._equityCBA.dataFrame(), "CBA.AX") dataPoint = cbaIndicatorSMA._indicatorDataFrame.ix[ '2015-08-31 00:00:00'] # These tests will fail if the Adjusted Close values change... self.assertAlmostEqual(dataPoint['SMA_5'], 72.93, 2) self.assertAlmostEqual(dataPoint['SMA_10'], 72.96, 2) self.assertAlmostEqual(dataPoint['SMA_15'], 73.78, 2) self.assertAlmostEqual(dataPoint['SMA_20'], 74.80, 2) self.assertAlmostEqual(dataPoint['SMA_50'], 77.72, 2) self.assertAlmostEqual(dataPoint['SMA_200'], 78.98, 2)
class TestIndicatorMACD(unittest.TestCase): @classmethod def setUpClass(self): Logger.pushLogData("unitTesting", __name__) forceWorkingDirectory() pyswing.database.overrideDatabase("output/TestIndicatorMACD.db") pyswing.constants.pySwingStartDate = datetime.datetime(2014, 1, 1) deleteFile(pyswing.database.pySwingDatabase) args = "-n %s" % ("unitTesting") createDatabase(args.split()) pretendDate = datetime.datetime(2015, 9, 1) with patch.object(Equity, '_getTodaysDate', return_value=pretendDate) as mock_method: self._equityCBA = Equity("CBA.AX") self._equityCBA.importData() @classmethod def tearDownClass(self): deleteFile(pyswing.database.pySwingDatabase) def test_IndicatorMACD(self): cbaIndicatorMACD = IndicatorMACD(self._equityCBA.dataFrame(), "CBA.AX") cbaIndicatorMACD.updateIndicator() dataPoint = cbaIndicatorMACD._indicatorDataFrame.ix['2015-08-31 00:00:00'] # These tests will fail if the Adjusted Close values change... self.assertEqual(dataPoint['Code'], "CBA.AX") self.assertAlmostEqual(dataPoint['macd'], -1.59, 2) self.assertAlmostEqual(dataPoint['macdsignal'], -1.51, 2) self.assertAlmostEqual(dataPoint['macdhist'], -0.09, 2)
class TestMultipleIndicatorRule(unittest.TestCase): @classmethod def setUpClass(self): Logger.pushLogData("unitTesting", __name__) forceWorkingDirectory() pyswing.database.overrideDatabase("output/TestMultipleIndicatorRule.db") pyswing.constants.pySwingStartDate = datetime.datetime(2013, 1, 1) deleteFile(pyswing.database.pySwingDatabase) args = "-n %s" % ("unitTesting") createDatabase(args.split()) pretendDate = datetime.datetime(2015, 9, 1) with patch.object(Equity, "_getTodaysDate", return_value=pretendDate) as mock_method: self._equityCBA = Equity("WOR.AX") self._equityCBA.importData() indicatorSMA = IndicatorSMA(self._equityCBA.dataFrame(), "WOR.AX") indicatorSMA.updateIndicator() @classmethod def tearDownClass(self): deleteFile(pyswing.database.pySwingDatabase) def test_IndicatorSMA(self): rule = MultipleIndicatorRule("Equities", "Indicator_SMA", "t1.Close > t2.SMA_200") rule.evaluateRule("WOR.AX") dataPointMatch = rule._ruleData.ix["2015-07-03 00:00:00"] self.assertEqual(dataPointMatch["Match"], 1) dataPointNoMatch = rule._ruleData.ix["2015-07-06 00:00:00"] self.assertEqual(dataPointNoMatch["Match"], 0)
class TestIndicatorMACD(unittest.TestCase): @classmethod def setUpClass(self): Logger.pushLogData("unitTesting", __name__) forceWorkingDirectory() pyswing.database.overrideDatabase("output/TestIndicatorMACD.db") pyswing.constants.pySwingStartDate = datetime.datetime(2014, 1, 1) deleteFile(pyswing.database.pySwingDatabase) args = "-n %s" % ("unitTesting") createDatabase(args.split()) pretendDate = datetime.datetime(2015, 9, 1) with patch.object(Equity, '_getTodaysDate', return_value=pretendDate) as mock_method: self._equityCBA = Equity("CBA.AX") self._equityCBA.importData() @classmethod def tearDownClass(self): deleteFile(pyswing.database.pySwingDatabase) def test_IndicatorMACD(self): cbaIndicatorMACD = IndicatorMACD(self._equityCBA.dataFrame(), "CBA.AX") cbaIndicatorMACD.updateIndicator() dataPoint = cbaIndicatorMACD._indicatorDataFrame.ix[ '2015-08-31 00:00:00'] # These tests will fail if the Adjusted Close values change... self.assertEqual(dataPoint['Code'], "CBA.AX") self.assertAlmostEqual(dataPoint['macd'], -1.59, 2) self.assertAlmostEqual(dataPoint['macdsignal'], -1.51, 2) self.assertAlmostEqual(dataPoint['macdhist'], -0.09, 2)
class TestIndicatorSTOCH(unittest.TestCase): @classmethod def setUpClass(self): Logger.pushLogData("unitTesting", __name__) forceWorkingDirectory() pyswing.database.overrideDatabase("output/TestIndicatorSTOCH.db") pyswing.constants.pySwingStartDate = datetime.datetime(2014, 1, 1) deleteFile(pyswing.database.pySwingDatabase) args = "-n %s" % ("unitTesting") createDatabase(args.split()) pretendDate = datetime.datetime(2015, 9, 1) with patch.object(Equity, '_getTodaysDate', return_value=pretendDate) as mock_method: self._equityCBA = Equity("CBA.AX") self._equityCBA.importData() @classmethod def tearDownClass(self): deleteFile(pyswing.database.pySwingDatabase) def test_IndicatorSTOCH(self): cbaIndicatorSTOCH = IndicatorSTOCH(self._equityCBA.dataFrame(), "CBA.AX") cbaIndicatorSTOCH.updateIndicator() dataPoint = cbaIndicatorSTOCH._indicatorDataFrame.ix['2015-08-31 00:00:00'] self.assertAlmostEqual(dataPoint['slowk'], 74.86, 2) self.assertAlmostEqual(dataPoint['slowd'], 73.89, 2) self.assertAlmostEqual(dataPoint['STOCH_K_ROC'], 507.42, 2) self.assertAlmostEqual(dataPoint['STOCH_D_ROC'], 253.54, 2)
class TestRelativeRule(unittest.TestCase): @classmethod def setUpClass(self): Logger.pushLogData("unitTesting", __name__) forceWorkingDirectory() pyswing.database.overrideDatabase("output/TestRelativeRule.db") pyswing.constants.pySwingStartDate = datetime.datetime(2015, 1, 1) deleteFile(pyswing.database.pySwingDatabase) args = "-n %s" % ("unitTesting") createDatabase(args.split()) pretendDate = datetime.datetime(2015, 9, 1) with patch.object(Equity, '_getTodaysDate', return_value=pretendDate) as mock_method: self._equityCBA = Equity("WOR.AX") self._equityCBA.importData() @classmethod def tearDownClass(self): deleteFile(pyswing.database.pySwingDatabase) def test_RelativeRule(self): rule = RelativeRule("Equities", "Close", -1, Comparison.GreaterThan, 1.01) rule.evaluateRule("WOR.AX") dataPointMatch = rule._ruleData.ix['2015-08-28 00:00:00'] self.assertEqual(dataPointMatch['Match'], 1) dataPointMatch = rule._ruleData.ix['2015-08-31 00:00:00'] self.assertEqual(dataPointMatch['Match'], 0)
class TestIndicatorADX(unittest.TestCase): @classmethod def setUpClass(self): Logger.pushLogData("unitTesting", __name__) forceWorkingDirectory() pyswing.database.overrideDatabase("output/TestIndicatorAROON.db") pyswing.constants.pySwingStartDate = datetime.datetime(2014, 1, 1) deleteFile(pyswing.database.pySwingDatabase) args = "-n %s" % ("unitTesting") createDatabase(args.split()) pretendDate = datetime.datetime(2015, 9, 1) with patch.object(Equity, '_getTodaysDate', return_value=pretendDate) as mock_method: self._equityCBA = Equity("CBA.AX") self._equityCBA.importData() @classmethod def tearDownClass(self): deleteFile(pyswing.database.pySwingDatabase) def test_IndicatorADX(self): cbaIndicatorAROON = IndicatorAROON(self._equityCBA.dataFrame(), "CBA.AX") cbaIndicatorAROON.updateIndicator() dataPoint = cbaIndicatorAROON._indicatorDataFrame.ix['2015-08-31 00:00:00'] self.assertEqual(dataPoint['Code'], "CBA.AX") self.assertAlmostEqual(dataPoint['aroondown'], 71.43, 2) self.assertAlmostEqual(dataPoint['aroonup'], 35.71, 2)
def setUpClass(self): Logger.pushLogData("unitTesting", __name__) forceWorkingDirectory() pyswing.database.overrideDatabase("output/TestMultipleIndicatorRule.db") pyswing.constants.pySwingStartDate = datetime.datetime(2013, 1, 1) deleteFile(pyswing.database.pySwingDatabase) args = "-n %s" % ("unitTesting") createDatabase(args.split()) pretendDate = datetime.datetime(2015, 9, 1) with patch.object(Equity, "_getTodaysDate", return_value=pretendDate) as mock_method: self._equityCBA = Equity("WOR.AX") self._equityCBA.importData() indicatorSMA = IndicatorSMA(self._equityCBA.dataFrame(), "WOR.AX") indicatorSMA.updateIndicator()
class TestEquity(unittest.TestCase): @classmethod def setUpClass(self): Logger.pushLogData("unitTesting", __name__) forceWorkingDirectory() pyswing.database.overrideDatabase("output/TestEquity.db") pyswing.constants.pySwingStartDate = datetime.datetime(2015, 1, 1) deleteFile(pyswing.database.pySwingDatabase) args = "-n %s" % ("unitTesting") createDatabase(args.split()) pretendDate = datetime.datetime(2015, 4, 1) with patch.object(Equity, '_getTodaysDate', return_value=pretendDate) as mock_method: self._equityCBA = Equity("CBA.AX") self._equityCBA.importData() self._equityTLS = Equity("TLS.AX") self._equityTLS.importData() @classmethod def tearDownClass(self): deleteFile(pyswing.database.pySwingDatabase) def test_importData(self): latestDate = self._equityCBA._getLatestDate() expectedLatestDate = datetime.datetime(2015, 4, 1) self.assertEquals(latestDate, expectedLatestDate) pretendDate = datetime.datetime(2015, 5, 1) with patch.object(Equity, '_getTodaysDate', return_value=pretendDate) as mock_method: self._equityCBA = Equity("CBA.AX") self._equityCBA.importData() self._equityTLS = Equity("TLS.AX") self._equityTLS.importData() latestDate = self._equityCBA._getLatestDate() expectedLatestDate = datetime.datetime(2015, 5, 1) self.assertEquals(latestDate, expectedLatestDate) def test_dataFrame(self): cbaData = self._equityCBA.dataFrame() # https://au.finance.yahoo.com/q/hp?s=CBA.AX&a=00&b=1&c=2015&d=02&e=6&f=2015&g=d # Date Open High Low Close Volume Adj Close* # 2 Mar 2015 91.40 92.61 91.14 92.05 2,130,100 85.09 dayData = cbaData.ix['2015-03-02 00:00:00'] open = dayData.Open close = dayData.Close high = dayData.High low = dayData.Low volume = dayData.Volume # These tests will fail if the Adjusted Close values change... self.assertAlmostEqual(open, 84.49, 2) # 91.40 * (85.09 / 92.05) self.assertAlmostEqual(close, 85.09, 2) self.assertEqual(volume, 2130100)
def updateIndicators(argv): """ Update Indicators. :param argv: Command Line Parameters. -n = Name Example: python -m pyswing.UpdateIndicators -n asx """ Logger.log(logging.INFO, "Log Script Call", {"scope": __name__, "arguments": " ".join(argv)}) Logger.pushLogData("script", __name__) marketName = "" try: shortOptions = "n:dh" longOptions = ["marketName=", "debug", "help"] opts, __ = getopt.getopt(argv, shortOptions, longOptions) except getopt.GetoptError as e: Logger.log(logging.ERROR, "Error Reading Options", {"scope": __name__, "exception": str(e)}) usage() sys.exit(2) for opt, arg in opts: if opt in ("-d", "--debug"): Logger().setLevel(logging.DEBUG) elif opt in ("-h", "--help"): print("?") usage() sys.exit() elif opt in ("-n", "--marketName"): marketName = arg if marketName != "": pyswing.database.initialiseDatabase(marketName) Logger.log(logging.INFO, "Update Indicators", {"scope": __name__, "market": marketName}) tickerCodesRelativeFilePath = "resources/%s.txt" % (marketName) market = Market(tickerCodesRelativeFilePath) # Market Indicators adiIndicator = IndicatorADI() adiIndicator.updateIndicator() # Equity Indicators for index, row in market.tickers.iterrows(): tickerCode = row[0] equity = Equity(tickerCode) equityDataFrame = equity.dataFrame() smaIndicator = IndicatorSMA(equityDataFrame, tickerCode) smaIndicator.updateIndicator() emaIndicator = IndicatorEMA(equityDataFrame, tickerCode) emaIndicator.updateIndicator() bbIndicator = IndicatorBB20(equityDataFrame, tickerCode) bbIndicator.updateIndicator() rocIndicator = IndicatorROC(equityDataFrame, tickerCode) rocIndicator.updateIndicator() macdIndicator = IndicatorMACD(equityDataFrame, tickerCode) macdIndicator.updateIndicator() stochIndicator = IndicatorSTOCH(equityDataFrame, tickerCode) stochIndicator.updateIndicator() rsiIndicator = IndicatorRSI(equityDataFrame, tickerCode) rsiIndicator.updateIndicator() adxIndicator = IndicatorADX(equityDataFrame, tickerCode) adxIndicator.updateIndicator() aroonIndicator = IndicatorAROON(equityDataFrame, tickerCode) aroonIndicator.updateIndicator() dxIndicator = IndicatorDX(equityDataFrame, tickerCode) dxIndicator.updateIndicator() TeamCity.setBuildResultText("Updated Indicators") else: Logger.log(logging.ERROR, "Missing Options", {"scope": __name__, "options": str(argv)}) usage() sys.exit(2)
def updateIndicators(argv): """ Update Indicators. :param argv: Command Line Parameters. -n = Name Example: python -m pyswing.UpdateIndicators -n asx """ Logger.log(logging.INFO, "Log Script Call", { "scope": __name__, "arguments": " ".join(argv) }) Logger.pushLogData("script", __name__) marketName = "" try: shortOptions = "n:dh" longOptions = ["marketName=", "debug", "help"] opts, __ = getopt.getopt(argv, shortOptions, longOptions) except getopt.GetoptError as e: Logger.log(logging.ERROR, "Error Reading Options", { "scope": __name__, "exception": str(e) }) usage() sys.exit(2) for opt, arg in opts: if opt in ("-d", "--debug"): Logger().setLevel(logging.DEBUG) elif opt in ("-h", "--help"): print("?") usage() sys.exit() elif opt in ("-n", "--marketName"): marketName = arg if marketName != "": pyswing.database.initialiseDatabase(marketName) Logger.log(logging.INFO, "Update Indicators", { "scope": __name__, "market": marketName }) tickerCodesRelativeFilePath = "resources/%s.txt" % (marketName) market = Market(tickerCodesRelativeFilePath) # Market Indicators adiIndicator = IndicatorADI() adiIndicator.updateIndicator() # Equity Indicators for index, row in market.tickers.iterrows(): tickerCode = row[0] equity = Equity(tickerCode) equityDataFrame = equity.dataFrame() smaIndicator = IndicatorSMA(equityDataFrame, tickerCode) smaIndicator.updateIndicator() emaIndicator = IndicatorEMA(equityDataFrame, tickerCode) emaIndicator.updateIndicator() bbIndicator = IndicatorBB20(equityDataFrame, tickerCode) bbIndicator.updateIndicator() rocIndicator = IndicatorROC(equityDataFrame, tickerCode) rocIndicator.updateIndicator() macdIndicator = IndicatorMACD(equityDataFrame, tickerCode) macdIndicator.updateIndicator() stochIndicator = IndicatorSTOCH(equityDataFrame, tickerCode) stochIndicator.updateIndicator() rsiIndicator = IndicatorRSI(equityDataFrame, tickerCode) rsiIndicator.updateIndicator() adxIndicator = IndicatorADX(equityDataFrame, tickerCode) adxIndicator.updateIndicator() aroonIndicator = IndicatorAROON(equityDataFrame, tickerCode) aroonIndicator.updateIndicator() dxIndicator = IndicatorDX(equityDataFrame, tickerCode) dxIndicator.updateIndicator() TeamCity.setBuildResultText("Updated Indicators") else: Logger.log(logging.ERROR, "Missing Options", { "scope": __name__, "options": str(argv) }) usage() sys.exit(2)
from pyswing.objects.equity import Equity cbaEquity = Equity("CBA.AX") cbaEquity.dataFrame().query("Date > '2015-01-01 00:00:00'").plot( y=['Close'], title='CBA Close 2015') import pyswing.database import sqlite3 from pandas.io.sql import read_sql_query pyswing.database.initialiseDatabase("ftse") connection = sqlite3.connect(pyswing.database.pySwingDatabase) query = "select * from Indicator_ROC WHERE CODE = 'AAL.L'" cbaEquityData = read_sql_query(query, connection, 'Date') connection.close() cbaEquityData.query("Date > '2010-01-01 00:00:00'").plot( y=['ROC_5', 'ROC_10', 'ROC_20'], title='Hello!') import pyswing.database import sqlite3 from pandas.io.sql import read_sql_query connection = sqlite3.connect(pyswing.database.pySwingDatabase) query = "select b.*, e.Close from Indicator_BB20 b inner join Equities e on b.Date = e.Date and b.Code = e.Code and b.Date > '2015-03-01 00:00:00' and b.Code = 'CBA.AX'" cbaEquityData = read_sql_query(query, connection, 'Date') connection.close() cbaEquityData.query("Date > '2015-01-01 00:00:00'").plot( y=['upperband', 'middleband', 'lowerband', 'Close'], title='CBA BBAND 2015') import pyswing.database import sqlite3 from pandas.io.sql import read_sql_query connection = sqlite3.connect("output/TestMultipleIndicatorRule.db")
from pyswing.objects.equity import Equity cbaEquity = Equity("CBA.AX") cbaEquity.dataFrame().query("Date > '2015-01-01 00:00:00'").plot(y=['Close'], title='CBA Close 2015') import pyswing.database import sqlite3 from pandas.io.sql import read_sql_query pyswing.database.initialiseDatabase("ftse") connection = sqlite3.connect(pyswing.database.pySwingDatabase) query = "select * from Indicator_ROC WHERE CODE = 'AAL.L'" cbaEquityData = read_sql_query(query, connection, 'Date') connection.close() cbaEquityData.query("Date > '2010-01-01 00:00:00'").plot(y=['ROC_5','ROC_10','ROC_20'], title='Hello!') import pyswing.database import sqlite3 from pandas.io.sql import read_sql_query connection = sqlite3.connect(pyswing.database.pySwingDatabase) query = "select b.*, e.Close from Indicator_BB20 b inner join Equities e on b.Date = e.Date and b.Code = e.Code and b.Date > '2015-03-01 00:00:00' and b.Code = 'CBA.AX'" cbaEquityData = read_sql_query(query, connection, 'Date') connection.close() cbaEquityData.query("Date > '2015-01-01 00:00:00'").plot(y=['upperband','middleband','lowerband','Close'], title='CBA BBAND 2015') import pyswing.database import sqlite3 from pandas.io.sql import read_sql_query connection = sqlite3.connect("output/TestMultipleIndicatorRule.db") query = "select e.Date, Close, SMA_200 from Equities e inner join Indicator_SMA i on e.Date = i.Date and e.Code = i.Code" cbaEquityData = read_sql_query(query, connection, 'Date') connection.close()
def importData(argv): """ Import Share Data. :param argv: Command Line Parameters. -n = Name Example: python -m pyswing.ImportData -n asx """ Logger.log(logging.INFO, "Log Script Call", { "scope": __name__, "arguments": " ".join(argv) }) Logger.pushLogData("script", __name__) marketName = "" try: shortOptions = "n:dh" longOptions = ["marketName=", "debug", "help"] opts, __ = getopt.getopt(argv, shortOptions, longOptions) except getopt.GetoptError as e: Logger.log(logging.ERROR, "Error Reading Options", { "scope": __name__, "exception": str(e) }) usage() sys.exit(2) for opt, arg in opts: if opt in ("-d", "--debug"): Logger().setLevel(logging.DEBUG) elif opt in ("-h", "--help"): print("?") usage() sys.exit() elif opt in ("-n", "--marketName"): marketName = arg if marketName != "": pyswing.database.initialiseDatabase(marketName) Logger.log(logging.INFO, "Import Market Data", { "scope": __name__, "market": marketName }) tickerCodesRelativeFilePath = "resources/%s.txt" % (marketName) market = Market(tickerCodesRelativeFilePath) for index, row in market.tickers.iterrows(): equity = Equity(row[0]) equity.importData() TeamCity.setBuildResultText("Imported Data from Yahoo") else: Logger.log(logging.ERROR, "Missing Options", { "scope": __name__, "options": str(argv) }) usage() sys.exit(2)