예제 #1
0
    def __init__(self, **kwargs):
        '''
        kwargs: {
                execution: {single_stock, multi_stocks},
                portfolio: {sharpe, dsharpe, ... ...} 
                valuer: {MarketValuer, SharpeValuer, ...  ... }
                }
        '''

        ### common variables
        self.__sym = kwargs['sym']
        self.__start = kwargs['start']
        self.__end = kwargs['end']

        ### market data providers
        self.__provider = MarketDataProvider('quandl', self.__sym,
                                             self.__start, self.__end)
        self.__OHLCV = self.__provider.getMarketData('OHLCV')
        self.__sma10 = self.__provider.getMarketData('close_sma', period=1)

        if (kwargs['execution'] == 'single_stock'):
            self.__executionservice = SingleStockExecutionSimulator(
                self.__sym, self.__start, self.__end, self.__OHLCV)

        self.__initial_value = 100000
        self.__current_value = self.__initial_value
        if (kwargs['portfolio'] == 'basic'):
            self.__portfolio = Portfolio(self.__current_value)

        if (kwargs['valuer'] == 'market'):
            self.__portfolio_valuer = MarketValuer()

        self.__oms = OMS(self.__executionservice, self.__portfolio,
                         self.__portfolio_valuer)
예제 #2
0
def portfolio_chart():
    portfolio = Portfolio(portfolio_id=1)
    state_asset, state_cur = portfolio.get_state(total=False)
    values = []
    labels = []
    for item in state_asset:
        ticker, name, quantity, sec_cur, position_orig, position = item
        values.append(position)
        labels.append(name)

    data = {
        'data': [
            {
                'values': values,
                'labels': labels,
                'type': 'pie'
            }
        ],
        'layout': {
            'autosize': False,
            'width': 1900,
            'height': 900,
        }
    }

    data = json.dumps(data, cls=plotly.utils.PlotlyJSONEncoder)
    return templating.render_template('chart.html', data=data)
예제 #3
0
 def create(self):
     """Create a new portfolio."""
     filename = input("File name to create: ")
     path = Path(filename)
     if not path.exists():
         self.portfolio = Portfolio(path=path)
         self.add()
예제 #4
0
def value_chart():
    cur = request.args.get('cur', Portfolio.RUB)
    broker = request.args.get('broker')

    portfolio = Portfolio(1, broker_id=int(broker) if broker else None)
    start_date = None
    end_date = datetime.now()
    time_range = TimeRange(start_date, end_date)

    data = portfolio.get_value_history(time_range, currency=cur)
    cbr_data = portfolio.get_cbr_history(time_range, currency=cur)
    cash_data = portfolio.get_cash_history(time_range, currency=cur)
    samples = [data, cbr_data, cash_data]

    data = {
        'data': [],
        'layout': RANGE_LAYOUT
    }

    for sample in samples:
        data['data'].append({
            'x': list(sample.keys()),
            'y': list(sample.values()),
            'name': sample.title,
        })

    data = json.dumps(data, cls=plotly.utils.PlotlyJSONEncoder)
    return templating.render_template('chart.html', data=data)
예제 #5
0
 def post( self, request, slug ):
     portfolio = Portfolio( slug )
     symbol = request.POST.get( 'symbol', None )
     amount = request.POST.get( 'amount', None )
     if portfolio.remove_holding( symbol, amount ):
         return redirect( '/portfolio/{}/manage'.format( slug ) )
     else:
         return redirect( '/portfolio/{}/manage'.format( slug ) )
예제 #6
0
 def setUp(self):
     home_currency = "GBP"
     leverage = 20
     equity = Decimal("100000.00")
     risk_per_trade = Decimal("0.02")
     ticker = TickerMock()
     events = {}
     self.port = Portfolio(
         ticker, events, home_currency=home_currency,
         leverage=leverage, equity=equity,
         risk_per_trade=risk_per_trade
     )
예제 #7
0
    def post( self, request ):
        form = Portfolio.create_form( request.POST )

        if form.is_valid():
            data = form.cleaned_data
            data['user'] = User.objects.get( id=request.user.id )
            results = Portfolio.create( data )
            
            return redirect( '/portfolio/{}/manage'.format( results.slug ) )

        request.context_dict[ 'form' ] = form
        
        return render( request, 'portfolio/create.html', request.context_dict )
 def test_it_returns_the_debt_to_equity_ratio_for_a_portfolio_with_only_liabilities(
         self):
     account = AccountBuilder().set_name("name") \
         .set_institution("institution") \
         .set_owner("owner") \
         .set_investment("investment") \
         .set_asset_class(AssetClass.NONE) \
         .set_account_type(AccountType.LIABILITY) \
         .build()
     account.import_snapshot(EpochDateConverter().date_to_epoch(), 1234)
     portfolio = Portfolio()
     portfolio.import_account(account)
     self.assertEqual(PortfolioAnalyzer(portfolio).debt_to_equity(), 1.0)
예제 #9
0
 def setUp(self):
     self.portfolio = Portfolio()
     self.asset_data_1 = {"timestamp": "2017-06-01", "name": "Proctor and Gamble", "investment": "PG", "value": 1000,
                          "asset_class": "Equities", "owner": "Bob", "institution": "Bank 1",
                          "account_type": "ASSET", "update_frequency": 2, "term": "none"}
     self.asset_data_2 = {"timestamp": "2017-07-01", "name": "Vanguard Bond Fund", "investment": "VTIBX",
                          "value": 2000, "asset_class": "Fixed Income", "owner": "Sam", "institution": "Bank 2",
                          "account_type": "ASSET", "update_frequency": 9, "term": "none"}
     self.liability_data_1 = {"timestamp": "2017-06-05", "name": "Visa Card", "value": 1000, "investment": "CASHX",
                              "institution": "Bank 1", "account_type": "LIABILITY", "asset_class": "None",
                              "owner": "Craig", "update_frequency": 15, "term": "none"}
     self.liability_data_2 = {"timestamp": "2017-07-05", "name": "Personal Loan", "value": 1500,
                              "investment": "CASHX", "institution": "Bank 2", "account_type": "LIABILITY",
                              "asset_class": "None", "owner": "Eusavio", "term": "none"}
예제 #10
0
 def setUp(self):
     self.asset = AccountBuilder().set_name("name") \
         .set_owner("owner") \
         .set_investment("investment") \
         .set_institution("institution") \
         .set_update_frequency(3) \
         .build()
     self.liability = AccountBuilder().set_name("name") \
         .set_owner("owner") \
         .set_investment("investment") \
         .set_institution("institution") \
         .set_liability() \
         .build()
     self.portfolio = Portfolio()
예제 #11
0
def main(portfolioJsonFilePath, updateCacheAfterMinutes):
    currentTime = datetime.now()
    currentEpoch = int(currentTime.timestamp())
    lastEpoch = utils.getLastUpdateEpochTime()

    currentTimeEST = datetime.now(pytz.timezone('US/Eastern'))
    currentTime = datetime.now()

    print("Local Time:\t", currentTime.strftime("%Y-%m-%d %I:%M %p, %A"))
    print("EST Time:\t", currentTimeEST.strftime("%Y-%m-%d %I:%M %p, %A"))
    print("***********************************")
    if isCacheStale(currentEpoch, lastEpoch,
                    updateCacheAfterMinutes * MINUTES_TO_SECONDS):
        print("===Updating Data===")
        utils.setLastUpdateEpochTime(currentEpoch)
        TickerCache.clearCache()
    else:
        print("===Using Cached Data===")

    portfoliosJson = json.loads(utils.getFileData(portfolioJsonFilePath))

    portfolios = list()
    for portfolioJson in portfoliosJson["portfolios"]:
        portfolio = Portfolio()
        portfolio.parse(portfolioJson)
        portfolios.append(portfolio)

    portfolioPrependStr = ""
    for portfolio in portfolios:
        Portfolio.printHeader(portfolioPrependStr)
        portfolio.print(portfolioPrependStr)

    TickerCache.saveCache()
예제 #12
0
 def __init__(self, portfolio=Portfolio()):
     self.portfolio = portfolio
     self.headers = [
         "Last Updated", "Institution", "Account", "Investment", "Owner",
         "Value"
     ]
     self.spacers = ["---", "---", "---", "---", "---", "---"]
예제 #13
0
 def __init__(self, events_queue, cash, quote_data, order_sizer, risk_manager):
     self.events_queue = events_queue
     self.cash = cash
     self.quote_data = quote_data
     self.order_sizer = order_sizer
     self.risk_manager = risk_manager
     self.portfolio = Portfolio(quote_data, cash)
예제 #14
0
def recommendation():

    # number of recommended items
    numberOfItems = 20
    print(numberOfItems)

    # (PortfolioDescription, EvaluationOfRecommenders)
    portfolioDescr, evaluationOfRecommenders = Input.input01()
    portfolioDescr, evaluationOfRecommenders = Input.input02()

    #portfolio:Portfolio
    portfolio = Portfolio(portfolioDescr)

    # itemIDs:list<int>
    itemIDs = portfolio.run(evaluationOfRecommenders, numberOfItems)
    print(itemIDs)
예제 #15
0
 def get( self, request ):
     if request.user.is_anonymous():
         return redirect('/')
     user_id = request.GET.get( 'user_id', request.user.id )
     request.context_dict[ 'portfolios' ] = Portfolio.by_user_id( user_id )
     
     return render( request, 'portfolio/display_all.html', request.context_dict )
예제 #16
0
 def get( self, request, slug ):
     if request.user.is_anonymous():
         return redirect('/')
     request.context_dict[ 'portfolio' ] = Portfolio( slug )
     request.context_dict[ 'form' ] = Portfolio.create_holding()
     
     return render( request, 'portfolio/holding_add.html', request.context_dict )
예제 #17
0
    def get( self, request, game_id ):
        if request.user.is_anonymous():
            return redirect('/')
        request.context_dict['game'] = get_game( game_id )
        request.context_dict['form'] = Portfolio.create_holding()

        print( request.context_dict['game'] )
        return render( request, 'game/manage.html', request.context_dict )
예제 #18
0
    def post( self, request, slug ):
        form = Portfolio.create_holding( request.POST )
        portfolio = Portfolio( slug, request.POST['date'] )

        if form.is_valid():
            form_data = form.cleaned_data
            form_data['date'] = request.POST['date']
            form_data['price'] = portfolio.stock_by_date( form_data['symbol'] ).close

            portfolio.add_holding( form_data )

            return redirect( '/portfolio/{}/manage'.format( slug ) )

        else:
            request.context_dict[ 'form' ] = form

            return render( request, 'portfolio/holding_add.html', request.context_dict )
예제 #19
0
파일: tables.py 프로젝트: akazaev/portfolio
def portfolio_table():
    broker = request.args.get('broker')
    portfolio = Portfolio(broker_id=int(broker) if broker else None,
                          portfolio_id=1)
    state_asset, state_cur = portfolio.get_state()
    items = []
    for item in state_asset:
        ticker, name, quantity, sec_cur, position_orig, position = item
        items.append({
            'ticker': ticker,
            'name': name,
            'quantity': quantity,
            'sec_cur': sec_cur,
            'position_orig': position_orig,
            'position': position
        })
    table = PortfolioTable(items, classes=['table', 'table-dark'])
    return templating.render_template('table.html', table=table)
예제 #20
0
def main() -> None:
    """Entry point for the portfolio app."""
    logger.debug('Running "%s" in "%s"', " ".join(sys.argv),
                 Path(".").resolve())
    with Portfolio() as portfolio:
        args = make_parser().parse_args()
        logger.debug("Arguments parsed as %s", args)
        if hasattr(args, "func"):
            with PortfolioConfig() as config:
                args.func(args, portfolio, config)
예제 #21
0
 def create(self, data_source):
     portfolio = Portfolio()
     data = data_source.get()
     snapshots = json.loads(data)
     for item in snapshots["snapshots"]:
         portfolio.import_data({
             "timestamp": item["timestamp"],
             "institution": item["institution"],
             "name": item["account"],
             "owner": item["owner"],
             "investment": item["investment"],
             "update_frequency": item["update_frequency"],
             "account_type": self.__account_type(item),
             "value": self.__value(item),
             "asset_class": self.__asset_class(item),
             "open_date": item["open_date"],
             "term": self.__term(item)
         })
     return portfolio
 def test_it_returns_the_debt_to_equity_ratio_for_a_historical_time(self):
     asset = AccountBuilder().set_name("name") \
         .set_institution("institution") \
         .set_owner("owner") \
         .set_investment("investment") \
         .set_asset_class(AssetClass.NONE) \
         .set_account_type(AccountType.ASSET) \
         .build()
     liability = AccountBuilder().set_name("name") \
         .set_institution("institution") \
         .set_owner("owner") \
         .set_investment("investment") \
         .set_asset_class(AssetClass.NONE) \
         .set_account_type(AccountType.LIABILITY) \
         .build()
     timestamp = EpochDateConverter().date_to_epoch()
     early_timestamp = timestamp - 200000
     query_time = timestamp - 100000
     asset.import_snapshot(timestamp, 112233)
     liability.import_snapshot(early_timestamp, 223344)
     portfolio = Portfolio()
     portfolio.import_account(asset)
     portfolio.import_account(liability)
     self.assertEqual(
         PortfolioAnalyzer(portfolio).debt_to_equity(
             EpochDateConverter().epoch_to_date(query_time)), 1.0)
예제 #23
0
def main(argv):

  config = "~/.portfolio.json"

  # cli arguments
  try:
    opts, args = getopt.getopt(argv,"hs:",[])
  except getopt.GetoptError:
    usage()

  for opt, arg in opts:
    if opt == '-h':
      usage()
    elif opt == '-s':
      config = arg
  
  try: 
    p = Portfolio(open(config).read())
    p.print_table()
  except IOError:
    print 'portfolio file not found!'
    sys.exit(1)
예제 #24
0
def example_rolling():
    start_date = Date(2019, 1, 3)
    oc = generate_cube(start_date, 0.88, 0.92)
    udl = oc.iloc[0].iloc[1].iloc[0].udl
    udls = udl.series
    dates = udls.index[udls.index.get_loc(Date(2019, 1, 3))::]
    cash_asset = OneUsd()
    rule = RollingPut(udl, oc)
    portfolio = Portfolio(rule, cash_asset, 100.0, start_date)
    portfolio.compute(dates)
    portfolio.report().to_clipboard()
    print(portfolio.report().head())
예제 #25
0
def gle_cppi():
    risky_asset = EquityYFinance("GLE.PA")
    maturity = Date(2025, 1, 5)
    zero_coupon = ZeroCouponFake(0.01, maturity, "long_rate_1")
    rule = CPPI_simple(risky_asset, zero_coupon, maturity, 25, 80.0)
    cash_asset = ZeroCouponFake(0.001, Date(2100, 1, 1), "cash_10_bp")
    start_date = Date(2021, 1, 4)
    portfolio = Portfolio(rule, cash_asset, 100.0, start_date)
    dates = risky_asset.h.index[risky_asset.h.index >= start_date]
    portfolio.compute(dates)
    portfolio.report().to_clipboard()
    print(portfolio.report().head())
예제 #26
0
    def get( self, request, date ):
        stocks = Portfolio.ticker( date )
        data = []
        for stock in stocks:
            yesterday = stock.date - datetime.timedelta(days=1)
            # print( 'yesterday', yesterday )
            try:
                yesterday = Stock_history.objects.get( symbol=stock.symbol, date=yesterday )
            except:
                continue
            # print( 'price',yesterday.close )
            change = yesterday.close - stock.close
            data.append({
                'symbol': stock.symbol,
                'close': stock.close,
                'change': change
            })

        return JsonResponse( data, safe=False )
예제 #27
0
    def post(self, request):
        form = GameCreateForm( request.POST )
        if form.is_valid():
            form_data = form.cleaned_data
            form_data['user'] = User.objects.get( id=request.user.id )
            form_data['balance'] = form_data['start_balance']

            portfolio_data = {
                'title': "game_{}".format( form_data['name'] ),
                'description': "Portfolio for game play.",
                'user': form_data['user']
            }

            portfolio = Portfolio.create( portfolio_data )

            form_data['portfolio_id'] = portfolio.id

            game = Whole_Game.objects.create( **form_data )
            return redirect( '/game/{}/start'.format( game.id ) )
        else:
            request.context_dict['form'] = form 
            return render( request, 'game/index.html', request.context_dict )
예제 #28
0
    def post( self, request, game_id ):
        request.context_dict['game'] = get_game( game_id )
        form = Portfolio.create_holding( request.POST )
        request.context_dict[ 'form' ] = form
        if form.is_valid():
            form_data = form.cleaned_data
            form_data['date'] = str( request.context_dict['game'].current_date )

            form_data['price'] = request.context_dict['game'].portfolio.stock_by_date( form_data['symbol'] ).close
            if form_data['price'] * form_data["shares"] <= request.context_dict["game"].balance:
                results = request.context_dict['game'].portfolio.add_holding( form_data )

                request.context_dict['game'].balance -= results
                request.context_dict['game'].save( update_fields=["balance"] )

                return redirect( '/game/{}/manage'.format( game_id ) )
            else:
                errors = request.context_dict[ 'form' ]._errors.setdefault("shares", ErrorList())
                errors.append(u"You cannot afford that")
                return render( request, 'game/manage.html', request.context_dict ) 
        else:
            return render( request, 'game/manage.html', request.context_dict )
 def test_it_returns_the_debt_to_equity_ratio_for_a_portfolio_with_a_mixture_of_accounts_in_nonequal_value(
         self):
     asset = AccountBuilder().set_name("name") \
         .set_institution("institution") \
         .set_owner("owner") \
         .set_investment("investment") \
         .set_asset_class(AssetClass.NONE) \
         .set_account_type(AccountType.ASSET) \
         .build()
     liability = AccountBuilder().set_name("name") \
         .set_institution("institution") \
         .set_owner("owner") \
         .set_investment("investment") \
         .set_asset_class(AssetClass.NONE) \
         .set_account_type(AccountType.LIABILITY) \
         .build()
     asset.import_snapshot(EpochDateConverter().date_to_epoch(), 1234)
     liability.import_snapshot(EpochDateConverter().date_to_epoch(), 12345)
     portfolio = Portfolio()
     portfolio.import_account(asset)
     portfolio.import_account(liability)
     self.assertAlmostEqual(
         PortfolioAnalyzer(portfolio).debt_to_equity(), 1.1110611)
예제 #30
0
def main():

    # Bull-Spread implementation example

    # default market environment
    market_env = MarketEnvironment()
    print(market_env)

    # options strikes
    K_long = 80
    K_short = 110

    # bull-spread portfolio initialized (as empty portfolio)
    bull_spread_ptf = Portfolio(name="Bull Spread Strategy")
    print(bull_spread_ptf)

    # 80-call
    Vanilla_Call_long = PlainVanillaOption(market_env,
                                           K=K_long,
                                           T='31-12-2021')
    print(Vanilla_Call_long)

    # 110-call
    Vanilla_Call_short = PlainVanillaOption(market_env,
                                            K=K_short,
                                            T='31-12-2021')
    print(Vanilla_Call_short)

    # creation of bull-spread portfolio strategy
    bull_spread_ptf.add_instrument(Vanilla_Call_long, 1)
    bull_spread_ptf.add_instrument(Vanilla_Call_short, -1)
    print(bull_spread_ptf)

    # portfolio plotter instance
    bull_spread_ptf_plotter = PortfolioPlotter(bull_spread_ptf)

    # select dependency to plot as x-axis of the plot
    # (strike 'K' is skipped because a bull-spread is a multi-strike portfolio)
    for dependency_type in ["S", "sigma", "r"]:

        # keyboard parameter and corresponding range to test
        x_axis_dict = options_x_axis_parameters_factory(
            bull_spread_ptf, dependency_type)

        # appropriate azimut angle for best viewing
        azimut_angle = get_azimut_angle(dependency_type)

        # select metrics to plot
        for plot_metrics in [
                "price", "PnL", "delta", "theta", "gamma", "vega", "rho"
        ]:

            plot_details_flag = True if plot_metrics == "price" else False

            # Bull-Spread price plot
            bull_spread_ptf_plotter.plot(**x_axis_dict,
                                         t='01-06-2020',
                                         plot_metrics=plot_metrics,
                                         plot_details=plot_details_flag)

            for time_kind in ['date', 'tau']:

                # set time-parameter to plot
                multiple_valuation_dates = get_time_parameter(bull_spread_ptf,
                                                              kind=time_kind)
                print(multiple_valuation_dates)

                # Plot at multiple dates
                bull_spread_ptf_plotter.plot(**x_axis_dict,
                                             t=multiple_valuation_dates,
                                             plot_metrics=plot_metrics)

                # Surface plot
                bull_spread_ptf_plotter.plot(**x_axis_dict,
                                             t=multiple_valuation_dates,
                                             plot_metrics=plot_metrics,
                                             surf_plot=True)

                # Surface plot (rotate) - x-axis side
                bull_spread_ptf_plotter.plot(**x_axis_dict,
                                             t=multiple_valuation_dates,
                                             plot_metrics=plot_metrics,
                                             surf_plot=True,
                                             view=(
                                                 0,
                                                 azimut_angle["x-axis side"]))

                # Price surface plot (rotate) - Date side
                bull_spread_ptf_plotter.plot(**x_axis_dict,
                                             t=multiple_valuation_dates,
                                             plot_metrics=plot_metrics,
                                             surf_plot=True,
                                             view=(0,
                                                   azimut_angle["Date side"]))
예제 #31
0
def main():

    #
    # portfolio instantiation example
    #

    # if np_output is True, the output will be np.ndarray, otherwise pd.DataFrame
    np_output = False  # True

    # default market environment
    market_env = MarketEnvironment(t="01-06-2020")
    print(market_env)

    # underlying values to test
    S_vector = [60, 90, 120]
    print("S_vector: {}\n".format(S_vector))

    # options maturities
    T_call = "31-12-2020"
    T_put = "30-06-2021"

    # options strikes are the same
    K = 90
    K_put = K
    K_call = K

    # portfolio options positions
    call_pos = 2
    put_pos = -5

    #
    # Step 0: empty portfolio initialized
    #

    ptf = Portfolio()
    print(ptf)

    #
    # Step 1: adding 2 long plain-vanilla call contracts
    #

    # plain-vanilla call option
    opt1_style = "plain_vanilla"  # "digital"
    opt1_type = "call"  # "put"
    call = option_factory(market_env,
                          opt1_style,
                          opt1_type,
                          K=K_call,
                          T=T_call)
    print(call)

    # adding contract to portfolio
    ptf.add_instrument(call, call_pos)
    print(ptf)

    #
    # Step 2: adding 5 short plain-vanilla put contracts
    #

    # plain-vanilla put option
    opt2_style = "plain_vanilla"  # "digital"
    opt2_type = "put"  # "call"
    put = option_factory(market_env, opt2_style, opt2_type, K=K_put, T=T_put)
    print(put)

    # plain-vanilla put option
    put = PlainVanillaOption(market_env, option_type="put", K=K_put, T=T_put)
    print(put)

    # adding contract to portfolio
    ptf.add_instrument(put, put_pos)
    print(ptf)

    #
    # Step 3: portfolio evaluation
    #

    for case in ['All_scalar', \
                 'S', 'S.sigma_distributed', 'S.r_distributed', 'S.sigma_and_r_distributed', \
                 'K', 'K.sigma_distributed', 'K.r_distributed', 'K.sigma_and_r_distributed', \
                 't', 't.sigma_distributed', 't.r_distributed', 't.sigma_and_r_distributed', \
                 'S.t', 'S.t.sigma_distributed_as_Sxt_grid', 'S.t.r_distributed_as_Sxt_grid', 'S.t.sigma_and_r_distributed_as_Sxt_grid', \
                 'K.t', 'K.t.sigma_distributed_as_Kxt_grid', 'K.t.r_distributed_as_Kxt_grid', 'K.t.sigma_and_r_distributed_as_Kxt_grid', \
                 't.sigma_axis', 't.r_axis']:

        # get parameters dictionary for case considered
        param_dict, case_info = get_param_dict_single_K_ptf(
            ptf,
            np_output,
            case,
            T=min(T_call, T_put, key=date_string_to_datetime_obj))

        print("\n--------------------------------------------\n")
        print("\n" + case_info + "\n")

        print("Parameters:")
        print("S: {}".format(param_dict["S"]))
        print("K: {}".format(param_dict["K"]))
        print("t: {}".format(param_dict["t"]))
        print("sigma: {}".format(param_dict["sigma"]))
        print("r: {}\n".format(param_dict["r"]))

        print("Metrics:")

        # metrics to compare
        for metrics in [
                "price", "PnL", "delta", "theta", "gamma", "vega", "rho"
        ]:

            # portfolio metrics
            ptf_metrics = getattr(ptf, metrics)(**param_dict)
            print("\nPortfolio {}:\n{}".format(metrics, ptf_metrics))

            # verification with benchmark metrics
            call_metrics = getattr(call, metrics)(**param_dict)
            put_metrics = getattr(put, metrics)(**param_dict)
            benchmark_metrics = call_pos * call_metrics + put_pos * put_metrics
            print("\nBenchmark {}:\n{}".format(metrics, benchmark_metrics))

            # check effective match
            diff = (ptf_metrics - benchmark_metrics).astype('float')
            num_nonzero_diff = np.count_nonzero(diff) - np.isnan(
                diff).sum().sum()
            exact_match = True if num_nonzero_diff == 0 else False
            print("\nIs replication exact (NaN excluded)? {}\n".format(
                exact_match))
예제 #32
0
from datetime import datetime
import cProfile
from portfolio.portfolio import Portfolio

portfolio = Portfolio(1)
start_date = datetime(2019, 11, 20)
end_date = datetime(2020, 12, 31)

#cProfile.run("portfolio.cbr(start_date, end_date)", sort='cumtime')
cProfile.run("portfolio.get_value()", sort='cumtime')
예제 #33
0
class LineGraphTestCase(unittest.TestCase):
    def setUp(self):
        self.portfolio = Portfolio()

    def test_it_returns_a_value_of_zero_on_a_single_day(self):
        line_graph = LineGraph(self.portfolio)
        net_worth_values = line_graph.net_worth_vs_time(
            "2017-01-01", "2017-01-01")
        self.assertEqual(len(net_worth_values), 1)
        self.assertEqual(net_worth_values[0], {
            "series": "net-worth",
            "date": "2017-01-01",
            "value": 0
        })

    def test_it_returns_two_values_of_zero(self):
        line_graph = LineGraph(self.portfolio)
        net_worth_values = line_graph.net_worth_vs_time(
            "2017-06-01", "2017-06-02")
        self.assertEqual(len(net_worth_values), 2)
        self.assertEqual(net_worth_values[0], {
            "series": "net-worth",
            "date": "2017-06-01",
            "value": 0
        })
        self.assertEqual(net_worth_values[1], {
            "series": "net-worth",
            "date": "2017-06-02",
            "value": 0
        })

    def test_it_returns_many_values_of_zero(self):
        line_graph = LineGraph(self.portfolio)
        net_worth_values = line_graph.net_worth_vs_time(
            "2010-09-01", "2011-08-31")
        self.assertEqual(len(net_worth_values), 365)

    def test_it_returns_the_value_of_a_single_account(self):
        account = AccountBuilder().set_name("name")\
            .set_institution("institution")\
            .set_owner("Craig")\
            .set_investment("investment")\
            .build()
        account.import_snapshot(
            EpochDateConverter().date_to_epoch("2005-12-10"), 1000)
        self.portfolio.import_account(account)
        line_graph = LineGraph(self.portfolio)
        net_worth_values = line_graph.net_worth_vs_time(
            "2005-12-09", "2005-12-11")
        self.assertEqual(net_worth_values[0], {
            "series": "net-worth",
            "date": "2005-12-09",
            "value": 0
        })
        self.assertEqual(net_worth_values[1], {
            "series": "net-worth",
            "date": "2005-12-10",
            "value": 1000
        })
        self.assertEqual(net_worth_values[2], {
            "series": "net-worth",
            "date": "2005-12-11",
            "value": 1000
        })

    def test_it_returns_the_value_of_two_accounts(self):
        account_one = AccountBuilder().set_name("name")\
            .set_institution("institution")\
            .set_owner("Craig")\
            .set_investment("investment")\
            .build()
        account_two = AccountBuilder().set_name("name")\
            .set_institution("institution")\
            .set_owner("Samuel")\
            .set_investment("investment")\
            .set_liability()\
            .build()
        account_one.import_snapshot(
            EpochDateConverter().date_to_epoch("2009-10-15"), 10)
        account_two.import_snapshot(
            EpochDateConverter().date_to_epoch("2009-10-17"), 1000)
        self.portfolio.import_account(account_one)
        self.portfolio.import_account(account_two)
        line_graph = LineGraph(self.portfolio)
        net_worth_values = line_graph.net_worth_vs_time(
            "2009-10-13", "2009-10-19")
        self.assertEqual(net_worth_values[0], {
            "series": "net-worth",
            "date": "2009-10-13",
            "value": 0
        })
        self.assertEqual(net_worth_values[1], {
            "series": "net-worth",
            "date": "2009-10-14",
            "value": 0
        })
        self.assertEqual(net_worth_values[2], {
            "series": "net-worth",
            "date": "2009-10-15",
            "value": 10
        })
        self.assertEqual(net_worth_values[3], {
            "series": "net-worth",
            "date": "2009-10-16",
            "value": 10
        })
        self.assertEqual(net_worth_values[4], {
            "series": "net-worth",
            "date": "2009-10-17",
            "value": -990
        })
        self.assertEqual(net_worth_values[5], {
            "series": "net-worth",
            "date": "2009-10-18",
            "value": -990
        })
        self.assertEqual(net_worth_values[6], {
            "series": "net-worth",
            "date": "2009-10-19",
            "value": -990
        })
예제 #34
0
 def get( self, request ):
     if request.user.is_anonymous():
         return redirect('/')
     request.context_dict[ 'form' ] = Portfolio.create_form()
     
     return render( request, 'portfolio/create.html', request.context_dict )
예제 #35
0
def main():

    # Bull-Spread implementation example

    # default market environment
    market_env = MarketEnvironment()
    print(market_env)

    # options strikes
    K_long = 80
    K_short = 110

    # bull-spread portfolio initialized (as empty portfolio)
    bull_spread_ptf = Portfolio(name="Bull Spread Strategy")
    print(bull_spread_ptf)

    # 80-call
    Vanilla_Call_long = PlainVanillaOption(market_env,
                                           K=K_long,
                                           T='31-12-2021')
    print(Vanilla_Call_long)

    # 110-call
    Vanilla_Call_short = PlainVanillaOption(market_env,
                                            K=K_short,
                                            T='31-12-2021')
    print(Vanilla_Call_short)

    # creation of bull-spread portfolio strategy
    bull_spread_ptf.add_instrument(Vanilla_Call_long, 1)
    bull_spread_ptf.add_instrument(Vanilla_Call_short, -1)
    print(bull_spread_ptf)

    # portfolio plotter instance
    bull_spread_ptf_plotter = PortfolioPlotter(bull_spread_ptf)

    # select metrics to plot
    for plot_metrics in [
            "price", "PnL", "delta", "theta", "gamma", "vega", "rho"
    ]:

        plot_details_flag = True if plot_metrics == "price" else False

        # Bull-Spread price plot
        bull_spread_ptf_plotter.plot(t='01-06-2020',
                                     plot_metrics=plot_metrics,
                                     plot_details=plot_details_flag)

        for time_kind in ['date', 'tau']:

            # set time-parameter to plot
            multiple_valuation_dates = get_time_parameter(bull_spread_ptf,
                                                          kind=time_kind)
            print(multiple_valuation_dates)

            # Plot at multiple dates
            bull_spread_ptf_plotter.plot(t=multiple_valuation_dates,
                                         plot_metrics=plot_metrics)

            # Surface plot
            bull_spread_ptf_plotter.plot(t=multiple_valuation_dates,
                                         plot_metrics=plot_metrics,
                                         surf_plot=True)

            # Surface plot (rotate) - Underlying value side
            bull_spread_ptf_plotter.plot(t=multiple_valuation_dates,
                                         plot_metrics=plot_metrics,
                                         surf_plot=True,
                                         view=(0, 180))

            # Price surface plot (rotate) - Date side
            bull_spread_ptf_plotter.plot(t=multiple_valuation_dates,
                                         plot_metrics=plot_metrics,
                                         surf_plot=True,
                                         view=(0, -90))
features = sample_data_features_raw.fillna(method='ffill')
features_no_nan = features.dropna()
features_final = features_no_nan.drop('side', axis=1).drop('label', axis=1)

model = pickle.load(open('randomforestmodel_strat1.sav', 'rb'))

sample_data.head()

sample_data.Date = pd.to_datetime(sample_data.Date)

from portfolio.portfolio import Portfolio
from order.order import Order

import datetime

SMA_portfolio = Portfolio('Strat1', datetime.date, 100000)

print(SMA_portfolio.TotalCapital)

#we start backtesting from the beginning of the 'test dataset' while training the ML model
i = sample_data[sample_data.Date == '2018-12-12 14:21:00'].index[0]

while i < len(sample_data.values):
    print(i)
    new_data_point = sample_data.loc[i]
    prev_data_point = sample_data.loc[i - 1]

    if prev_data_point.MA_5 < prev_data_point.MA_20 and new_data_point.MA_5 > new_data_point.MA_20:

        new_data_point_features = features_final.loc[
            new_data_point.Date].values.reshape(1, -1)
def main():
    
    # Calendar-Spread implementation example
            
    # default market environment
    market_env = MarketEnvironment()
    print(market_env)
    
    # options expirations
    T_short = "31-05-2020"
    T_long = "30-08-2020"
    
    # current underlying level
    S_t = market_env.get_S()

    # calendar-spread portfolio initialized (as empty portfolio)   
    calendar_spread_ptf = Portfolio(name="Calendar Spread Strategy")
    print(calendar_spread_ptf)
    
    # T_long-call
    Vanilla_Call_long = PlainVanillaOption(market_env, T=T_long, K=S_t)
    print(Vanilla_Call_long)

    # T_short-call
    Vanilla_Call_short = PlainVanillaOption(market_env, T=T_short, K=S_t)
    print(Vanilla_Call_short)

    # creation of Calendar-Spread portfolio strategy   
    calendar_spread_ptf.add_instrument(Vanilla_Call_long, 1)
    calendar_spread_ptf.add_instrument(Vanilla_Call_short, -1)    
    print(calendar_spread_ptf)
    
    # portfolio plotter instance
    calendar_spread_ptf_plotter = PortfolioPlotter(calendar_spread_ptf)
    
    # valuation date of the portfolio
    valuation_date = calendar_spread_ptf.get_t()
    print(valuation_date)
        
    # select metrics to plot
    for plot_metrics in ["price", "PnL", "delta", "theta", "gamma", "vega", "rho"]:
        
        plot_details_flag = True if plot_metrics == "price" else False

        # time-parameter as a date-range of 5 valuation dates between t and T_short
        # being the Calendar-Spread a multi-horizon portfolio, time-to-maturity
        # time parameters are not allowed.
        last_date = T_short if plot_metrics in ["price", "PnL"] else date_string_to_datetime_obj(T_short) - pd.Timedelta(days=1)
        multiple_valuation_dates = pd.date_range(start=valuation_date, 
                                                 end=last_date, 
                                                 periods=5)
        print(multiple_valuation_dates)

        # Bull-Spread price plot
        calendar_spread_ptf_plotter.plot(t=last_date, plot_metrics=plot_metrics, 
                                         plot_details=plot_details_flag)
            
        # Plot at multiple dates
        calendar_spread_ptf_plotter.plot(t=multiple_valuation_dates, plot_metrics=plot_metrics)
    
        # Surface plot
        calendar_spread_ptf_plotter.plot(t=multiple_valuation_dates, plot_metrics=plot_metrics, 
                                         surf_plot=True)
    
        # Surface plot (rotate) - Underlying value side
        calendar_spread_ptf_plotter.plot(t=multiple_valuation_dates, plot_metrics=plot_metrics, 
                                         surf_plot=True, view=(0,180))
    
        # Price surface plot (rotate) - Date side
        calendar_spread_ptf_plotter.plot(t=multiple_valuation_dates, plot_metrics=plot_metrics, 
                                         surf_plot=True, view=(0,-90))
예제 #38
0
class PortfolioTestCase(unittest.TestCase):
    def setUp(self):
        self.portfolio = Portfolio()
        self.asset_data_1 = {"timestamp": "2017-06-01", "name": "Proctor and Gamble", "investment": "PG", "value": 1000,
                             "asset_class": "Equities", "owner": "Bob", "institution": "Bank 1",
                             "account_type": "ASSET", "update_frequency": 2, "term": "none"}
        self.asset_data_2 = {"timestamp": "2017-07-01", "name": "Vanguard Bond Fund", "investment": "VTIBX",
                             "value": 2000, "asset_class": "Fixed Income", "owner": "Sam", "institution": "Bank 2",
                             "account_type": "ASSET", "update_frequency": 9, "term": "none"}
        self.liability_data_1 = {"timestamp": "2017-06-05", "name": "Visa Card", "value": 1000, "investment": "CASHX",
                                 "institution": "Bank 1", "account_type": "LIABILITY", "asset_class": "None",
                                 "owner": "Craig", "update_frequency": 15, "term": "none"}
        self.liability_data_2 = {"timestamp": "2017-07-05", "name": "Personal Loan", "value": 1500,
                                 "investment": "CASHX", "institution": "Bank 2", "account_type": "LIABILITY",
                                 "asset_class": "None", "owner": "Eusavio", "term": "none"}

    def test_it_starts_off_with_no_assets_or_liabilities(self):
        self.assertEqual(self.portfolio.assets_value(), 0)
        self.assertEqual(self.portfolio.liabilities_value(), 0)
        self.assertEqual(self.portfolio.total_value(), 0)

    def test_it_starts_off_no_percentages(self):
        self.assertEqual(self.portfolio.percentages(), {})

    def test_it_imports_asset_data_for_a_new_asset(self):
        self.portfolio.import_data(self.asset_data_1)
        self.assertEqual(self.portfolio.percentages(), {"PG": 1.0})

    def test_it_imports_liability_data_for_a_new_liability(self):
        self.portfolio.import_data(self.liability_data_1)
        self.assertEqual(self.portfolio.assets_value(), 0)
        self.assertEqual(self.portfolio.liabilities_value(), 1000)
        self.assertEqual(self.portfolio.total_value(), -1000)

    def test_it_imports_data_for_two_new_assets(self):
        self.portfolio.import_data(self.asset_data_1)
        self.portfolio.import_data(self.asset_data_2)
        self.assertEqual(self.portfolio.percentages(), {'PG': 0.333, 'VTIBX': 0.667})

    def test_it_imports_data_for_two_new_liabilities(self):
        self.portfolio.import_data(self.liability_data_1)
        self.portfolio.import_data(self.liability_data_2)
        self.assertEqual(self.portfolio.assets_value(), 0)
        self.assertEqual(self.portfolio.liabilities_value(), 2500)
        self.assertEqual(self.portfolio.total_value(), -2500)

    def test_it_imports_asset_data_for_an_existing_asset(self):
        asset_data = {"timestamp": "2017-05-01", "name": "Verizon", "investment": "VZ", "value": 5000,
                      "asset_class": "Equities", "term": "none",
                      "owner": "Abraham", "institution": "Bank", "account_type": "ASSET"}
        self.portfolio.import_data(asset_data)
        asset_data = {"timestamp": "2017-05-02", "name": "Verizon", "investment": "VZ", "value": 2000,
                      "asset_class": "Equities", "term": "none",
                      "owner": "Francis", "institution": "Bank", "account_type": "ASSET"}
        self.portfolio.import_data(asset_data)
        self.assertEqual(self.portfolio.percentages(), {"VZ": 1.0})

    def test_it_imports_asset_data_for_existing_and_new_assets_with_the_same_owner(self):
        asset_data = {"timestamp": "2017-06-01", "name": "VZ", "investment": "VZ", "value": 3000,
                      "asset_class": "Equities", "term": "none",
                      "owner": "Willie", "institution": "Bank", "account_type": "ASSET"}
        self.portfolio.import_data(asset_data)
        asset_data = {"timestamp": "2017-06-30", "name": "PEP", "investment": "PEP", "value": 4000,
                      "asset_class": "Equities", "term": "none",
                      "owner": "Willie", "institution": "Bank", "account_type": "ASSET"}
        self.portfolio.import_data(asset_data)
        asset_data = {"timestamp": "2017-06-17", "name": "VZ", "investment": "VZ", "value": 6000,
                      "asset_class": "Equities", "term": "none",
                      "owner": "Willie", "institution": "Bank", "account_type": "ASSET"}
        self.portfolio.import_data(asset_data)
        self.assertEqual(self.portfolio.percentages(), {"VZ": 0.6, "PEP": 0.4})

    def test_it_imports_asset_data_for_existing_and_new_assets_with_different_owners(self):
        asset_data = {"timestamp": "2017-06-01", "name": "VZ", "investment": "VZ", "value": 6000,
                      "asset_class": "Equities", "term": "none",
                      "owner": "Willie", "institution": "Bank", "account_type": "ASSET"}
        self.portfolio.import_data(asset_data)
        asset_data = {"timestamp": "2017-06-30", "name": "PEP", "investment": "PEP", "value": 6000,
                      "asset_class": "Equities", "term": "none",
                      "owner": "Seymour", "institution": "Bank", "account_type": "ASSET"}
        self.portfolio.import_data(asset_data)
        asset_data = {"timestamp": "2017-06-17", "name": "VZ", "investment": "VZ", "value": 6000,
                      "asset_class": "Equities", "term": "none",
                      "owner": "Jack", "institution": "Bank", "account_type": "ASSET"}
        self.portfolio.import_data(asset_data)
        self.assertEqual(self.portfolio.percentages(), {"VZ": 0.667, "PEP": 0.333})

    def test_it_does_not_ignore_a_single_zero_dollar_amount(self):
        asset_data = {"timestamp": "2012-01-01", "name": "T", "investment": "T", "value": 0, "asset_class": "Equities",
                      "owner": "Shauna", "institution": "Bank", "account_type": "ASSET",  "term": "none"}
        self.portfolio.import_data(asset_data)
        self.assertEqual(self.portfolio.percentages(), {"T": 0})

    def test_it_does_not_ignore_a_zero_dollar_amount_mixed_with_other_amounts(self):
        asset_data = {"timestamp": "2011-02-08", "name": "Verizon", "investment": "VZ", "value": 0,
                      "asset_class": "Equities", "term": "none",
                      "owner": "Brandine", "institution": "Bank", "account_type": "ASSET"}
        self.portfolio.import_data(asset_data)
        asset_data = {"timestamp": "2011-02-08", "name": "Something", "investment": "SP", "value": 12.54, "term": "none",
                      "asset_class": "Equities", "owner": "Brittney", "institution": "Bank", "account_type": "ASSET"}
        self.portfolio.import_data(asset_data)
        self.assertEqual(self.portfolio.percentages(), {"VZ": 0, "SP": 1.0})

    def test_it_gives_the_total_value_of_the_portfolio_at_the_current_time(self):
        self.portfolio.import_data(self.asset_data_1)
        self.portfolio.import_data(self.asset_data_2)
        self.portfolio.import_data(self.liability_data_1)
        self.assertEqual(self.portfolio.assets_value(), 3000)
        self.assertEqual(self.portfolio.liabilities_value(), 1000)
        self.assertEqual(self.portfolio.total_value(), 2000)

    def test_the_value_changes_on_the_day_it_is_recorded(self):
        self.portfolio.import_data(self.asset_data_1)
        self.assertEqual(self.portfolio.total_value("2017-05-31"), 0)
        self.assertEqual(self.portfolio.total_value("2017-06-01"), 1000)
        self.assertEqual(self.portfolio.total_value("2017-06-02"), 1000)

    def test_it_gives_the_total_value_of_the_portfolio_at_a_previous_time(self):
        asset_data = {"timestamp": "2017-01-01", "name": "Verizon", "investment": "VZ", "value": 100,
                      "asset_class": "Equities", "term": "none",
                      "owner": "Carl", "institution": "Bank", "account_type": "ASSET"}
        self.portfolio.import_data(asset_data)
        asset_data = {"timestamp": "2017-06-01", "name": "SP", "investment": "SP", "value": 12.50,
                      "asset_class": "Equities", "term": "none",
                      "owner": "Julie", "institution": "Bank", "account_type": "ASSET"}
        self.portfolio.import_data(asset_data)
        liability_data = {"timestamp": "2017-02-01", "name": "loan", "investment": "Bank of Martin", "value": 50,
                          "institution": "bank", "term": "none",
                          "account_type": "LIABILITY", "asset_class": "None", "owner": "Martin"}
        self.portfolio.import_data(liability_data)
        self.assertEqual(self.portfolio.assets_value("2017-03-01"), 100)
        self.assertEqual(self.portfolio.liabilities_value("2017-03-01"), 50)
        self.assertEqual(self.portfolio.total_value("2017-03-01"), 50)

    def test_it_does_not_include_liabilities_in_percentages(self):
        self.portfolio.import_data(self.asset_data_1)
        self.portfolio.import_data(self.asset_data_2)
        self.portfolio.import_data(self.liability_data_1)
        self.assertEqual(self.portfolio.percentages(), {'PG': 0.333, 'VTIBX': 0.667})

    def test_it_combines_assets_with_the_same_investment_in_percentage_calculations(self):
        asset_data = {"timestamp": "2017-01-01", "name": "Foo", "investment": "A", "value": 100,
                      "asset_class": "Equities", "term": "none",
                      "owner": "Felipe", "institution": "Bank", "account_type": "ASSET"}
        self.portfolio.import_data(asset_data)
        asset_data = {"timestamp": "2017-06-01", "name": "Bar", "investment": "A", "value": 100,
                      "asset_class": "Equities", "term": "none",
                      "owner": "Kent", "institution": "Bank", "account_type": "ASSET"}
        self.portfolio.import_data(asset_data)
        asset_data = {"timestamp": "2017-02-01", "name": "Baz", "investment": "B", "value": 100,
                      "asset_class": "Equities", "term": "none",
                      "owner": "Marge", "institution": "Bank", "account_type": "ASSET"}
        self.portfolio.import_data(asset_data)
        self.assertEqual(self.portfolio.percentages(), {"A": 0.667, "B": 0.333})

    def test_it_creates_different_assets_given_different_investments_with_the_same_name(self):
        asset_data = {"timestamp": "2017-01-01", "name": "Foo", "investment": "A", "value": 100,
                      "asset_class": "Equities", "term": "none",
                      "owner": "Lucy", "institution": "Bank", "account_type": "ASSET"}
        self.portfolio.import_data(asset_data)
        asset_data = {"timestamp": "2017-06-01", "name": "Foo", "investment": "B", "value": 200,
                      "asset_class": "Equities", "term": "none",
                      "owner": "Greg", "institution": "Bank", "account_type": "ASSET"}
        self.portfolio.import_data(asset_data)
        self.assertEqual(self.portfolio.percentages(), {"A": 0.333, "B": 0.667})

    def test_it_returns_zero_for_each_asset_class_if_there_is_no_asset_data(self):
        self.assertEqual(self.portfolio.asset_classes(),
                         {"Cash Equivalents": 0, "Equities": 0, "Fixed Income": 0, "Real Estate": 0, "Commodities": 0,
                          "Annuities": 0, "Fixed Assets": 0})

    def test_it_returns_asset_data_for_one_cash_equivalent(self):
        asset_data = {"timestamp": "2017-01-01", "name": "Foo", "investment": "A", "value": 100,
                      "asset_class": "Cash Equivalents", "owner": "Frank", "institution": "Bank",
                      "account_type": "ASSET", "term": "none"}
        self.portfolio.import_data(asset_data)
        self.assertEqual(self.portfolio.asset_classes(),
                         {"Cash Equivalents": 1, "Equities": 0, "Fixed Income": 0, "Real Estate": 0, "Commodities": 0,
                          "Annuities": 0, "Fixed Assets": 0})

    def test_it_returns_asset_data_for_one_equity(self):
        self.portfolio.import_data(self.asset_data_1)
        self.assertEqual(self.portfolio.asset_classes(),
                         {"Cash Equivalents": 0, "Equities": 1, "Fixed Income": 0, "Real Estate": 0, "Commodities": 0,
                          "Annuities": 0, "Fixed Assets": 0})

    def test_it_returns_asset_data_for_one_fixed_income_asset(self):
        self.portfolio.import_data(self.asset_data_2)
        self.assertEqual(self.portfolio.asset_classes(),
                         {"Cash Equivalents": 0, "Equities": 0, "Fixed Income": 1, "Real Estate": 0, "Commodities": 0,
                          "Annuities": 0, "Fixed Assets": 0})

    def test_it_returns_asset_data_for_one_real_estate_asset(self):
        asset_data = {"timestamp": "2017-01-01", "name": "Foo", "investment": "A", "value": 100,
                      "asset_class": "Real Estate", "owner": "Anna", "institution": "Bank", "account_type": "ASSET", "term": "none"}
        self.portfolio.import_data(asset_data)
        self.assertEqual(self.portfolio.asset_classes(),
                         {"Cash Equivalents": 0, "Equities": 0, "Fixed Income": 0, "Real Estate": 1, "Commodities": 0,
                          "Annuities": 0, "Fixed Assets": 0})

    def test_it_returns_asset_data_for_one_commodity(self):
        asset_data = {"timestamp": "2017-01-01", "name": "Foo", "investment": "A", "value": 100,
                      "asset_class": "Commodities", "owner": "Clark", "institution": "Bank", "account_type": "ASSET", "term": "none"}
        self.portfolio.import_data(asset_data)
        self.assertEqual(self.portfolio.asset_classes(),
                         {"Cash Equivalents": 0, "Equities": 0, "Fixed Income": 0, "Real Estate": 0, "Commodities": 1,
                          "Annuities": 0, "Fixed Assets": 0})

    def test_it_returns_asset_data_for_one_annuity(self):
        asset_data = {"timestamp": "2017-01-01", "name": "Foo", "investment": "A", "value": 100,
                      "asset_class": "Annuities", "owner": "Clark", "institution": "Bank", "account_type": "ASSET", "term": "none"}
        self.portfolio.import_data(asset_data)
        self.assertEqual(self.portfolio.asset_classes(),
                         {"Cash Equivalents": 0, "Equities": 0, "Fixed Income": 0, "Real Estate": 0, "Commodities": 0,
                          "Annuities": 1, "Fixed Assets": 0})

    def test_it_returns_asset_data_for_one_fixed_asset(self):
        asset_data = {"timestamp": "2017-01-01", "name": "Foo", "investment": "A", "value": 100,
                      "asset_class": "Fixed Assets", "owner": "Clark", "institution": "Bank", "account_type": "ASSET", "term": "none"}
        self.portfolio.import_data(asset_data)
        self.assertEqual(self.portfolio.asset_classes(),
                         {"Cash Equivalents": 0, "Equities": 0, "Fixed Income": 0, "Real Estate": 0, "Commodities": 0,
                          "Annuities": 0, "Fixed Assets": 1})

    def test_it_returns_asset_data_for_two_asset_classes(self):
        asset_data = {"timestamp": "2017-01-01", "name": "Foo", "investment": "A", "value": 100,
                      "asset_class": "Equities", "owner": "Tiffany", "institution": "Bank", "account_type": "ASSET", "term": "long"}
        self.portfolio.import_data(asset_data)
        asset_data = {"timestamp": "2017-02-01", "name": "Bar", "investment": "B", "value": 100, "asset_class": "Fixed Income",
                      "owner": "Eusavio", "institution": "Bank", "account_type": "ASSET", "term": "none"}
        self.portfolio.import_data(asset_data)
        self.assertEqual(self.portfolio.asset_classes(),
                         {"Cash Equivalents": 0, "Equities": 0.5, "Fixed Income": 0.5, "Real Estate": 0,
                          "Commodities": 0, "Annuities": 0, "Fixed Assets": 0})

    def test_it_imports_an_account(self):
        account = AccountBuilder().set_name("name") \
            .set_institution("institution") \
            .set_owner("owner") \
            .set_investment("investment") \
            .set_asset_class(AssetClass.NONE) \
            .set_account_type(AccountType.ASSET) \
            .build()
        self.portfolio.import_account(account)
        self.assertEqual(self.portfolio.accounts, [account])

    def test_it_imports_a_second_account_in_the_portfolio(self):
        account_one = AccountBuilder().set_name("name") \
            .set_institution("institution") \
            .set_owner("owner") \
            .set_investment("investment") \
            .set_asset_class(AssetClass.NONE) \
            .set_account_type(AccountType.ASSET) \
            .build()
        account_two = AccountBuilder().set_name("name") \
            .set_institution("institution") \
            .set_owner("another owner") \
            .set_investment("investment") \
            .set_asset_class(AssetClass.NONE) \
            .set_account_type(AccountType.ASSET) \
            .build()
        self.portfolio.import_account(account_one)
        self.portfolio.import_account(account_two)
        self.assertEqual(self.portfolio.accounts, [account_one, account_two])

    def test_it_does_not_import_an_account_if_it_already_exists_in_the_portfolio(self):
        account = AccountBuilder().set_name("name") \
            .set_institution("institution") \
            .set_owner("owner") \
            .set_investment("investment") \
            .set_asset_class(AssetClass.NONE) \
            .set_account_type(AccountType.ASSET) \
            .build()
        self.portfolio.import_account(account)
        self.portfolio.import_account(account)
        self.assertEqual(self.portfolio.accounts, [account])

    def test_it_returns_a_list_of_outdated_assets(self):
        account_one = AccountBuilder().set_name("name one") \
            .set_institution("institution") \
            .set_owner("owner") \
            .set_investment("investment") \
            .set_asset_class(AssetClass.NONE) \
            .set_account_type(AccountType.ASSET) \
            .set_update_frequency(120) \
            .build()
        account_two = AccountBuilder().set_name("name two") \
            .set_institution("institution") \
            .set_owner("owner") \
            .set_investment("investment") \
            .set_asset_class(AssetClass.NONE) \
            .set_account_type(AccountType.ASSET) \
            .set_update_frequency(1) \
            .build()
        timestamp = EpochDateConverter().date_to_epoch() - 5 * Constants.SECONDS_PER_DAY
        account_one.import_snapshot(timestamp, 100)
        account_two.import_snapshot(timestamp, 100)
        self.portfolio.import_account(account_one)
        self.portfolio.import_account(account_two)
        self.assertEqual(self.portfolio.outdated_assets(), [account_two])

    def test_it_returns_a_list_of_outdated_liabilities(self):
        account_one = AccountBuilder().set_name("name one") \
            .set_institution("institution") \
            .set_owner("owner") \
            .set_investment("investment") \
            .set_asset_class(AssetClass.NONE) \
            .set_account_type(AccountType.LIABILITY) \
            .set_update_frequency(10) \
            .build()
        account_two = AccountBuilder().set_name("name two") \
            .set_institution("institution") \
            .set_owner("owner") \
            .set_investment("investment") \
            .set_asset_class(AssetClass.NONE) \
            .set_account_type(AccountType.LIABILITY) \
            .set_update_frequency(3) \
            .build()
        timestamp = EpochDateConverter().date_to_epoch() - 7 * Constants.SECONDS_PER_DAY
        account_one.import_snapshot(timestamp, 100)
        account_two.import_snapshot(timestamp, 100)
        self.portfolio.import_account(account_one)
        self.portfolio.import_account(account_two)
        self.assertEqual(self.portfolio.outdated_liabilities(), [account_two])

    def test_it_returns_no_institutions_if_there_are_no_accounts_in_a_portfolio(self):
        self.assertEqual(self.portfolio.institutions(), [])

    def test_it_returns_one_institution(self):
        account = AccountBuilder().set_name("name one") \
            .set_institution("institution") \
            .set_owner("owner") \
            .set_investment("investment") \
            .build()
        self.portfolio.import_account(account)
        self.assertEqual(self.portfolio.institutions(), ["institution"])

    def test_it_returns_two_institutions(self):
        account_one = AccountBuilder().set_name("name one") \
            .set_institution("institution 1") \
            .set_owner("owner") \
            .set_investment("investment") \
            .build()
        account_two = AccountBuilder().set_name("name two") \
            .set_institution("institution 2") \
            .set_owner("owner") \
            .set_investment("investment") \
            .build()
        self.portfolio.import_account(account_one)
        self.portfolio.import_account(account_two)
        self.assertTrue("institution 1" in self.portfolio.institutions())
        self.assertTrue("institution 2" in self.portfolio.institutions())

    def test_it_does_not_return_duplicate_institutions(self):
        account_one = AccountBuilder().set_name("name one") \
            .set_institution("inst") \
            .set_owner("owner") \
            .set_investment("investment") \
            .build()
        account_two = AccountBuilder().set_name("name two") \
            .set_institution("inst") \
            .set_owner("owner") \
            .set_investment("investment") \
            .build()
        self.portfolio.import_account(account_one)
        self.portfolio.import_account(account_two)
        self.assertEqual(self.portfolio.institutions(), ["inst"])
예제 #39
0
def main():
    
    # Calendar-Spread implementation example
            
    # default market environment
    market_env = MarketEnvironment()
    print(market_env)
    
    # options expirations
    T_short = "31-05-2020"
    T_long = "30-08-2020"
    
    # current underlying level
    S_t = market_env.get_S()

    # calendar-spread portfolio initialized (as empty portfolio)   
    calendar_spread_ptf = Portfolio(name="Calendar Spread Strategy")
    print(calendar_spread_ptf)
    
    # T_long-call
    Vanilla_Call_long = PlainVanillaOption(market_env, T=T_long, K=S_t)
    print(Vanilla_Call_long)

    # T_short-call
    Vanilla_Call_short = PlainVanillaOption(market_env, T=T_short, K=S_t)
    print(Vanilla_Call_short)

    # creation of Calendar-Spread portfolio strategy   
    calendar_spread_ptf.add_instrument(Vanilla_Call_long, 1)
    calendar_spread_ptf.add_instrument(Vanilla_Call_short, -1)    
    print(calendar_spread_ptf)
    
    # portfolio plotter instance
    calendar_spread_ptf_plotter = PortfolioPlotter(calendar_spread_ptf)
    
    # valuation date of the portfolio
    valuation_date = calendar_spread_ptf.get_t()
    print(valuation_date)
        
    # select dependency to plot as x-axis of the plot 
    for dependency_type in ["S", "K", "sigma", "r"]:
    
        # keyboard parameter and corresponding range to test
        x_axis_dict = options_x_axis_parameters_factory(calendar_spread_ptf, dependency_type)    

        # appropriate azimut angle for best viewing
        azimut_angle = get_azimut_angle(dependency_type)

        # select metrics to plot
        for plot_metrics in ["price", "PnL", "delta", "theta", "gamma", "vega", "rho"]:
            
            plot_details_flag = True if plot_metrics == "price" else False
    
            # time-parameter as a date-range of 5 valuation dates between t and T_short
            last_date = T_short if plot_metrics in ["price", "PnL"] else date_string_to_datetime_obj(T_short) - pd.Timedelta(days=1)
            multiple_valuation_dates = pd.date_range(start=valuation_date, 
                                                     end=last_date, 
                                                     periods=5)
            print(multiple_valuation_dates)
    
            # Bull-Spread price plot
            calendar_spread_ptf_plotter.plot(**x_axis_dict, t=last_date, plot_metrics=plot_metrics, 
                                             plot_details=plot_details_flag)
                
            # Plot at multiple dates
            calendar_spread_ptf_plotter.plot(**x_axis_dict, t=multiple_valuation_dates, plot_metrics=plot_metrics)
        
            # Surface plot
            calendar_spread_ptf_plotter.plot(**x_axis_dict, t=multiple_valuation_dates, 
                                             plot_metrics=plot_metrics, surf_plot=True)
        
            # Surface plot (rotate) - Underlying value side
            calendar_spread_ptf_plotter.plot(**x_axis_dict, t=multiple_valuation_dates, 
                                             plot_metrics=plot_metrics, surf_plot=True, 
                                             view=(0,azimut_angle["x-axis side"]))
        
            # Price surface plot (rotate) - Date side
            calendar_spread_ptf_plotter.plot(**x_axis_dict, t=multiple_valuation_dates, 
                                             plot_metrics=plot_metrics, surf_plot=True, 
                                             view=(0,azimut_angle["Date side"]))
예제 #40
0
class PortfolioHandler(object):
    def __init__(self, events_queue, cash, quote_data, order_sizer, risk_manager):
        self.events_queue = events_queue
        self.cash = cash
        self.quote_data = quote_data
        self.order_sizer = order_sizer
        self.risk_manager = risk_manager
        self.portfolio = Portfolio(quote_data, cash)

    def update_signal(self):
        pass

    def generate_simple_order(self, signal):
        order = None

        symbol = signal.symbol
        direction = signal.signal_type
        strength = signal.strength

        # mkt_quantity = floor(100 * strength)
        # cur_quantity = self.current_positions[symbol]
        # order_type = 'MKT'

        # if direction == 'LONG' and cur_quantity == 0:
        #     order = Order(symbol, order_type, mkt_quantity, 'BUY')
        # if direction == 'SHORT' and cur_quantity == 0:
        #     order = Order(symbol, order_type, mkt_quantity, 'SELL')

        # if direction == 'EXIT' and cur_quantity > 0:
        #     order = Order(symbol, order_type, abs(cur_quantity), 'SELL')
        # if direction == 'EXIT' and cur_quantity < 0:
        #     order = Order(symbol, order_type, abs(cur_quantity), 'BUY')
        return order

    def _prelim_order_from_signal(self, signal_event):
        return PrelimOrder(signal_event.instrument, signal_event.side, signal_event.order)

    def _put_orders_on_queue(self, order_events):
        for order in order_events:
            # order.time_stamp = dt.datetime.utcnow()
            self.events_queue.put(order)

    def handle_signal(self, signal_event):
        prelim_order = self._prelim_order_from_signal(signal_event)
        prelim_order_sized = self.order_sizer.size_order(prelim_order)
        order_events = self.risk_manager.check_orders(self.portfolio, prelim_order_sized)
        self._put_orders_on_queue(order_events)

    def handle_fill(self, fill_event):
        self.update_portfolio(fill_event)

    def update_portfolio(self, fill_event):
        side = fill_event.side
        instrument = fill_event.instrument
        size = fill_event.size
        price = fill_event.price
        commission = fill_event.commission

        # Create or modify the position from the fill info
        self.portfolio.transact_position(side, instrument, size, price, commission)

    def update_portfolio_value(self):
        self.portfolio._update_portfolio()
def main():

    #
    # portfolio instantiation example
    #

    # if np_output is True, the output will be np.ndarray, otherwise pd.DataFrame
    np_output = False  # True

    # default market environment
    market_env = MarketEnvironment(t="01-06-2020")
    print(market_env)

    # underlying values to test
    S_vector = [60, 90, 120]
    print("S_vector: {}\n".format(S_vector))

    # options maturities
    T_call = "31-12-2020"
    T_put = "30-06-2021"  # T_call

    # choose the kind of time-parameter to use: either a date ('date') or a
    # time-to-maturity ('ttm'). Time-to-maturity time parameter is not allowed
    # for multi-horizon portfolios.
    time_parameter = 'date'  # 'ttm'

    # get time parameter
    t_range = get_time_parameter(market_env,
                                 end_date=min(T_call,
                                              T_put,
                                              key=date_string_to_datetime_obj),
                                 periods=5,
                                 kind=time_parameter,
                                 multi_horizon_ptf=T_call != T_put)

    # options strikes
    K_put = 80
    K_call = 110

    # portfolio options positions
    call_pos = 2
    put_pos = -5

    #
    # Step 0: empty portfolio initialized
    #

    ptf = Portfolio()
    print(ptf)

    #
    # Step 1: adding 2 long plain-vanilla call contracts
    #

    # plain-vanilla call option
    call = PlainVanillaOption(market_env, K=K_call, T=T_call)
    print(call)

    # adding contract to portfolio
    ptf.add_instrument(call, call_pos)
    print(ptf)

    # metrics to compare
    for metrics in ["price", "PnL", "delta", "theta", "gamma", "vega", "rho"]:

        # portfolio metrics
        ptf_metrics = getattr(ptf, metrics)(S=S_vector,
                                            t=t_range,
                                            np_output=np_output)
        print("\nPortfolio {}:\n{}".format(metrics, ptf_metrics))

        # verification with benchmark metrics
        call_metrics = getattr(call, metrics)(S=S_vector,
                                              t=t_range,
                                              np_output=np_output)
        benchmark_metrics = call_pos * call_metrics
        print("\nBenchmark {}:\n{}".format(metrics, benchmark_metrics))

        # check effective match
        diff = (ptf_metrics - benchmark_metrics).astype('float')
        num_nonzero_diff = np.count_nonzero(diff) - np.isnan(diff).sum().sum()
        exact_match = True if num_nonzero_diff == 0 else False
        print(
            "\nIs replication exact (NaN excluded)? {}\n".format(exact_match))

    #
    # Step 2: adding 5 short plain-vanilla put contracts
    #

    # plain-vanilla put option
    put = PlainVanillaOption(market_env, option_type="put", K=K_put, T=T_put)
    print(put)

    # adding contract to portfolio
    ptf.add_instrument(put, put_pos)
    print(ptf)

    # metrics to compare
    for metrics in ["price", "PnL", "delta", "theta", "gamma", "vega", "rho"]:

        # portfolio metrics
        ptf_metrics = getattr(ptf, metrics)(S=S_vector,
                                            t=t_range,
                                            np_output=np_output)
        print("\nPortfolio {}:\n{}".format(metrics, ptf_metrics))

        # verification with benchmark metrics
        call_metrics = getattr(call, metrics)(S=S_vector,
                                              t=t_range,
                                              np_output=np_output)
        put_metrics = getattr(put, metrics)(S=S_vector,
                                            t=t_range,
                                            np_output=np_output)
        benchmark_metrics = call_pos * call_metrics + put_pos * put_metrics
        print("\nBenchmark {}:\n{}".format(metrics, benchmark_metrics))

        # check effective match
        diff = (ptf_metrics - benchmark_metrics).astype('float')
        num_nonzero_diff = np.count_nonzero(diff) - np.isnan(diff).sum().sum()
        exact_match = True if num_nonzero_diff == 0 else False
        print(
            "\nIs replication exact (NaN excluded)? {}\n".format(exact_match))
예제 #42
0
from datetime import datetime
from portfolio.portfolio import Portfolio

portfolio = Portfolio(1)
start_date = datetime(2019, 11, 20)
end_date = datetime.now()
portfolio.chart(start_date, end_date, currency=Portfolio.RUB)
예제 #43
0
 def setUp(self):
     self.portfolio = Portfolio()