def convert_to_equity(latest_price, config): # convert rsus into date/value pairs rsus = list(map( lambda rsu: Equity.from_rsu( current_price=latest_price, quantity=rsu["qty"], vest_date=rsu["vest_date"], tax_rate=config["tax_rate"] ), config["rsus"] )) # convert options into date/value pairs options = list(map( lambda option: Equity.from_option( current_price=latest_price, quantity=option["qty"], vest_date=option["vest_date"], strike_price=option["price"], tax_rate=config["tax_rate"] ), config["options"] )) return EquityGroup(rsus + options)
def main(): securities = [ Security(30, "$", RiskLevel.LOW, Trend.UP, 0, "Ukraine", "I"), Equity(20, "$", RiskLevel.MEDIUM, Trend.DOWN, 0, "Russia", "I", "Roshen", 0.5), Debt(10, "$", RiskLevel.HIGH, Trend.UP, 0, "Belarus", "I"), Derivative(0, "$", RiskLevel.DANGER, Trend.UP, 0, "Moldova", "I", "house"), Security(0, "$", RiskLevel.LOW, Trend.DOWN, 10, "Ukraine", "I") ] manager = SecuritiesManager(*securities) filteredList = manager.filterByPrice(0) for s in filteredList: print(s) print() sortedList = SecuritiesManager.sortByPriceAscending(securities) for s in sortedList: print(s) print() sortedFilteredList = SecuritiesManager.sortByDurationDescending( filteredList) for s in sortedFilteredList: print(s)
def main(): """ Stock_price Options_price Call_strike_price Dividends """ # option = { # 'price': 4.41, # 'type': 'call', # 'strike': 28.38, # 'dividends': .8, # 'stock_price': 25 # } # print(option) # bes = option.stock_price - option.price - option.dividends # print("break even stock price", bes) benchmark = Equity('VOO') print(benchmark.benchmark) e = Equity('IBM', benchmark) print(e.beta())
def get_tickdata(ls_symbols, ldt_timestamps): c_dataobj = da.DataAccess('Yahoo', cachestalltime=0) ls_keys = ['open', 'high', 'low', 'close', 'volume', 'actual_close'] ldf_data = c_dataobj.get_data(ldt_timestamps, ls_symbols, ls_keys) d_data = dict(zip(ls_symbols, ldf_data)) for s_key in ls_symbols: d_data[s_key] = d_data[s_key].fillna(method='ffill') d_data[s_key] = d_data[s_key].fillna(method='bfill') d_data[s_key] = d_data[s_key].fillna(1.0) stocks = dict() for s in ls_symbols: stocks[s] = Equity(index=ldt_timestamps, data=d_data[s]) stocks[s].nml_close() return stocks
def init(self, secret_hash, recipient_public, sender_public, sequence=bytom["sequence"]): """ Initialize bytom Hash Time Lock Contract (HTLC). :param secret_hash: secret sha-256 hash. :type secret_hash: str :param recipient_public: bytom recipient public key. :type recipient_public: str :param sender_public: bytom sender public key. :type sender_public: str :param sequence: bytom sequence number of expiration block, defaults to bytom config sequence (15). :type sequence: int :returns: HTLC -- bytom Hash Time Lock Contract (HTLC) instance. >>> from shuttle.providers.bytom.htlc import HTLC >>> htlc = HTLC(network="testnet") >>> htlc.init(secret_hash, recipient_public_key, sender_public_key, 100) <shuttle.providers.bytom.htlc.HTLC object at 0x0409DAF0> """ # Checking parameters if not isinstance(secret_hash, str): raise TypeError("secret hash must be string format") if len(secret_hash) != 64: raise ValueError("invalid secret hash, length must be 64.") if not isinstance(recipient_public, str): raise TypeError("recipient public key must be string format") if len(recipient_public) != 64: raise ValueError("invalid recipient public key, length must be 64.") if not isinstance(sender_public, str): raise TypeError("sender public key must be string format") if len(sender_public) != 64: raise ValueError("invalid sender public key, length must be 64.") if not isinstance(sequence, int): raise TypeError("sequence must be integer format") # HTLC agreements HTLC_ARGEEMENTS = [ secret_hash, # secret_hash: Hash recipient_public, # recipient: PublicKey sender_public, # sender: PublicKey sequence, # sequence: Integer ] # Compiling HTLC contract self.equity = Equity(bytom[self.network]["bytom"])\ .compile_source(HTLC_SCRIPT, HTLC_ARGEEMENTS) return self
def _compile(url, equity_source, name, args=None, save=None): # Init Equity equity = Equity(url=url) # Compile equity source equity.compile_source(equity_source, args) if save: _, save_name = equity.save(dir_path=save) else: _, save_name = equity.save() print("Compiling is Done! %s" % save_name)
def init(self, secret_hash, recipient_public, sender_public, sequence=bytom["sequence"], use_script=False): """ Initialize Bytom Hash Time Lock Contract (HTLC). :param secret_hash: secret sha-256 hash. :type secret_hash: str :param recipient_public: Bytom recipient public key. :type recipient_public: str :param sender_public: Bytom sender public key. :type sender_public: str :param sequence: Bytom sequence number(expiration block), defaults to Bytom config sequence. :type sequence: int :param use_script: Initialize HTLC by using script, default to False. :type use_script: bool :returns: HTLC -- Bytom Hash Time Lock Contract (HTLC) instance. >>> from shuttle.providers.bytom.htlc import HTLC >>> from shuttle.utils import sha256 >>> htlc = HTLC(network="mainnet") >>> htlc.init(secret_hash=sha256("Hello Meheret!".encode()).hex(), recipient_public="91ff7f525ff40874c4f47f0cab42e46e3bf53adad59adef9558ad1b6448f22e2", sender_public="d4351a0e743e6f10b35122ac13c0bb1445423a641754182d53f0677cc3d7ea01", sequence=1000, use_script=False) <shuttle.providers.bytom.htlc.HTLC object at 0x0409DAF0> """ # Checking parameters if not isinstance(secret_hash, str): raise TypeError("secret hash must be string format") if len(secret_hash) != 64: raise ValueError("invalid secret hash, length must be 64") if not isinstance(recipient_public, str): raise TypeError("recipient public key must be string format") if len(recipient_public) != 64: raise ValueError("invalid recipient public key, length must be 64") if not isinstance(sender_public, str): raise TypeError("sender public key must be string format") if len(sender_public) != 64: raise ValueError("invalid sender public key, length must be 64") if not isinstance(sequence, int): raise TypeError("sequence must be integer format") if use_script: # HTLC agreements HTLC_AGREEMENTS = [ secret_hash, # secret_hash: Hash recipient_public, # recipient: PublicKey sender_public, # sender: PublicKey sequence, # sequence: Integer ] # Compiling HTLC by script self.equity = Equity(bytom[self.network]["bytom"])\ .compile_source(HTLC_SCRIPT, HTLC_AGREEMENTS) else: # Compiling HTLC by script binary builder = Builder() builder.add_int(sequence) # sequence: Integer builder.add_bytes( bytes.fromhex(sender_public)) # sender: PublicKey builder.add_bytes( bytes.fromhex(recipient_public)) # recipient: PublicKey builder.add_bytes(bytes.fromhex(secret_hash)) # secret_hash: Hash builder.add_op(OP_DEPTH) builder.add_bytes(bytes.fromhex(HTLC_SCRIPT_BINARY)) builder.add_op(OP_FALSE) builder.add_op(OP_CHECKPREDICATE) SEQUENCE = bytes(c_int64(sequence)).rstrip(b'\x00').hex() self.equity = dict( program=builder.hex_digest(), opcodes=f"0x{SEQUENCE} 0x{sender_public} 0x{recipient_public} " f"0x{secret_hash} DEPTH 0x{HTLC_SCRIPT_BINARY} FALSE CHECKPREDICATE" ) return self
def build_htlc(self, secret_hash: str, recipient_public_key: str, sender_public_key: str, endblock: int, use_script: bool = False) -> "HTLC": """ Build Bytom Hash Time Lock Contract (HTLC). :param secret_hash: secret sha-256 hash. :type secret_hash: str :param recipient_public_key: Bytom recipient public key. :type recipient_public_key: str :param sender_public_key: Bytom sender public key. :type sender_public_key: str :param endblock: Bytom expiration block height. :type endblock: int :param use_script: Initialize HTLC by using script, default to ``False``. :type use_script: bool :returns: HTLC -- Bytom Hash Time Lock Contract (HTLC) instance. >>> from swap.providers.bytom.htlc import HTLC >>> from swap.providers.bytom.rpc import get_current_block_height >>> from swap.utils import sha256 >>> htlc: HTLC = HTLC(network="mainnet") >>> htlc.build_htlc(secret_hash=sha256("Hello Meheret!"), recipient_public_key="3e0a377ae4afa031d4551599d9bb7d5b27f4736d77f78cac4d476f0ffba5ae3e", sender_public_key="fe6b3fd4458291b19605d92837ae1060cc0237e68022b2eb9faf01a118226212", endblock=get_current_block_height(plus=100), use_script=False) <swap.providers.bytom.htlc.HTLC object at 0x0409DAF0> """ # Checking parameters instances if len(secret_hash) != 64: raise ValueError("Invalid secret hash, length must be 64") if len(recipient_public_key) != 64: raise ValueError( "Invalid Bytom recipient public key, length must be 64") if len(sender_public_key) != 64: raise ValueError( "Invalid Bytom sender public key, length must be 64") if use_script: # Get current working directory path (like linux or unix path). cwd: str = PurePosixPath( os.path.dirname(os.path.realpath(__file__))).__str__().replace( "\\", "/") with open(f"{cwd}/contracts/htlc.equity", "r", encoding="utf-8") as htlc_equity_file: htlc_script: str = "".join(htlc_equity_file.readlines()[-14:]) htlc_equity_file.close() htlc_agreement: List[str, int] = [ secret_hash, recipient_public_key, sender_public_key, endblock ] # Compile HTLC by script self._script = Equity(config[self._network]["bytom-core"])\ .compile_source(htlc_script, htlc_agreement) else: # Compile HTLC by script binary builder: Builder = Builder() builder.add_int(endblock) builder.add_bytes(bytes.fromhex(sender_public_key)) builder.add_bytes(bytes.fromhex(recipient_public_key)) builder.add_bytes(bytes.fromhex(secret_hash)) builder.add_op(OP_DEPTH) builder.add_bytes(bytes.fromhex(config["htlc_script_binary"])) builder.add_op(OP_FALSE) builder.add_op(OP_CHECKPREDICATE) sequence: str = bytes(c_int64(endblock)).rstrip(b'\x00').hex() self._script = dict( program=builder.hex_digest(), opcodes= f"0x{sequence} 0x{sender_public_key} 0x{recipient_public_key} " f"0x{secret_hash} DEPTH 0x{config['htlc_script_binary']} FALSE CHECKPREDICATE" ) self.agreements = { "secret_hash": secret_hash, "recipient": { "public_key": recipient_public_key, "address": get_address( program=get_program(public_key=recipient_public_key), network=self._network, vapor=False) }, "sender": { "public_key": sender_public_key, "address": get_address(program=get_program(public_key=sender_public_key), network=self._network, vapor=False) }, "endblock": endblock } return self
def build_htlc(self, secret_hash: str, recipient_public_key: str, sender_public_key: str, sequence: int = config["sequence"], use_script: bool = False) -> "HTLC": """ Build Vapor Hash Time Lock Contract (HTLC). :param secret_hash: secret sha-256 hash. :type secret_hash: str :param recipient_public_key: Vapor recipient public key. :type recipient_public_key: str :param sender_public_key: Vapor sender public key. :type sender_public_key: str :param sequence: Vapor sequence number(expiration block), defaults to Vapor config sequence. :type sequence: int :param use_script: Initialize HTLC by using script, default to False. :type use_script: bool :returns: HTLC -- Vapor Hash Time Lock Contract (HTLC) instance. >>> from swap.providers.vapor.htlc import HTLC >>> from swap.utils import sha256 >>> htlc = HTLC(network="mainnet") >>> htlc.build_htlc(secret_hash=sha256("Hello Meheret!"), recipient_public_key="3e0a377ae4afa031d4551599d9bb7d5b27f4736d77f78cac4d476f0ffba5ae3e", sender_public_key="91ff7f525ff40874c4f47f0cab42e46e3bf53adad59adef9558ad1b6448f22e2", sequence=1000, use_script=False) <swap.providers.vapor.htlc.HTLC object at 0x0409DAF0> """ # Checking parameters instances if len(secret_hash) != 64: raise ValueError("Invalid secret hash, length must be 64") if len(recipient_public_key) != 64: raise ValueError("Invalid Bitcoin recipient public key, length must be 64") if len(sender_public_key) != 64: raise ValueError("Invalid Bitcoin sender public key, length must be 64") if use_script: HTLC_AGREEMENTS: List[str, int] = [ secret_hash, recipient_public_key, sender_public_key, sequence ] # Compile HTLC by script self._script = Equity( url=config[self._network]["vapor-core"], timeout=config["sequence"] ).compile_source(HTLC_SCRIPT, HTLC_AGREEMENTS) else: # Compile HTLC by script binary builder: Builder = Builder() builder.add_int(sequence) builder.add_bytes(bytes.fromhex(sender_public_key)) builder.add_bytes(bytes.fromhex(recipient_public_key)) builder.add_bytes(bytes.fromhex(secret_hash)) builder.add_op(OP_DEPTH) builder.add_bytes(bytes.fromhex(HTLC_SCRIPT_BINARY)) builder.add_op(OP_FALSE) builder.add_op(OP_CHECKPREDICATE) SEQUENCE = bytes(c_int64(sequence)).rstrip(b'\x00').hex() self._script = dict( program=builder.hex_digest(), opcodes=f"0x{SEQUENCE} 0x{sender_public_key} 0x{recipient_public_key} " f"0x{secret_hash} DEPTH 0x{HTLC_SCRIPT_BINARY} FALSE CHECKPREDICATE" ) return self
from equity import Equity LOCK_WITH_PUBLIC_KEY_SOURCE = """ contract LockWithPublicKey(publicKey: PublicKey) locks valueAmount of valueAsset { clause spend(sig: Signature) { verify checkTxSig(publicKey, sig) unlock valueAmount of valueAsset } } """ LOCK_WITH_PUBLIC_KEY_PATH = "./LockWithPublicKey.equity" # LOCK_WITH_PUBLIC_KEY_ARGS = [ # "e9108d3ca8049800727f6a3505b3a2710dc579405dde03c250f16d9a7e1e6e78" # ] equity = Equity("http://localhost:9888") COMPILED = equity.compile_source( LOCK_WITH_PUBLIC_KEY_SOURCE, "e9108d3ca8049800727f6a3505b3a2710dc579405dde03c250f16d9a7e1e6e78") print(COMPILED["name"]) print(COMPILED["program"]) print(COMPILED["opcodes"], "\n") print(COMPILED) equity.save()