<s> import os <EOL> import re <EOL> import pandas as pd <EOL> import rpy2 . robjects as robjects <EOL> from intuition . api . portfolio import PortfolioFactory <EOL> import insights . transforms as transforms <EOL> class OptimalFrontier ( PortfolioFactory ) : <EOL> '''<STR_LIT>''' <EOL> def initialize ( self , parameters ) : <EOL> self . r = robjects . r <EOL> portfolio_opt_file = '<STR_LIT:/>' . join ( <EOL> [ os . path . expanduser ( '<STR_LIT>' ) , '<STR_LIT:R>' , '<STR_LIT>' ] ) <EOL> assert os . path . exists ( portfolio_opt_file ) <EOL> self . r ( '<STR_LIT>' . format ( portfolio_opt_file ) ) <EOL> self . price_transform = transforms . get_past_returns ( <EOL> refresh_period = parameters . get ( '<STR_LIT>' , <NUM_LIT:1> ) , <EOL> window_length = parameters . get ( '<STR_LIT>' , <NUM_LIT:50> ) , <EOL> compute_only_full = parameters . get ( '<STR_LIT>' , True ) ) <EOL> def optimize ( self , date , to_buy , to_sell , parameters ) : <EOL> allocations = { } <EOL> for sid in to_sell : <EOL> allocations [ sid ] = - parameters . get ( '<STR_LIT>' , <NUM_LIT:1.0> ) <EOL> if len ( to_buy ) == <NUM_LIT:1> : <EOL> allocations . update ( <EOL> { to_buy . keys ( ) [ <NUM_LIT:0> ] : parameters . get ( '<STR_LIT>' , <NUM_LIT> ) } ) <EOL> return allocations , <NUM_LIT:0> , <NUM_LIT:1> <EOL> if '<STR_LIT>' in parameters : <EOL> returns_df = parameters [ '<STR_LIT>' ] <EOL> else : <EOL> returns_df = self . price_transform . handle_data ( to_buy ) <EOL> if returns_df is None : <EOL> return allocations , <NUM_LIT:0> , <NUM_LIT:1> <EOL> for i , column in enumerate ( returns_df ) : <EOL> if returns_df [ column ] . isnull ( ) . any ( ) : <EOL> self . log . warning ( '<STR_LIT>' <EOL> . format ( column ) ) <EOL> returns_df = returns_df . dropna ( axis = <NUM_LIT:1> ) <EOL> returns = pd . rpy . common . convert_to_r_matrix ( returns_df ) <EOL> frontier = self . r ( '<STR_LIT>' ) ( <EOL> returns , points = <NUM_LIT> , Debug = False , graph = False ) <EOL> if not frontier : <EOL> self . log . warning ( '<STR_LIT>' ) <EOL> return allocations , <NUM_LIT:0> , <NUM_LIT:1> <EOL> try : <EOL> mp = self . r ( '<STR_LIT>' ) ( <EOL> frontier , <NUM_LIT> , Debug = False , graph = False ) <EOL> except : <EOL> self . log . error ( '<STR_LIT>' ) <EOL> return allocations , <NUM_LIT:0> , <NUM_LIT:1> <EOL> for sid in returns_df : <EOL> try : <EOL> allocations [ sid ] = round ( <EOL> mp . rx ( re . sub ( "<STR_LIT>" , "<STR_LIT:.>" , sid ) ) [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] , <NUM_LIT:2> ) <EOL> except : <EOL> allocations [ sid ] = <NUM_LIT> <EOL> er = round ( mp . rx ( '<STR_LIT>' ) [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] , <NUM_LIT:2> ) <EOL> eStd = round ( mp . rx ( '<STR_LIT>' ) [ <NUM_LIT:0> ] [ <NUM_LIT:0> ] , <NUM_LIT:2> ) <EOL> self . log . info ( <EOL> '<STR_LIT>' <EOL> . format ( allocations , er , eStd ) ) <EOL> return allocations , er , eStd </s>
