<commit_before>import json
from time import time

import matplotlib.pyplot as plt

from exchange import ExchangeInterface
from analysis import StrategyAnalyzer
from behaviours.ui.backtesting.candlestick import Candlestick

"""
A Chart class encompassing functionality for a set of historical data in a time-series domain
"""
class Chart(object):
    def __init__(self, pair, period, exchange_name, exchange_interface, start_time=time() - 2000000):

        self.pair = pair
        self.period = period

        self.start_time = start_time
        self.indicators = StrategyAnalyzer(exchange_interface)

        self.data = []

        # Query the data to fill our chart truncate it to 'length' elements
        rawdata = exchange_interface.get_historical_data(pair, exchange_name, period, start_time*1000)

        for i in range(len(rawdata)):
            datum = rawdata[i]
            stick = Candlestick(open=datum[1], high=datum[2], low=datum[3], close=datum[4], price_average=(datum[2] + datum[3])/2.)
            stick.time = i
            self.data.append(stick)

    def get_points(self):
        return self.data

    '''
    Returns the indicators specified in the **kwargs dictionary as a json-serializable dictionary
    '''
    def get_indicators(self, **kwargs):

        # Indicators are hardcoded for now. Will be updated to accommodate variable-sized MA's
        response = {
            'bollinger_upper': [],
            'bollinger_lower': [],
            'sma9': [],
            'sma15': []
        }

        # Get closing historical datapoints
        closings = [[0, 0, 0, 0, x.close, 0] for x in self.data]

        # The 'bollinger' keyword argument takes in a period, i.e. bollinger=21
        if "bollinger" in kwargs:
            period = kwargs["bollinger"]
            assert type(period) is int

            bbupper = [datum["values"][0] for datum in self.indicators.analyze_bollinger_bands(closings, all_data=True)]
            bblower = [datum["values"][2] for datum in self.indicators.analyze_bollinger_bands(closings, all_data=True)]

            response['bollinger_upper'] = bbupper
            response['bollinger_lower'] = bblower


        # The 'sma' keyword argument takes in a list of periods, i.e. sma=[9,15,21]
        if "sma" in kwargs:
            periods = kwargs["sma"]
            assert type(periods) is list

            for period in periods:
                response['sma' + str(period)] = [datum["values"] for datum in self.indicators.analyze_sma(closings, period_count=period, all_data=True)]

        return response

    '''
    Plots the specified indicators on a matplotlib plot
    '''
    def plot_indicators(self, **kwargs):

        # Get closing historical datapoints
        closings = [[0, 0, 0, 0, x.close, 0] for x in self.data]
        plt.plot([x.close for x in self.data])

        # The 'bollinger' keyword argument takes in a period, i.e. bollinger=21
        if "bollinger" in kwargs:
            period = kwargs["bollinger"]
            assert type(period) is int

            bbupper = [datum["values"][0] for datum in self.indicators.analyze_bollinger_bands(closings, all_data=True)]
            bblower = [datum["values"][2] for datum in self.indicators.analyze_bollinger_bands(closings, all_data=True)]
            plt.plot(np.arange(period, len(closings)), bbupper[period:], 'g--')
            plt.plot(np.arange(period, len(closings)), bblower[period:], 'b--')

        # The 'sma' keyword argument takes in a list of periods, i.e. sma=[9,15,21]
        if "sma" in kwargs:
            periods = kwargs["sma"]
            assert type(periods) is list

            for period in periods:
                plt.plot([datum["values"] for datum in self.indicators.analyze_sma(closings, period_count=period, all_data=True)])

    '''
    Plots each buy trade as a green 'x', and each sell trade as a red 'x'
    '''
    def plot_trades(self, buys, sells):
        for timestamp, price in buys:
            plt.plot(timestamp, price, 'gx')

        for timestamp, price in sells:
            plt.plot(timestamp, price, 'rx')


<commit_msg>nan-to-num when plotting<commit_after>import json
from time import time

import matplotlib.pyplot as plt

from exchange import ExchangeInterface
from analysis import StrategyAnalyzer
from behaviours.ui.backtesting.candlestick import Candlestick

"""
A Chart class encompassing functionality for a set of historical data in a time-series domain
"""
class Chart(object):
    def __init__(self, pair, period, exchange_name, exchange_interface, start_time=time() - 2000000):

        self.pair = pair
        self.period = period

        self.start_time = start_time
        self.indicators = StrategyAnalyzer(exchange_interface)

        self.data = []

        # Query the data to fill our chart truncate it to 'length' elements
        rawdata = exchange_interface.get_historical_data(pair, exchange_name, period, start_time*1000)

        for i in range(len(rawdata)):
            datum = rawdata[i]
            stick = Candlestick(open=datum[1], high=datum[2], low=datum[3], close=datum[4], price_average=(datum[2] + datum[3])/2.)
            stick.time = i
            self.data.append(stick)

    def get_points(self):
        return self.data

    '''
    Returns the indicators specified in the **kwargs dictionary as a json-serializable dictionary
    '''
    def get_indicators(self, **kwargs):
        import numpy as np

        # Indicators are hardcoded for now. Will be updated to accommodate variable-sized MA's
        response = {
            'bollinger_upper': [],
            'bollinger_lower': [],
            'sma9': [],
            'sma15': []
        }

        # Get closing historical datapoints
        closings = [[0, 0, 0, 0, x.close, 0] for x in self.data]

        # The 'bollinger' keyword argument takes in a period, i.e. bollinger=21
        if "bollinger" in kwargs:
            period = kwargs["bollinger"]
            assert type(period) is int

            bbupper = [np.nan_to_num(datum["values"][0]) for datum in self.indicators.analyze_bollinger_bands(closings, all_data=True)]
            bblower = [np.nan_to_num(datum["values"][2]) for datum in self.indicators.analyze_bollinger_bands(closings, all_data=True)]

            response['bollinger_upper'] = bbupper
            response['bollinger_lower'] = bblower


        # The 'sma' keyword argument takes in a list of periods, i.e. sma=[9,15,21]
        if "sma" in kwargs:
            periods = kwargs["sma"]
            assert type(periods) is list

            for period in periods:
                response['sma' + str(period)] = [np.nan_to_num(datum["values"][0]) for datum in self.indicators.analyze_sma(closings, period_count=period, all_data=True)]

        return response

    '''
    Plots the specified indicators on a matplotlib plot
    '''
    def plot_indicators(self, **kwargs):
        import numpy as np

        # Get closing historical datapoints
        closings = [[0, 0, 0, 0, x.close, 0] for x in self.data]
        plt.plot([x.close for x in self.data])

        # The 'bollinger' keyword argument takes in a period, i.e. bollinger=21
        if "bollinger" in kwargs:
            period = kwargs["bollinger"]
            assert type(period) is int

            bbupper = [np.nan_to_num(datum["values"][0]) for datum in self.indicators.analyze_bollinger_bands(closings, all_data=True)]
            bblower = [np.nan_to_num(datum["values"][2]) for datum in self.indicators.analyze_bollinger_bands(closings, all_data=True)]
            plt.plot(np.arange(period, len(closings)), bbupper[period:], 'g--')
            plt.plot(np.arange(period, len(closings)), bblower[period:], 'b--')

        # The 'sma' keyword argument takes in a list of periods, i.e. sma=[9,15,21]
        if "sma" in kwargs:
            periods = kwargs["sma"]
            assert type(periods) is list

            for period in periods:
                plt.plot([np.nan_to_num(datum["values"][0]) for datum in self.indicators.analyze_sma(closings, period_count=period, all_data=True)])

    '''
    Plots each buy trade as a green 'x', and each sell trade as a red 'x'
    '''
    def plot_trades(self, buys, sells):
        for timestamp, price in buys:
            plt.plot(timestamp, price, 'gx')

        for timestamp, price in sells:
            plt.plot(timestamp, price, 'rx')



{'fraction_non_alphanumeric': 0.10956293914493272, 'fraction_numerical': 0.011909015124449208, 'mean_word_length': 2.6213885295385944, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5271001', 'n_tokens_mistral': 2682, 'n_tokens_neox': 2509, 'n_words': 724}