Exemple #1
0
    def stake(self, confidence, value):
        """ participate in the staking competition

        confidence: your confidence (C) value
        value: amount of NMR you are willing to stake
        """

        query = '''
          mutation($code: String,
            $confidence: String!
            $password: String
            $round: Int!
            $value: String!) {
              stake(code: $code
                    confidence: $confidence
                    password: $password
                    round: $round
                    value: $value) {
                id
                status
                txHash
                value
              }
        }
        '''
        arguments = {'code': 'somecode',
                     'confidence': str(confidence),
                     'password': "******",
                     'round': self.get_current_round(),
                     'value': str(value)}
        result = self.raw_query(query, arguments, authorization=True)
        stake = result['data']
        utils.replace(stake, "value", utils.parse_float_string)
        return stake
Exemple #2
0
    def daily_submissions_performances(self, username: str) -> List[Dict]:
        """Fetch daily Numerai Signals performance of a user's submissions.

        Args:
            username (str)

        Returns:
            list of dicts: list of daily submission performance entries

            For each entry in the list, there is a dict with the following
            content:

                * date (`datetime`)
                * returns (`float`)
                * submission_time (`datetime`)
                * correlation (`float`)
                * mmc (`float`)
                * roundNumber (`int`)
                * corrRep (`float`)
                * mmcRep (`float`)


        Example:
            >>> api = SignalsAPI()
            >>> api.daily_submissions_performances("uuazed")
            [{'date': datetime.datetime(2020, 5, 16, 0, 0),
              'returns': 1.256,
              'submissionTime': datetime.datetime(2020, 5, 12, 1, 23)},
              'corrRep': None,
              'mmc': None,
              'mmcRep': None,
              'roundNumber': 226,
              'correlation': 0.03}
             ...
              ]
        """
        query = """
          query($username: String!) {
            signalsUserProfile(username: $username) {
              dailySubmissionPerformances {
                date
                returns
                submissionTime
                correlation
                mmc
                roundNumber
                corrRep
                mmcRep
              }
            }
          }
        """
        arguments = {'username': username}
        data = self.raw_query(query, arguments)['data']['signalsUserProfile']
        performances = data['dailySubmissionPerformances']
        # convert strings to python objects
        for perf in performances:
            utils.replace(perf, "date", utils.parse_datetime_string)
            utils.replace(perf, "submissionTime", utils.parse_datetime_string)
        return performances
Exemple #3
0
    def stake_change(self,
                     nmr,
                     action: str = "decrease",
                     model_id: str = None,
                     tournament: int = 8) -> Dict:
        """Change stake by `value` NMR.

        Args:
            nmr (float or str): amount of NMR you want to increase/decrease
            action (str): `increase` or `decrease`
            model_id (str): Target model UUID (required for accounts with
                multiple models)
            tournament (int): ID of the tournament (optional, defaults to 8)
                -- DEPRECATED there is only one tournament nowadays

        Returns:
            dict: stake information with the following content:

              * dueDate (`datetime`)
              * status (`str`)
              * requestedAmount (`decimal.Decimal`)
              * type (`str`)

        Example:
            >>> api = NumerAPI(secret_key="..", public_id="..")
            >>> model = api.get_models()['uuazed']
            >>> api.stake_change(10, "decrease", model)
            {'dueDate': None,
             'requestedAmount': decimal.Decimal('10'),
             'type': 'decrease',
             'status': ''}
        """
        query = '''
          mutation($value: String!
                   $type: String!
                   $tournamentNumber: Int!
                   $modelId: String) {
              v2ChangeStake(value: $value
                            type: $type
                            modelId: $modelId
                            tournamentNumber: $tournamentNumber) {
                dueDate
                requestedAmount
                status
                type
              }
        }
        '''
        arguments = {
            'value': str(nmr),
            'type': action,
            'modelId': model_id,
            'tournamentNumber': tournament
        }
        result = self.raw_query(query, arguments, authorization=True)
        stake = result['data']['v2ChangeStake']
        utils.replace(stake, "requestedAmount", utils.parse_float_string)
        utils.replace(stake, "dueDate", utils.parse_datetime_string)
        return stake
Exemple #4
0
    def daily_model_performances(self, username: str) -> List[Dict]:
        """Fetch daily performance of a user.

        Args:
            username (str)

        Returns:
            list of dicts: list of daily model performance entries

            For each entry in the list, there is a dict with the following
            content:

                * rank (`int`)
                * date (`datetime`)
                * corrRep (`float` or None)
                * corrRank (`int`)
                * mmcRep (`float` or None)
                * mmcRank (`int`)
                * fncRep (`float` or None)
                * fncRank (`int`)

        Example:
            >>> api = NumerAPI()
            >>> api.daily_model_performances("uuazed")
            [{'corrRep': 0.04989791277211584,
             'date': datetime.datetime(2021, 6, 29, 0, 0, tzinfo=tzutc()),
             'fncRep': 0.013364783709176759,
             'mmcRep': 0.006799019156483222,
             'payoutPending': '5.979926674348371782',
             'payoutSettled': None,
             'rank': 559,
             'stakeValue': '226.746596100340180000'},
             ...
            ]
        """
        query = """
          query($username: String!) {
            v3UserProfile(modelName: $username) {
              dailyModelPerformances {
                date
                corrRep
                corrRank
                mmcRep
                mmcRank
                fncRep
                fncRank
              }
            }
          }
        """
        arguments = {'username': username}
        data = self.raw_query(query, arguments)['data']['v3UserProfile']
        performances = data['dailyModelPerformances']
        # convert strings to python objects
        for perf in performances:
            utils.replace(perf, "date", utils.parse_datetime_string)
        return performances
Exemple #5
0
    def daily_submissions_performances(self, username: str) -> List[Dict]:
        """Fetch daily performance of a user's submissions.

        Args:
            username (str)

        Returns:
            list of dicts: list of daily submission performance entries

            For each entry in the list, there is a dict with the following
            content:

                * date (`datetime`)
                * correlation (`float`)
                * roundNumber (`int`)
                * mmc (`float`): metamodel contribution
                * fnc (`float`): feature neutral correlation
                * correlationWithMetamodel (`float`)

        Example:
            >>> api = NumerAPI()
            >>> api.daily_user_performances("uuazed")
            [{'roundNumber': 181,
              'correlation': -0.011765912,
              'date': datetime.datetime(2019, 10, 16, 0, 0),
              'mmc': 0.3,
              'fnc': 0.1,
              'correlationWithMetamodel': 0.87},
              ...
            ]
        """
        query = """
          query($username: String!) {
            v2UserProfile(username: $username) {
              dailySubmissionPerformances {
                date
                correlation
                roundNumber
                mmc
                fnc
                correlationWithMetamodel
              }
            }
          }
        """
        arguments = {'username': username}
        data = self.raw_query(query, arguments)['data']['v2UserProfile']
        performances = data['dailySubmissionPerformances']
        # convert strings to python objects
        for perf in performances:
            utils.replace(perf, "date", utils.parse_datetime_string)
        # remove useless items
        performances = [
            p for p in performances
            if any([p['correlation'], p['fnc'], p['mmc']])
        ]
        return performances
Exemple #6
0
def test_replace():
    d = None
    assert utils.replace(d, "a", float) is None
    # empty dict
    d = {}
    assert not utils.replace(d, "a", float)
    # normal case
    d = {"a": "1"}
    utils.replace(d, "a", float)
    assert d["a"] == 1.0
Exemple #7
0
    def daily_model_performances(self, username: str) -> List[Dict]:
        """Fetch daily Numerai Signals performance of a model.

        Args:
            username (str)

        Returns:
            list of dicts: list of daily user performance entries

            For each entry in the list, there is a dict with the following
            content:

                * date (`datetime`)
                * corrRank (`int`)
                * corrRep (`float` or None)
                * mmcRank (`int`)
                * mmcRep (`float` or None)
                * corr_20dRank (`int`)
                * corr_20dRep (`float` or None)

        Example:
            >>> api = SignalsAPI()
            >>> api.daily_model_performances("floury_kerril_moodle")
            [{'corrRank': 45,
              'corrRep': -0.00010935616731632354,
              'corr_20dRank': None,
              'corr_20dRep': None,
              'date': datetime.datetime(2020, 9, 18, 0, 0, tzinfo=tzutc()),
              'mmcRank': 6,
              'mmcRep': 0.0},
              ...
              ]
        """
        query = """
          query($username: String!) {
            v2SignalsProfile(modelName: $username) {
              dailyModelPerformances {
                date
                corrRank
                corrRep
                mmcRep
                mmcRank
                corr_20dRep
                corr_20dRank
              }
            }
          }
        """
        arguments = {'username': username}
        data = self.raw_query(query, arguments)['data']['v2SignalsProfile']
        performances = data['dailyModelPerformances']
        # convert strings to python objects
        for perf in performances:
            utils.replace(perf, "date", utils.parse_datetime_string)
        return performances
Exemple #8
0
    def get_rankings(self, limit=50, offset=0):
        """Get the overall ranking

        Args:
            limit (int): number of items to return (optional, defaults to 50)
            offset (int): number of items to skip (optional, defaults to 0)

        Returns:
            list of dicts: list of ranking items

            Each dict contains the following items:

                * id (`str`)
                * username (`str`)
                * nmrBurned (`decimal.Decimal`)
                * nmrPaid (`decimal.Decimal`)
                * nmrStaked (`decimal.Decimal`)
                * rep (`int`)
                * stakeCount (`int`)
                * usdEarned (`decimal.Decimal`)

        Example:
            >>> numerapi.NumerAPI().get_rankings(1)
            [{'username': '******',
              'usdEarned': Decimal('16347.12'),
              'stakeCount': 41,
              'rep': 14,
              'nmrStaked': Decimal('250.000000000000000000'),
              'nmrPaid': Decimal('16061.37'),
              'nmrBurned': Decimal('295.400000000000000000'),
              'id': 'bbee4f0e-f238-4d8a-8f1b-5eb384cdcbfc'}]
        """
        query = '''
            query($limit: Int!
                  $offset: Int!) {
              rankings(limit: $limit
                       offset: $offset) {
                username
                id
                nmrBurned
                nmrPaid
                nmrStaked
                rep
                stakeCount
                usdEarned
              }
            }
        '''
        arguments = {'limit': limit, 'offset': offset}
        data = self.raw_query(query, arguments)['data']['rankings']
        for item in data:
            for p in ["nmrBurned", "nmrPaid", "nmrStaked", "usdEarned"]:
                utils.replace(item, p, utils.parse_float_string)
        return data
Exemple #9
0
    def wallet_transactions(self) -> List:
        """Get all transactions in your wallet.

        Returns:
            list: List of dicts with the following structure:

                 * from (`str`)
                 * posted (`bool`)
                 * status (`str`)
                 * to (`str`)
                 * txHash (`str`)
                 * amount (`decimal.Decimal`)
                 * time (`datetime`)
                 * tournament (`int`)

        Example:
            >>> api = NumerAPI(secret_key="..", public_id="..")
            >>> api.wallet_transactions()
            [{'amount': Decimal('1.000000000000000000'),
              'from': '0x000000000000000000000000000000000000313bc',
              'status': 'confirmed',
              'time': datetime.datetime(2023, 4, 19, 13, 28, 45),
              'to': '0x000000000000000000000000000000000006621',
              'tournament': None,
              'txHash': '0xeasdfkjaskljf314451234',
              'type': 'withdrawal'},

              ...
              ]
        """
        query = """
          query {
            account {
              walletTxns {
                amount
                from
                status
                to
                time
                tournament
                txHash
                type
              }
            }
          }
        """
        txs = self.raw_query(
            query, authorization=True)['data']['account']['walletTxns']
        # convert strings to python objects
        for transaction in txs:
            utils.replace(transaction, "time", utils.parse_datetime_string)
            utils.replace(transaction, "amount", utils.parse_float_string)
        return txs
Exemple #10
0
    def get_competitions(self, tournament=1):
        """Retrieves information about all competitions

        Args:
            tournament (int, optional): ID of the tournament, defaults to 1

        Returns:
            list of dicts: list of rounds

            Each round's dict contains the following items:

                * datasetId (`str`)
                * number (`int`)
                * openTime (`datetime`)
                * resolveTime (`datetime`)
                * resolvedGeneral (`bool`)
                * resolvedStaking (`bool`)

        Example:
            >>> NumerAPI().get_competitions()
            [
             {'datasetId': '59a70840ca11173c8b2906ac',
              'number': 71,
              'openTime': datetime.datetime(2017, 8, 31, 0, 0),
              'resolveTime': datetime.datetime(2017, 9, 27, 21, 0),
              'resolvedGeneral': True,
              'resolvedStaking': True
             },
              ..
            ]
        """
        self.logger.info("getting rounds...")

        query = '''
            query($tournament: Int!) {
              rounds(tournament: $tournament) {
                number
                resolveTime
                datasetId
                openTime
                resolvedGeneral
                resolvedStaking
              }
            }
        '''
        arguments = {'tournament': tournament}
        result = self.raw_query(query, arguments)
        rounds = result['data']['rounds']
        # convert datetime strings to datetime.datetime objects
        for r in rounds:
            utils.replace(r, "openTime", utils.parse_datetime_string)
            utils.replace(r, "resolveTime", utils.parse_datetime_string)
        return rounds
Exemple #11
0
    def public_user_profile(self, username: str) -> Dict:
        """Fetch the public profile of a user.

        Args:
            username (str)

        Returns:
            dict: user profile including the following fields:

                * username (`str`)
                * startDate (`datetime`)
                * netEarnings (`float`)
                * id (`string`)
                * historicalNetUsdEarnings (`float`)
                * historicalNetNmrEarnings (`float`)
                * badges (`list of str`)
                * bio (`str`)
                * totalStake (`float`)

        Example:
            >>> api = NumerAPI()
            >>> api.public_user_profile("niam")
            {'username': '******',
             'startDate': datetime.datetime(2018, 6, 14, 22, 58, 2, 186221),
             'netEarnings': None,
             'id': '024c9bb9-77af-4b3f-91c7-63062fce2b80',
             'historicalNetUsdEarnings': '3669.41',
             'historicalNetNmrEarnings': '1094.247665827645663410',
             'badges': ['burned_3', 'compute_0', 'submission-streak_1'],
             'bio': 'blabla',
             'totalStake': 12.2}
        """
        query = """
          query($username: String!) {
            v2UserProfile(username: $username) {
              badges
              historicalNetNmrEarnings
              historicalNetUsdEarnings
              id
              netEarnings
              startDate
              username
              bio
              totalStake
            }
          }
        """
        arguments = {'username': username}
        data = self.raw_query(query, arguments)['data']['v2UserProfile']
        # convert strings to python objects
        utils.replace(data, "startDate", utils.parse_datetime_string)
        return data
Exemple #12
0
    def daily_user_performances(self, username: str) -> List[Dict]:
        """DEPRECATED Fetch daily Numerai Signals performance of a user.

        Args:
            username (str)

        Returns:
            list of dicts: list of daily user performance entries

            For each entry in the list, there is a dict with the following
            content:

                * rank (`int`)
                * date (`datetime`)
                * sharpe (`float`)
                * mmcRep (`float`)
                * reputation (`float`)

        Example:
            >>> api = SignalsAPI()
            >>> api.daily_user_performances("floury_kerril_moodle")
            [{'date': datetime.datetime(2020, 5, 16, 0, 0,
              'rank': 1,
              'sharpe': 2.35,
              'mmcRep': 0.35,
              'reputation': 1.35
              },
             ...]
        """
        query = """
          query($username: String!) {
            signalsUserProfile(username: $username) {
              dailyUserPerformances {
                rank
                date
                sharpe
                mmcRep
                reputation
              }
            }
          }
        """
        self.logger.warning("Method daily_user_performances is DEPRECATED, "
                            "use daily_model_performances")
        arguments = {'username': username}
        data = self.raw_query(query, arguments)['data']['signalsUserProfile']
        performances = data['dailyUserPerformances']
        # convert strings to python objects
        for perf in performances:
            utils.replace(perf, "date", utils.parse_datetime_string)
        return performances
Exemple #13
0
    def get_stakes(self):
        """List all your stakes.

        Returns:
            list of dicts: stakes

            Each stake is a dict with the following fields:

                * confidence (`decimal.Decimal`)
                * roundNumber (`int`)
                * tournamentId (`int`)
                * soc (`decimal.Decimal`)
                * insertedAt (`datetime`)
                * staker (`str`): NMR adress used for staking
                * status (`str`)
                * txHash (`str`)
                * value (`decimal.Decimal`)

        Example:

            >>> api = NumerAPI(secret_key="..", public_id="..")
            >>> api.get_stakes()
            [{'confidence': Decimal('0.053'),
              'insertedAt': datetime.datetime(2017, 9, 26, 8, 18, 36, 709000, tzinfo=tzutc()),
              'roundNumber': 74,
              'soc': Decimal('56.60'),
              'staker': '0x0000000000000000000000000000000000003f9e',
              'status': 'confirmed',
              'tournamentId': 1,
              'txHash': '0x1cbb985629552a0f57b98a1e30a5e7f101a992121db318cef02e02aaf0e91c95',
              'value': Decimal('3.00')},
              ..
             ]
        """
        query = """
          query {
            user {
              stakeTxs {
                confidence
                insertedAt
                roundNumber
                tournamentId
                soc
                staker
                status
                txHash
                value
              }
            }
          }
        """
        data = self.raw_query(query, authorization=True)['data']
        stakes = data['user']['stakeTxs']
        # convert strings to python objects
        for s in stakes:
            utils.replace(s, "insertedAt", utils.parse_datetime_string)
            utils.replace(s, "soc", utils.parse_float_string)
            utils.replace(s, "confidence", utils.parse_float_string)
            utils.replace(s, "value", utils.parse_float_string)
        return stakes
Exemple #14
0
    def get_payments(self):
        """Get all your payments.

        Returns:
            list of dicts: payments

            For each payout in the list, a dict contains the following items:

                * nmrAmount (`decimal.Decimal`)
                * usdAmount (`decimal.Decimal`)
                * tournament (`str`)
                * round (`dict`)
                 * number (`int`)
                 * openTime (`datetime`)
                 * resolveTime (`datetime`)
                 * resolvedGeneral (`bool`)
                 * resolvedStaking (`bool`)

        Example:
            >>> api = NumerAPI(secret_key="..", public_id="..")
            >>> api.get_payments()
            [{'nmrAmount': Decimal('0.00'),
              'round': {'number': 84,
               'openTime': datetime.datetime(2017, 12, 2, 18, 0, tzinfo=tzutc()),
               'resolveTime': datetime.datetime(2018, 1, 1, 18, 0, tzinfo=tzutc()),
               'resolvedGeneral': True,
               'resolvedStaking': True},
              'tournament': 'staking',
              'usdAmount': Decimal('17.44')},
              ...
             ]
    """
        query = """
          query {
            user {
              payments {
                nmrAmount
                round {
                  number
                  openTime
                  resolveTime
                  resolvedGeneral
                  resolvedStaking
                }
                tournament
                usdAmount
              }
            }
          }
        """
        data = self.raw_query(query, authorization=True)['data']
        payments = data['user']['payments']
        # convert strings to python objects
        for p in payments:
            utils.replace(p['round'], "openTime", utils.parse_datetime_string)
            utils.replace(p['round'], "resolveTime",
                          utils.parse_datetime_string)
            utils.replace(p, "usdAmount", utils.parse_float_string)
            utils.replace(p, "nmrAmount", utils.parse_float_string)
        return payments
Exemple #15
0
 def get_stakes(self):
     """all your stakes"""
     query = """
       query {
         user {
           stakeTxs {
             confidence
             insertedAt
             roundNumber
             soc
             staker
             status
             txHash
             value
           }
         }
       }
     """
     data = self.raw_query(query, authorization=True)['data']
     stakes = data['user']['stakeTxs']
     # convert strings to python objects
     for s in stakes:
         utils.replace(s, "insertedAt", utils.parse_datetime_string)
         utils.replace(s, "soc", utils.parse_float_string)
         utils.replace(s, "confidence", utils.parse_float_string)
         utils.replace(s, "value", utils.parse_float_string)
     return stakes
Exemple #16
0
 def get_payments(self):
     """all your payments"""
     query = """
       query {
         user {
           payments {
             nmrAmount
             round {
               number
               openTime
               resolveTime
               resolvedGeneral
               resolvedStaking
             }
             tournament
             usdAmount
           }
         }
       }
     """
     data = self.raw_query(query, authorization=True)['data']
     payments = data['user']['payments']
     # convert strings to python objects
     for p in payments:
         utils.replace(p['round'], "openTime", utils.parse_datetime_string)
         utils.replace(p['round'], "resolveTime",
                       utils.parse_datetime_string)
         utils.replace(p, "usdAmount", utils.parse_float_string)
         utils.replace(p, "nmrAmount", utils.parse_float_string)
     return payments
Exemple #17
0
    def get_rankings(self, limit=50, offset=0):
        """Get the overall ranking

        Args:
            limit (int): number of items to return (optional, defaults to 50)
            offset (int): number of items to skip (optional, defaults to 0)

        Returns:
            list of dicts: list of ranking items

            Each dict contains the following items:

                * username (`str`)
                * nmrBurned (`decimal.Decimal`)
                * nmrEarned (`decimal.Decimal`)
                * nmrStaked (`decimal.Decimal`)
                * reputation (`float`)
                * usdEarned (`decimal.Decimal`)

        Example:
            >>> numerapi.NumerAPI().get_rankings(1)
            [{'username': '******',
              'usdEarned': Decimal('16347.12'),
              'reputation': 0.5121,
              'nmrStaked': Decimal('250.000000000000000000'),
              'nmrEarned': Decimal('16061.37'),
              'nmrBurned': Decimal('295.400000000000000000')]
        """
        query = '''
            query($limit: Int!
                  $offset: Int!) {
              globalLeaderboard(limit: $limit
                                offset: $offset) {
                username
                nmrBurned
                nmrEarned
                nmrStaked
                reputation
                usdEarned
              }
            }
        '''
        arguments = {'limit': limit, 'offset': offset}
        data = self.raw_query(query, arguments)['data']['globalLeaderboard']
        for item in data:
            for p in ["nmrBurned", "nmrEarned", "nmrStaked", "usdEarned"]:
                utils.replace(item, p, utils.parse_float_string)
        return data
Exemple #18
0
    def public_user_profile(self, username: str) -> Dict:
        """Fetch the public Numerai Signals profile of a user.

        Args:
            username (str)

        Returns:
            dict: user profile including the following fields:

                * username (`str`)
                * startDate (`datetime`)
                * id (`string`)
                * rank (`int`)
                * bio (`str`)
                * sharpe (`float`)
                * totalStake (`decimal.Decimal`)

        Example:
            >>> api = SignalsAPI()
            >>> api.public_user_profile("floury_kerril_moodle")
            {'bio': None,
             'id': '635db2a4-bdc6-4e5d-b515-f5120392c8c9',
             'rank': 1,
             'sharpe': 2.35,
             'startDate': datetime.datetime(2019, 3, 26, 0, 43),
             'username': '******',
             'totalStake': Decimal('14.630994874320760131')}

        """
        query = """
          query($username: String!) {
            signalsUserProfile(username: $username) {
              rank
              id
              startDate
              username
              bio
              sharpe
              totalStake
            }
          }
        """
        arguments = {'username': username}
        data = self.raw_query(query, arguments)['data']['signalsUserProfile']
        # convert strings to python objects
        utils.replace(data, "startDate", utils.parse_datetime_string)
        utils.replace(data, "totalStake", utils.parse_float_string)
        return data
Exemple #19
0
 def get_transactions(self):
     """all deposits and withdrawals"""
     query = """
       query {
         user {
           nmrDeposits {
             from
             id
             posted
             status
             to
             txHash
             value
           }
           nmrWithdrawals {
             from
             id
             posted
             status
             to
             txHash
             value
           }
           usdWithdrawals {
             ethAmount
             confirmTime
             from
             posted
             sendTime
             status
             to
             txHash
             usdAmount
           }
         }
       }
     """
     txs = self.raw_query(query, authorization=True)['data']['user']
     # convert strings to python objects
     for t in txs['usdWithdrawals']:
         utils.replace(t, "confirmTime", utils.parse_datetime_string)
         utils.replace(t, "sendTime", utils.parse_datetime_string)
         utils.replace(t, "usdAmount", utils.parse_float_string)
     for t in txs["nmrWithdrawals"]:
         utils.replace(t, "value", utils.parse_float_string)
     for t in txs["nmrDeposits"]:
         utils.replace(t, "value", utils.parse_float_string)
     return txs
Exemple #20
0
    def get_leaderboard(self, round_num=0):
        """ retrieves the leaderboard for the given round

        round_num: The round you are interested in, defaults to current round.
        """
        self.logger.info("getting leaderboard for round {}".format(round_num))
        query = '''
            query($number: Int!) {
              rounds(number: $number) {
                leaderboard {
                  consistency
                  concordance {
                    pending
                    value
                  }
                  originality {
                    pending
                    value
                  }
                  liveLogloss
                  submissionId
                  username
                  validationLogloss
                  paymentGeneral {
                    nmrAmount
                    usdAmount
                  }
                  paymentStaking {
                    nmrAmount
                    usdAmount
                  }
                  totalPayments {
                    nmrAmount
                    usdAmount
                  }
                }
              }
            }
        '''
        arguments = {'number': round_num}
        result = self.raw_query(query, arguments)
        leaderboard = result['data']['rounds'][0]['leaderboard']
        # parse to correct data types
        for item in leaderboard:
            for p in ["totalPayments", "paymentGeneral", "paymentStaking"]:
                utils.replace(item[p], "nmrAmount", utils.parse_float_string)
                utils.replace(item[p], "usdAmount", utils.parse_float_string)
        return leaderboard
Exemple #21
0
    def round_details(self, round_num: int) -> List[Dict]:
        """Fetch all correlation scores of a round.

        Args:
            round_num (int)

        Returns:
            list of dicts: list containing scores for each user

            For each entry in the list, there is a dict with the following
            content:

                * date (`datetime`)
                * correlation (`float`)
                * username (`str`)

        Example:
            >>> api = NumerAPI()
            >>> api.round_details(180)
            [{'username': '******',
              'date': datetime.datetime(2019, 11, 15, 0, 0),
              'correlation': 0.02116131087},
              ...
            ]
        """
        query = """
          query($roundNumber: Int!) {
            v2RoundDetails(roundNumber: $roundNumber) {
              userPerformances {
                date
                correlation
                username
              }
            }
          }
        """
        arguments = {'roundNumber': round_num}
        data = self.raw_query(query, arguments)['data']['v2RoundDetails']
        performances = data['userPerformances']
        # convert strings to python objects
        for perf in performances:
            utils.replace(perf, "date", utils.parse_datetime_string)
        return performances
Exemple #22
0
    def public_user_profile(self, username: str) -> Dict:
        """Fetch the public profile of a user.

        Args:
            username (str)

        Returns:
            dict: user profile including the following fields:
                * username (`str`)
                * startDate (`datetime`)
                * id (`string`)
                * bio (`str`)
                * nmrStaked (`float`)

        Example:
            >>> api = NumerAPI()
            >>> api.public_user_profile("integration_test")
            {'bio': 'The official example model. Submits example predictions.',
             'id': '59de8728-38e5-45bd-a3d5-9d4ad649dd3f',
             'startDate': datetime.datetime(
                2018, 6, 6, 17, 33, 21, tzinfo=tzutc()),
             'nmrStaked': '57.582371875005243780',
             'username': '******'}

        """
        query = """
          query($model_name: String!) {
            v3UserProfile(model_name: $model_name) {
              id
              startDate
              username
              bio
              nmrStaked
            }
          }
        """
        arguments = {'model_name': username}
        data = self.raw_query(query, arguments)['data']['v3UserProfile']
        # convert strings to python objects
        utils.replace(data, "startDate", utils.parse_datetime_string)
        return data
Exemple #23
0
 def get_user(self):
     """get all information about you! """
     query = """
       query {
         user {
           username
           banned
           assignedEthAddress
           availableNmr
           availableUsd
           email
           id
           mfaEnabled
           status
           insertedAt
           apiTokens {
             name
             public_id
             scopes
           }
         }
       }
     """
     data = self.raw_query(query, authorization=True)['data']['user']
     # convert strings to python objects
     utils.replace(data, "insertedAt", utils.parse_datetime_string)
     utils.replace(data, "availableUsd", utils.parse_float_string)
     utils.replace(data, "availableNmr", utils.parse_float_string)
     return data
Exemple #24
0
    def get_competitions(self):
        """ get information about rounds """
        self.logger.info("getting rounds...")

        query = '''
            query {
              rounds {
                number
                resolveTime
                datasetId
                openTime
                resolvedGeneral
                resolvedStaking
              }
            }
        '''
        result = self.raw_query(query)
        rounds = result['data']['rounds']
        # convert datetime strings to datetime.datetime objects
        for r in rounds:
            utils.replace(r, "openTime", utils.parse_datetime_string)
            utils.replace(r, "resolveTime", utils.parse_datetime_string)
        return rounds
Exemple #25
0
    def get_staking_leaderboard(self, round_num=0):
        """ retrieves the leaderboard of the staking competition for the given
        round

        round_num: The round you are interested in, defaults to current round.
        """
        self.logger.info("getting stakes for round {}".format(round_num))
        query = '''
            query($number: Int!) {
              rounds(number: $number) {
                leaderboard {
                  consistency
                  liveLogloss
                  username
                  validationLogloss
                  stake {
                    insertedAt
                    soc
                    confidence
                    value
                    txHash
                  }
                }
              }
            }
        '''
        arguments = {'number': round_num}
        result = self.raw_query(query, arguments)
        stakes = result['data']['rounds'][0]['leaderboard']
        # filter those with actual stakes
        stakes = [item for item in stakes if item["stake"]["soc"] is not None]
        # convert strings to pyton objects
        for s in stakes:
            utils.replace(s["stake"], "insertedAt",
                          utils.parse_datetime_string)
            utils.replace(s["stake"], "confidence", utils.parse_float_string)
            utils.replace(s["stake"], "soc", utils.parse_float_string)
            utils.replace(s["stake"], "value", utils.parse_float_string)
        return stakes
Exemple #26
0
    def get_transactions(self, model_id: str = None) -> Dict:
        """Get all your deposits and withdrawals.

        Args:
            model_id (str): Target model UUID (required for accounts
                            with multiple models)

        Returns:
            dict: lists of your NMR and USD transactions

            The returned dict has the following structure:

                * nmrDeposits (`list`) contains items with fields:
                 * from (`str`)
                 * posted (`bool`)
                 * status (`str`)
                 * to (`str`)
                 * txHash (`str`)
                 * value (`decimal.Decimal`)
                 * insertedAt (`datetime`)
                * nmrWithdrawals"` (`list`) contains items with fields:
                 * from"` (`str`)
                 * posted"` (`bool`)
                 * status"` (`str`)
                 * to"` (`str`)
                 * txHash"` (`str`)
                 * value"` (`decimal.Decimal`)
                  * insertedAt (`datetime`)
                * usdWithdrawals"` (`list`) contains items with fields:
                 * confirmTime"` (`datetime` or `None`)
                 * ethAmount"` (`str`)
                 * from"` (`str`)
                 * posted"` (`bool`)
                 * sendTime"` (`datetime`)
                 * status"` (`str`)
                 * to (`str`)
                 * txHash (`str`)
                 * usdAmount (`decimal.Decimal`)

        Example:
            >>> api = NumerAPI(secret_key="..", public_id="..")
            >>> model = api.get_models()['uuazed']
            >>> api.get_transactions(model)
            {'nmrDeposits': [
                {'from': '0x54479..9ec897a',
                 'posted': True,
                 'status': 'confirmed',
                 'to': '0x0000000000000000000001',
                 'txHash': '0x52..e2056ab',
                 'value': Decimal('9.0'),
                 'insertedAt: datetime.datetime((2018, 2, 11, 17, 54, 2)},
                 .. ],
             'nmrWithdrawals': [
                {'from': '0x0000000000000000..002',
                 'posted': True,
                 'status': 'confirmed',
                 'to': '0x00000000000..001',
                 'txHash': '0x1278..266c',
                 'value': Decimal('2.0'),
                 'insertedAt: datetime.datetime((2018, 2, 11, 17, 54, 2)},},
                 .. ],
             'usdWithdrawals': [
                {'confirmTime': datetime.datetime(2018, 2, 11, 17, 54, 2),
                 'ethAmount': '0.295780674909307710',
                 'from': '0x11.....',
                 'posted': True,
                 'sendTime': datetime.datetime(2018, 2, 11, 17, 53, 25),
                 'status': 'confirmed',
                 'to': '0x81.....',
                 'txHash': '0x3c....',
                 'usdAmount': Decimal('10.07')},
                 ..]}
        """
        self.logger.warning(
            "get_transactions is DEPRECATED, use get_account_transactions")
        query = """
          query($modelId: String) {
            user(modelId: $modelId) {
              nmrDeposits {
                from
                posted
                status
                to
                txHash
                value
                insertedAt
              }
              nmrWithdrawals {
                from
                posted
                status
                to
                txHash
                value
                insertedAt
              }
              usdWithdrawals {
                ethAmount
                confirmTime
                from
                posted
                sendTime
                status
                to
                txHash
                usdAmount
              }
            }
          }
        """
        arguments = {'modelId': model_id}
        txs = self.raw_query(query, arguments,
                             authorization=True)['data']['user']
        # convert strings to python objects
        for t in txs['usdWithdrawals']:
            utils.replace(t, "confirmTime", utils.parse_datetime_string)
            utils.replace(t, "sendTime", utils.parse_datetime_string)
            utils.replace(t, "usdAmount", utils.parse_float_string)
        for t in txs["nmrWithdrawals"]:
            utils.replace(t, "value", utils.parse_float_string)
            utils.replace(t, "insertedAt", utils.parse_datetime_string)
        for t in txs["nmrDeposits"]:
            utils.replace(t, "value", utils.parse_float_string)
            utils.replace(t, "insertedAt", utils.parse_datetime_string)
        return txs
Exemple #27
0
    def get_account_transactions(self) -> Dict:
        """Get all your account deposits and withdrawals.

        Returns:
            dict: lists of your tournament wallet NMR transactions

            The returned dict has the following structure:

                * nmrDeposits (`list`) contains items with fields:
                 * from (`str`)
                 * posted (`bool`)
                 * status (`str`)
                 * to (`str`)
                 * txHash (`str`)
                 * value (`decimal.Decimal`)
                 * insertedAt (`datetime`)
                * nmrWithdrawals"` (`list`) contains items with fields:
                 * from"` (`str`)
                 * posted"` (`bool`)
                 * status"` (`str`)
                 * to"` (`str`)
                 * txHash"` (`str`)
                 * value"` (`decimal.Decimal`)
                  * insertedAt (`datetime`)

        Example:
            >>> api = NumerAPI(secret_key="..", public_id="..")
            >>> api.get_account_transactions()
            {'nmrDeposits': [
                {'from': '0x54479..9ec897a',
                 'posted': True,
                 'status': 'confirmed',
                 'to': '0x0000000000000000000001',
                 'txHash': '0x52..e2056ab',
                 'value': Decimal('9.0'),
                 'insertedAt: datetime.datetime((2018, 2, 11, 17, 54, 2)},
                 .. ],
             'nmrWithdrawals': [
                {'from': '0x0000000000000000..002',
                 'posted': True,
                 'status': 'confirmed',
                 'to': '0x00000000000..001',
                 'txHash': '0x1278..266c',
                 'value': Decimal('2.0'),
                 'insertedAt: datetime.datetime((2018, 2, 11, 17, 54, 2)},},
                 .. ]}
        """
        query = """
          query {
            account {
              nmrDeposits {
                from
                posted
                status
                to
                txHash
                value
                insertedAt
              }
              nmrWithdrawals {
                from
                posted
                status
                to
                txHash
                value
                insertedAt
              }
            }
          }
        """
        txs = self.raw_query(query, authorization=True)['data']['account']
        # convert strings to python objects
        for t in txs["nmrWithdrawals"]:
            utils.replace(t, "value", utils.parse_float_string)
            utils.replace(t, "insertedAt", utils.parse_datetime_string)
        for t in txs["nmrDeposits"]:
            utils.replace(t, "value", utils.parse_float_string)
            utils.replace(t, "insertedAt", utils.parse_datetime_string)
        return txs
Exemple #28
0
    def get_account(self) -> Dict:
        """Get all information about your account!

        Returns:
            dict: user information including the following fields:

                * assignedEthAddress (`str`)
                * availableNmr (`decimal.Decimal`)
                * availableUsd (`decimal.Decimal`)
                * email (`str`)
                * id (`str`)
                * insertedAt (`datetime`)
                * mfaEnabled (`bool`)
                * status (`str`)
                * username (`str`)
                * apiTokens (`list`) each with the following fields:
                 * name (`str`)
                 * public_id (`str`)
                 * scopes (`list of str`)
                * models
                  * username
                  * id
                  * submissions
                  * v2Stake
                   * status (`str`)
                   * txHash (`str`)

        Example:
            >>> api = NumerAPI(secret_key="..", public_id="..")
            >>> api.get_account()
            {'apiTokens': [
                    {'name': 'tokenname',
                     'public_id': 'BLABLA',
                     'scopes': ['upload_submission', 'stake', ..]
                     }, ..],
             'assignedEthAddress': '0x0000000000000000000000000001',
             'availableNmr': Decimal('99.01'),
             'email': '*****@*****.**',
             'id': '1234-ABC..',
             'insertedAt': datetime.datetime(2018, 1, 1, 2, 16, 48),
             'mfaEnabled': False,
             'status': 'VERIFIED',
             'username': '******',
             }
        """
        query = """
          query {
            account {
              username
              walletAddress
              availableNmr
              email
              id
              mfaEnabled
              status
              insertedAt
              models {
                id
                name
                submissions {
                  id
                  filename
                }
                v2Stake {
                  status
                  txHash
                }
              }
              apiTokens {
                name
                public_id
                scopes
              }
            }
          }
        """
        data = self.raw_query(query, authorization=True)['data']['account']
        # convert strings to python objects
        utils.replace(data, "insertedAt", utils.parse_datetime_string)
        utils.replace(data, "availableNmr", utils.parse_float_string)
        return data
Exemple #29
0
    def get_transactions(self):
        """Get all your deposits and withdrawals.

        Returns:
            dict: lists of your NMR and USD transactions

            The returned dict has the following structure:

                * nmrDeposits (`list`) contains items with fields:
                 * from (`str`)
                 * posted (`bool`)
                 * status (`str`)
                 * to (`str`)
                 * txHash (`str`)
                 * value (`decimal.Decimal`)
                * nmrWithdrawals"` (`list`) contains items with fields:
                 * from"` (`str`)
                 * posted"` (`bool`)
                 * status"` (`str`)
                 * to"` (`str`)
                 * txHash"` (`str`)
                 * value"` (`decimal.Decimal`)
                * usdWithdrawals"` (`list`) contains items with fields:
                 * confirmTime"` (`datetime` or `None`)
                 * ethAmount"` (`str`)
                 * from"` (`str`)
                 * posted"` (`bool`)
                 * sendTime"` (`datetime`)
                 * status"` (`str`)
                 * to (`str`)
                 * txHash (`str`)
                 * usdAmount (`decimal.Decimal`)

        Example:
            >>> api = NumerAPI(secret_key="..", public_id="..")
            >>> api.get_transactions()
            {'nmrDeposits': [
                {'from': '0x54479..9ec897a',
                 'posted': True,
                 'status': 'confirmed',
                 'to': '0x0000000000000000000001',
                 'txHash': '0x52..e2056ab',
                 'value': Decimal('9.0')},
                 .. ],
             'nmrWithdrawals': [
                {'from': '0x0000000000000000..002',
                 'posted': True,
                 'status': 'confirmed',
                 'to': '0x00000000000..001',
                 'txHash': '0x1278..266c',
                 'value': Decimal('2.0')},
                 .. ],
             'usdWithdrawals': [
                {'confirmTime': datetime.datetime(2018, 2, 11, 17, 54, 2, 785430, tzinfo=tzutc()),
                 'ethAmount': '0.295780674909307710',
                 'from': '0x11.....',
                 'posted': True,
                 'sendTime': datetime.datetime(2018, 2, 11, 17, 53, 25, 235035, tzinfo=tzutc()),
                 'status': 'confirmed',
                 'to': '0x81.....',
                 'txHash': '0x3c....',
                 'usdAmount': Decimal('10.07')},
                 ..]}
        """
        query = """
          query {
            user {
              nmrDeposits {
                from
                posted
                status
                to
                txHash
                value
              }
              nmrWithdrawals {
                from
                posted
                status
                to
                txHash
                value
              }
              usdWithdrawals {
                ethAmount
                confirmTime
                from
                posted
                sendTime
                status
                to
                txHash
                usdAmount
              }
            }
          }
        """
        txs = self.raw_query(query, authorization=True)['data']['user']
        # convert strings to python objects
        for t in txs['usdWithdrawals']:
            utils.replace(t, "confirmTime", utils.parse_datetime_string)
            utils.replace(t, "sendTime", utils.parse_datetime_string)
            utils.replace(t, "usdAmount", utils.parse_float_string)
        for t in txs["nmrWithdrawals"]:
            utils.replace(t, "value", utils.parse_float_string)
        for t in txs["nmrDeposits"]:
            utils.replace(t, "value", utils.parse_float_string)
        return txs
Exemple #30
0
    def get_user_activities(self, username, tournament=1):
        """Get user activities (works for all users!).

        Args:
            username (str): name of the user
            tournament (int): ID of the tournament (optional, defaults to 1)

        Returns:
            list: list of user activities (`dict`)

            Each activity in the list as the following structure:

                * resolved (`bool`)
                * roundNumber (`int`)
                * tournament (`int`)
                * submission (`dict`)
                 * concordance (`bool`)
                 * consistency (`float`)
                 * date (`datetime`)
                 * liveLogloss (`float`)
                 * originality (`bool`)
                 * validationLogloss (`float`)
                * stake (`dict`)
                 * confidence (`decimal.Decimal`)
                 * date (`datetime`)
                 * nmrEarned (`decimal.Decimal`)
                 * staked (`bool`)
                 * usdEarned (`decimal.Decimal`)
                 * burned (`bool`)

        Example:
            >>> NumerAPI().get_user_activities("slyfox", 5)
            [{'tournament': 5,
              'submission': {'validationLogloss': 0.6928141372700635,
               'originality': True,
               'liveLogloss': None,
               'date': datetime.datetime(2018, 7, 14, 17, 5, 27, 206042, tzinfo=tzutc()),
               'consistency': 83.33333333333334,
               'concordance': True},
              'stake': {'value': Decimal('0.10'),
               'usdEarned': None,
               'staked': True,
               'nmrEarned': None,
               'date': datetime.datetime(2018, 7, 14, 17, 7, 7, 877845, tzinfo=tzutc()),
               'confidence': Decimal('0.100000000000000000')},
               'burned': False
              'roundNumber': 116,
              'resolved': False},
             {'tournament': 5,
              'submission': {'validationLogloss': 0.6928141372700635,

               ...

               ]

        """
        query = '''
            query($tournament: Int!
                  $username: String!) {
              userActivities(tournament: $tournament
                     username: $username) {
                resolved
                roundNumber
                tournament
                submission {
                    concordance
                    consistency
                    date
                    liveLogloss
                    originality
                    validationLogloss
                }
                stake {
                    confidence
                    date
                    nmrEarned
                    staked
                    usdEarned
                    value
                    burned
                }
              }
            }
        '''
        arguments = {'tournament': tournament, 'username': username}
        data = self.raw_query(query, arguments)['data']['userActivities']
        # filter rounds with no activity
        data = [item for item in data
                if item['submission']['date'] is not None]
        for item in data:
            # remove stakes with all values set to None
            if item['stake']['date'] is None:
                del item['stake']
            # parse
            else:
                utils.replace(item['stake'], "date",
                              utils.parse_datetime_string)
                for col in ['confidence', 'value', 'nmrEarned', 'usdEarned']:
                    utils.replace(item['stake'], col, utils.parse_float_string)
        # parse
        for item in data:
            utils.replace(item['submission'], "date",
                          utils.parse_datetime_string)
        return data