<s> import numpy as np <EOL> from intuition . api . portfolio import PortfolioFactory <EOL> import insights . managers . utils as utils <EOL> class OLMAR ( PortfolioFactory ) : <EOL> '''<STR_LIT>''' <EOL> initialized = False <EOL> def initialize ( self , configuration ) : <EOL> self . log . debug ( configuration ) <EOL> self . eps = configuration . get ( '<STR_LIT>' , <NUM_LIT:1> ) <EOL> def warm ( self , data ) : <EOL> self . m = len ( data . keys ( ) ) <EOL> self . b_t = np . ones ( self . m ) / self . m <EOL> def _rebalance_portfolio ( self , data , desired_port ) : <EOL> allocations = { } <EOL> desired_amount = np . zeros_like ( desired_port ) <EOL> current_amount = np . zeros_like ( desired_port ) <EOL> prices = np . zeros_like ( desired_port ) <EOL> if not self . initialized : <EOL> positions_value = self . portfolio . starting_cash <EOL> self . initialized = True <EOL> else : <EOL> positions_value = self . portfolio . positions_value + self . portfolio . cash <EOL> for i , stock in enumerate ( data ) : <EOL> current_amount [ i ] = self . portfolio . positions [ stock ] . amount <EOL> prices [ i ] = data [ stock ] . price <EOL> desired_amount = np . round ( desired_port * positions_value / prices ) <EOL> diff_amount = desired_amount - current_amount <EOL> for i , stock in enumerate ( data ) : <EOL> if not np . isnan ( diff_amount [ i ] ) : <EOL> allocations [ stock ] = int ( diff_amount [ i ] ) <EOL> return allocations <EOL> def optimize ( self , date , to_buy , to_sell , parameters ) : <EOL> allocations = { } <EOL> for sid in to_sell : <EOL> allocations [ sid ] = to_sell [ sid ] . amount <EOL> data = to_buy <EOL> x_tilde = np . zeros ( self . m ) <EOL> b = np . zeros ( self . m ) <EOL> for i , stock in enumerate ( data ) : <EOL> price = data [ stock ] . price <EOL> if '<STR_LIT>' in data [ stock ] : <EOL> x_tilde [ i ] = data [ stock ] [ '<STR_LIT>' ] [ '<STR_LIT>' ] / price <EOL> x_bar = x_tilde . mean ( ) <EOL> mark_rel_dev = x_tilde - x_bar <EOL> exp_return = np . dot ( self . b_t , x_tilde ) <EOL> weight = self . eps - exp_return <EOL> variability = ( np . linalg . norm ( mark_rel_dev ) ) ** <NUM_LIT:2> <EOL> if variability == <NUM_LIT:0.0> : <EOL> step_size = <NUM_LIT:0> <EOL> else : <EOL> step_size = max ( <NUM_LIT:0> , weight / variability ) <EOL> b = self . b_t + step_size * mark_rel_dev <EOL> b_norm = utils . simplex_projection ( b ) <EOL> np . testing . assert_almost_equal ( b_norm . sum ( ) , <NUM_LIT:1> ) <EOL> allocations . update ( self . _rebalance_portfolio ( data , b_norm ) ) <EOL> self . b_t = b_norm <EOL> e_ret = exp_return <EOL> e_risk = variability <EOL> return allocations , e_ret , e_risk </s>
