How to use the otree.api.models function in otree

To help you get started, we’ve selected a few otree examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github oTree-org / oTree / public_goods / models.py View on Github external
if contributions:
            return dict(
                avg_contribution=sum(contributions) / len(contributions),
                min_contribution=min(contributions),
                max_contribution=max(contributions),
            )
        else:
            return dict(
                avg_contribution='(no data)',
                min_contribution='(no data)',
                max_contribution='(no data)',
            )


class Group(BaseGroup):
    total_contribution = models.CurrencyField()

    individual_share = models.CurrencyField()

    def set_payoffs(self):
        self.total_contribution = sum([p.contribution for p in self.get_players()])
        self.individual_share = (
            self.total_contribution * Constants.multiplier / Constants.players_per_group
        )
        for p in self.get_players():
            p.payoff = (Constants.endowment - p.contribution) + self.individual_share


class Player(BasePlayer):
    contribution = models.CurrencyField(
        min=0, max=Constants.endowment, doc="""The amount contributed by the player"""
    )
github Leeps-Lab / high_frequency_trading / hft_bcs / _models.py View on Github external
total = sum(group_state.values())
        self.broadcast(
            client_messages.total_role(group_state)
        )
        if total != ppg:
            raise ValueError('total: %d, ppg: %d' % (total, ppg))

    def loggy(self):
        log_events.convert()
        log_events.dump()


class Player(BasePlayer):

    # basic state variables
    role = models.StringField(initial='OUT')
    speed = models.BooleanField(initial=False)
    spread = models.IntegerField()
    channel = models.CharField(max_length=255)
    cost = models.IntegerField(initial=0)
    fp = models.IntegerField()
    endowment = models.IntegerField()
    prev_speed_update = models.BigIntegerField(initial=0)
    speed_on = models.IntegerField(initial=0)
    speed_unit_cost = models.IntegerField()
    max_spread = models.IntegerField()
    code = models.CharField(default=random_chars_8)
    log_file = models.StringField()
    design =  models.CharField()
    consent = models.BooleanField(initial=True)
    final_payoff = models.IntegerField()
    total_payoff = models.IntegerField()
github WZBSocialScienceCenter / otreeutils / otreeutils_example2 / models.py View on Github external
'Strongly agree'
)

likert_5point_field = generate_likert_field(likert_5_labels)


# define survey questions per page
# for each page define a page title and a list of questions
# the questions have a field name, a question text (input label), and a field type (model field class)
SURVEY_DEFINITIONS = (
    {
        'page_title': 'Survey Questions - Page 1 - Simple questions and inputs',
        'survey_fields': [
            ('q_age', {   # field name (which will also end up in your "Player" class and hence in your output data)
                'text': 'How old are you?',   # survey question
                'field': models.PositiveIntegerField(min=18, max=100),  # the same as in normal oTree model field definitions
            }),
            ('q_gender', {
                'text': 'Please tell us your gender.',
                'field': models.CharField(choices=GENDER_CHOICES),
            }),
        ]
    },
    {
        'page_title': 'Survey Questions - Page 2 - Likert 5-point scale',
        'survey_fields': [
            ('q_otree_surveys', {  # most of the time, you'd add a "help_text" for a Likert scale question. You can use HTML:
                'help_text': """
                    <p>Consider this quote:</p>
                    <blockquote>
                        "oTree is great to make surveys, too."
                    </blockquote>
github Leeps-Lab / high_frequency_trading / hft / models.py View on Github external
self.__class__._default_manager.filter(pk=self.pk).update(**json_fields)


class Group(BaseGroup):
    pass


class Player(BasePlayer):

    channel = models.CharField(max_length=255)
    consented = models.BooleanField(initial=False)
    exchange_host = models.CharField()
    exchange_port = models.IntegerField()
    # subsession_id = models.CharField()
    market_id = models.CharField()
    id_in_market = models.IntegerField()
    speed_unit_cost = models.IntegerField()
    net_worth = models.IntegerField()
    cash = models.IntegerField()
    cost = models.IntegerField()
    speed_cost = models.IntegerField()
    tax_paid = models.IntegerField()
    reference_price = models.IntegerField()
    inventory = models.IntegerField()
    bid = models.IntegerField()
    offer = models.IntegerField()
    staged_bid = models.IntegerField()
    staged_offer = models.IntegerField()
    implied_bid = models.IntegerField()
    implied_offer = models.IntegerField()
    best_bid = models.IntegerField()
    best_offer = models.IntegerField()
github Leeps-Lab / high_frequency_trading / hft / exogenous_event.py View on Github external
class CSVRowMixIn:
    
    @classmethod
    def from_csv_row(cls, csv_row:list, csv_headers:list, **kwargs):
        instance = cls.objects.create(**kwargs)
        for ix, fieldname in enumerate(csv_headers):
            fieldvalue = csv_row[ix]
            setattr(instance, fieldname, fieldvalue)
        return instance

class ExogenousOrderRecord(Model, CSVRowMixIn):

    submitted_file = ForeignKey(ExogenousEventFile, on_delete=models.CASCADE)
    arrival_time = models.FloatField()
    market_id_in_subsession = models.StringField()
    price = models.IntegerField()
    time_in_force = models.IntegerField()
    buy_sell_indicator = models.StringField()


class ExternalFeedRecord(Model, CSVRowMixIn):

    submitted_file = ForeignKey(ExogenousEventFile, on_delete=models.CASCADE)
    arrival_time = models.FloatField()
    market_id_in_subsession = models.StringField()
    e_best_bid = models.IntegerField()
    e_best_offer = models.IntegerField()
    e_signed_volume = models.FloatField()


def handle_exogenous_event_file(filename, filelike, record_cls, record_type):
    if None in (filename, filelike):
github WZBSocialScienceCenter / otree_custom_models / example_decisions / models.py View on Github external
for _ in range(Constants.num_decisions_per_round):
            decision = self.decision_set.create()    # create a new Decision object as part of the player's decision set
            decision.value = random.randint(1, 10)
            decision.save()   # important: save to DB!


class Decision(Model):   # our custom model inherits from Django's base class "Model"
    REASONS = (
        ('dont_know', "Don't know"),
        ('example_reason', "Example reason"),
        ('another_example_reason', "Another example reason"),
    )

    value = models.IntegerField()    # will be randomly generated
    player_decision = models.BooleanField()
    reason = models.CharField(choices=REASONS)

    player = ForeignKey(Player)    # creates 1:m relation -> this decision was made by a certain player

    def __str__(self):
        return 'decision #%d for player %d (participant %d) - value %d'\
               % (self.pk, self.player.pk, self.player.participant.id_in_session, self.value)
github Leeps-Lab / high_frequency_trading / hft_bcs / _models.py View on Github external
except Exception as e:
                    log.exception(e)
    else:
        for _, process_list in subprocesses.items():
            if process_list:
                for process in process_list:
                    try:
                        process.kill()
                    except Exception as e:
                        log.exception(e)




class Subsession(BaseSubsession):
    design = models.StringField()
    next_available_exchange = models.IntegerField()
    players_per_group = models.IntegerField()
    round_length = models.IntegerField()
    batch_length = models.IntegerField(initial=0)
    trade_ended = models.BooleanField(initial=False)
    code = models.CharField(default=random_chars_8)
    has_trial = models.BooleanField(initial=True)
    is_trial = models.BooleanField(initial=False)
    trial_length = models.IntegerField(initial=0)
    log_file = models.StringField()
    first_round = models.IntegerField(initial=1)
    last_round = models.IntegerField(initial=0)
    total_rounds = models.IntegerField(initial=0)
    restore_from = models.CharField()
    restore = models.BooleanField(initial=False)
    lambda_i = models.FloatField()
github oTree-org / oTree / guess_two_thirds / models.py View on Github external
players_per_group = 3
    num_rounds = 3
    name_in_url = 'guess_two_thirds'

    jackpot = Currency(100)
    guess_max = 100

    instructions_template = 'guess_two_thirds/instructions.html'


class Subsession(BaseSubsession):
    pass


class Group(BaseGroup):
    two_thirds_avg = models.FloatField()
    best_guess = models.IntegerField()
    num_winners = models.IntegerField()

    def set_payoffs(self):
        players = self.get_players()
        guesses = [p.guess for p in players]
        two_thirds_avg = (2 / 3) * sum(guesses) / len(players)
        self.two_thirds_avg = round(two_thirds_avg, 2)

        self.best_guess = min(
            guesses, key=lambda guess: abs(guess - self.two_thirds_avg)
        )

        winners = [p for p in players if p.guess == self.best_guess]
        self.num_winners = len(winners)