class InstrumentSchema(BaseSchema): """The Schema for Instrument objects.""" __model__ = Instrument # symbol query returns a paginator but we only want the first __first__ = "results" bloomberg_unique = fields.Str() country = fields.Str() day_trade_ratio = fields.Float() default_collar_fraction = fields.Float() fractional_tradability = fields.Str() # TODO: determine possible values fundamentals = fields.URL() id = fields.UUID() list_date = fields.NaiveDateTime(format="%Y-%m-%d", allow_none=True) maintenance_ratio = fields.Float() margin_initial_ratio = fields.Float() market = fields.URL() # This value can be null: http://www.finra.org/industry/tick-size-pilot-program min_tick_size = fields.Float(allow_none=True) name = fields.Str() quote = fields.URL() rhs_tradability = fields.Str() # TODO: determine possible values simple_name = fields.Str(allow_none=True) splits = fields.URL() state = fields.Str() # TODO: determine possible values symbol = fields.Str() tradability = fields.Str() tradable_chain_id = fields.Str( allow_none=True) # TODO: determine possible values tradeable = fields.Boolean() # looks like they're mixing UK and US english type = fields.Str() # TODO: determine possible values url = fields.URL()
class PortfolioSchema(BaseSchema): """Robinhood portfolio schema data loader.""" __model__ = Portfolio __first__ = "results" # returns a paginator but we only need the first url = fields.URL() account = fields.URL() start_date = fields.NaiveDateTime() market_value = fields.Float() equity = fields.Float() extended_hours_market_value = fields.Float() extended_hours_equity = fields.Float() extended_hours_portfolio_equity = fields.Float() last_core_market_value = fields.Float() last_core_equity = fields.Float() last_core_portfolio_equity = fields.Float() excess_margin = fields.Float() excess_maintenance = fields.Float() excess_margin_with_uncleared_deposits = fields.Float() portfolio_equity_previous_close = fields.Float() adjusted_equity_previous_close = fields.Float() adjusted_portfolio_equity_previous_close = fields.Float() withdrawable_amount = fields.Float() unwithdrawable_deposits = fields.Float() unwithdrawable_grants = fields.Float()
class GiftCardSerializer(Schema): id = fields.UUID(dump_only=True) redeem_code = fields.Str() date_of_issue = fields.Date() pin = fields.Int() is_used = fields.Bool(dump_only=True) source = fields.Str() denomination = fields.Int() timestamp = fields.NaiveDateTime(dump_only=True) date_of_expiry = fields.Date(dump_only=True)
class ItemSchema(SQLAlchemyAutoSchema): class Meta: model = Item include_fk = True sqla_session = db.session # Override these fields so we can tell Marshmallow more about # time format and time zone. `NaiveDateTime` means we're not # attempting to store a time zone. The `format` argument means # we expect JSON strings in the format Flask emits by default. # The `timezone` argument prevents off-by-a-few-hours # errors we were otherwise getting -- I'm unclear on why it needs # to be specified, but empirically it works. (lbv) start_date = fields.NaiveDateTime(format="rfc", timezone=GMT, allow_none=True) due_date = fields.NaiveDateTime(format="rfc", timezone=GMT, allow_none=True) end_date = fields.NaiveDateTime(format="rfc", timezone=GMT, allow_none=True)
class IOURequest: """A HTTP request to IOUResource""" sender: Address = field(metadata={"marshmallow_field": ChecksumAddress(required=True)}) receiver: Address = field(metadata={"marshmallow_field": ChecksumAddress(required=True)}) timestamp: datetime = field(metadata={"marshmallow_field": fields.NaiveDateTime()}) timestamp_str: str = field(metadata=dict(data_key="timestamp", load_only=True)) signature: Signature = field(metadata={"marshmallow_field": HexedBytes()}) Schema: ClassVar[Type[marshmallow.Schema]] def is_signature_valid(self) -> bool: packed_data = self.sender + self.receiver + Web3.toBytes(text=self.timestamp_str) try: recovered_address = recover(packed_data, self.signature) except InvalidSignature: return False return is_same_address(recovered_address, self.sender)
class PortfolioSchema(BaseSchema): """Robinhood portfolio schema data loader.""" __model__ = Portfolio url = fields.URL() account = fields.URL() start_date = fields.NaiveDateTime() market_value = fields.Float() equity = fields.Float() extended_hours_market_value = fields.Float() extended_hours_equity = fields.Float() extended_hours_portfolio_equity = fields.Float() last_core_market_value = fields.Float() last_core_equity = fields.Float() last_core_portfolio_equity = fields.Float() excess_margin = fields.Float() excess_maintenance = fields.Float() excess_margin_with_uncleared_deposits = fields.Float() portfolio_equity_previous_close = fields.Float() adjusted_equity_previous_close = fields.Float() adjusted_portfolio_equity_previous_close = fields.Float() withdrawable_amount = fields.Float() unwithdrawable_deposits = fields.Float() unwithdrawable_grants = fields.Float() @post_load def make_object(self, data: JSON, **kwargs: Any) -> Portfolio: """Build model for the Portfolio class. Args: data: The JSON diction to use to build the Portfolio. **kwargs: Unused but required to match signature of `Schema.make_object` Returns: An instance of the Portfolio class. """ data = data.get("results", [{}])[0] return self.__model__(**data)
class UserSchema(Schema): name = fields.String(required=True, validate=validate.Length(min=1, max=255)) age = fields.Float() created = fields.DateTime() created_formatted = fields.DateTime(format="%Y-%m-%d", attribute="created", dump_only=True) created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True) updated_naive = fields.NaiveDateTime(attribute="updated", dump_only=True) updated = fields.DateTime() species = fields.String(attribute="SPECIES") id = fields.String(default="no-id") homepage = fields.Url() email = fields.Email() balance = fields.Decimal() registered = fields.Boolean() hair_colors = fields.List(fields.Raw) sex_choices = fields.List(fields.Raw) finger_count = fields.Integer() uid = fields.UUID() time_registered = fields.Time() birthdate = fields.Date() since_created = fields.TimeDelta() sex = fields.Str(validate=validate.OneOf( choices=["male", "female", "non_binary", "other"], labels=["Male", "Female", "Non-binary/fluid", "Other"], )) various_data = fields.Dict() addresses = fields.Nested(Address, many=True, validate=validate.Length(min=1, max=3)) github = fields.Nested(GithubProfile) const = fields.String(validate=validate.Length(equal=50)) is_user = fields.Boolean(validate=validate.Equal(True))
birthdate = fields.Date() since_created = fields.TimeDelta() sex = fields.Str(validate=validate.OneOf( choices=["male", "female", "non_binary", "other"], labels=["Male", "Female", "Non-binary/fluid", "Other"], )) various_data = fields.Dict() addresses = fields.Nested(Address, many=True, validate=validate.Length(min=1, max=3)) github = fields.Nested(GithubProfile) const = fields.String(validate=validate.Length(equal=50)) if MARSHMALLOW_3: UserSchema.updated_naive = fields.NaiveDateTime(attribute="updated", dump_only=True) def _validate_schema(schema): """ raises jsonschema.exceptions.SchemaError """ Draft7Validator.check_schema(schema) def validate_and_dump(schema): json_schema = JSONSchema() dumped = json_schema.dump(schema) data = dot_data_backwards_compatible(dumped) _validate_schema(data) # ensure last version