Example #1
0
def profit_percent_chart():
    portfolio = Portfolio(1)
    start_date = None
    end_date = datetime.now()
    time_range = TimeRange(start_date, end_date)
    cur = request.args.get('cur', Portfolio.RUB)

    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 = [100 * (data - cash_data) / cash_data,
               100 * (cbr_data - cash_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)
Example #2
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()
Example #3
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)
 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)
Example #5
0
def profit_chart():
    start_date = None
    end_date = datetime.now()
    time_range = TimeRange(start_date, end_date)
    cur = request.args.get('cur', Portfolio.RUB)
    broker = request.args.get('broker')
    portfolio = Portfolio(1, broker_id=int(broker) if broker else None)

    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)
    dividend_data = portfolio.get_dividend_history(time_range, currency=cur)
    commission_data = portfolio.get_commission_history(time_range,
                                                       currency=cur)
    samples = [data - cash_data, cbr_data - cash_data, dividend_data,
               commission_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)
 def __init__(self, portfolio=Portfolio()):
     self.portfolio = portfolio
     self.headers = [
         "Last Updated", "Institution", "Account", "Investment", "Owner",
         "Value"
     ]
     self.spacers = ["---", "---", "---", "---", "---", "---"]
Example #7
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()
Example #8
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)
Example #9
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)
Example #10
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
     )
Example #11
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())
Example #12
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())
 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)
Example #14
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"}
Example #15
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()
Example #16
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)
Example #17
0
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)
Example #18
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_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)
Example #20
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)
Example #21
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"]))
Example #22
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))
Example #23
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))
Example #24
0
    pairs = ["EURUSD", "GBPUSD"]

    # Create the OANDA market price streaming class
    # making sure to provide authentication commands
    prices = StreamingForexPrices(settings.STREAM_DOMAIN,
                                  settings.ACCESS_TOKEN, settings.ACCOUNT_ID,
                                  pairs, events)

    # Create the strategy/signal generator, passing the
    # instrument and the events queue
    strategy = TestStrategy(pairs, events)

    # Create the portfolio object that will be used to
    # compare the OANDA positions with the local, to
    # ensure backtesting integrity.
    portfolio = Portfolio(prices, events, equity=equity, backtest=False)

    # Create the execution handler making sure to
    # provide authentication commands
    execution = OANDAExecutionHandler(settings.API_DOMAIN,
                                      settings.ACCESS_TOKEN,
                                      settings.ACCOUNT_ID)

    # Create two separate threads: One for the trading loop
    # and another for the market price streaming class
    trade_thread = threading.Thread(target=trade,
                                    args=(events, strategy, portfolio,
                                          execution, heartbeat))
    price_thread = threading.Thread(target=prices.stream_to_queue, args=[])

    # Start both threads
Example #25
0
    while True:
        try:
            event = events.get(False)
        except queue.Empty:
            pass
        else:
            if event.type == "TICK":
                strategy.calculate_signals(event)
                portfolio.update_portfolio(event)
            elif event.type == "SIGNAL":
                risk.size_position(event)
            elif event.type == "ORDER":
                execution.execute_order(event)

if __name__ == "__main__":

    events = queue.Queue()
    pairs = ['EURUSD']
    stream = DataStream("practice", ACCESS_TOKEN, ACCOUNT_ID, pairs, events)
    portfolio = Portfolio(stream, events)
    execution = OandaExecution("practice", ACCESS_TOKEN, ACCOUNT_ID, portfolio)
    risk = DefaultTestHandler(portfolio, events)
    strategy = TestStrategy(events)

    trade_thread = threading.Thread(
        target=trade, args=(execution, portfolio, risk, strategy, events))
    price_thread = threading.Thread(target=stream.stream_to_queue, args=[])

    trade_thread.start()
    price_thread.start()
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))
Example #27
0
 def setUp(self):
     self.portfolio = Portfolio()
Example #28
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"]))
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))