Пример #1
0
def simulate(tickers, baseline, start, end, cost):
    if baseline not in tickers:
        tickers += [baseline]

    dates = pd.date_range(start, end)
    data = process.Pipe(
        process.Baseline(baseline),
        process.FillMissing(),
        process.Range(dates),
    ).process(reader.CsvReader().read_column(tickers, ColumnName.ADJCLOSE))

    simulator = Simulator(data, 252)
    allocations = []
    for ticker in tickers:
        allocations += [Allocation(ticker, 1)]
    sim = process.Merge().process(
        # simulator.run(HoldMoney(cost), "Hold money"),
        simulator.run(HoldAllocation(cost, [Allocation(baseline, 1)]),
                      "Hold only baseline"),
        simulator.run(MonthlyRebalance(HoldAllocation(cost, allocations)),
                      "Hold equal allocation + mrb"),
        simulator.run(
            MonthlyRebalance(
                OptimizerAllocation(
                    cost,
                    trade.data.optimize.FitLine(
                        trade.data.optimize.ReversSharpeRatio(), False))),
            "Optimizer allocation + mrb"))
    print(sim)
    plot.Plot(plot.Graph()).process(sim)
Пример #2
0
def analize(tickers, start, end, baseline, window, predict, test_size):
    dates = pd.date_range(start, end)
    stock = process.ProcessLine([
        process.Baseline(baseline),
        process.FillMissing(),
        process.Range(dates)
    ]).process(reader.CsvReader().read_stock(tickers, [Column.Name.ADJCLOSE]))

    ac_data = stock.column(Column.Name.ADJCLOSE)
Пример #3
0
def value(allocation_set, date=None):
    date_filter = process.Tail(1)
    if date is not None:
        date_filter = process.Range(pd.date_range(date, date))
    tickers = allocation_set.data.keys()

    data = process.Pipe(
        process.FillMissing(),
        date_filter,
    ).process(reader.CsvReader().read_column(tickers, ColumnName.ADJCLOSE))

    value = process.PortfolioSetValue(allocation_set).process(
        data).iloc[0]['Value']
    print("Portfolio value: ", value)
    return value
Пример #4
0
def portfolio(allocations, baseline, start, end, stat):
    tickers = [allocation.ticker for allocation in allocations]
    dates = pd.date_range(start, end)

    for allocation in allocations:
        print(allocation)

    data = process.Pipe(process.Baseline(baseline), process.FillMissing(),
                        process.Range(dates)).process(
                            reader.CsvReader().read_column(
                                tickers, ColumnName.ADJCLOSE))

    port_data = process.PortfolioSetValue(
        trade.type.AllocationSet(allocations)).process(data)

    if stat:
        statistic.Print().process(port_data)
    plot.Plot(plot.Graph()).process(port_data)
Пример #5
0
def optimize(tickers, baseline, start, end, cost, short, stat, json_path):
    if baseline not in tickers:
        tickers += [baseline]

    dates = pd.date_range(start, end)
    data = process.Pipe(
        process.Baseline(baseline),
        process.FillMissing(),
        process.Range(dates),
    ).process(reader.CsvReader().read_column(tickers, ColumnName.ADJCLOSE))
    allocations = trade.data.optimize.FitLine(
        trade.data.optimize.ReversSharpeRatio(), short).run(data)

    allocation_set = process.PortfolioSet(allocations, cost).process(data)
    print("Risk and return optimized")
    print(allocation_set)
    value = process.PortfolioSetValue(allocation_set).process(
        data[-1:]).iloc[0]['Value']
    print("Portfolio value: ", value)
    print("Parts")
    for allocation in allocations:
        print(allocation)

    if json_path:
        with open(json_path, "w") as json_file:
            json.dump(allocation_set.data, json_file, indent=4)

    data = process.Pipe(
        process.Split(
            process.Normalize(),
            process.Portfolio(allocation_set.get_list()),
        ), process.Merge()).process(data)

    if stat:
        process.statistic.Print().process(data)
    process.Pipe(process.Filter([baseline, 'Portfolio']),
                 plot.Plot(plot.Graph())).process(data)
Пример #6
0
def plot_tickers(tickers, baseline, window, start, end):
    dates = pd.date_range(start, end)

    data, norm_data, daily_return = process.Pipe(
        process.FillMissing(), process.Range(dates),
        process.Split(process.Pass(), process.Normalize(),
                      process.DailyReturn())).process(
                          reader.CsvReader().read_column(
                              tickers + [baseline], ColumnName.ADJCLOSE))

    root_dir = os.path.dirname(os.path.realpath(__file__))
    plot_dir = os.path.join(root_dir, "plots")
    if not os.path.exists(plot_dir):
        os.makedirs(plot_dir)

    plot_path = os.path.join(plot_dir, "Market.pdf")
    plot.PdfPlot(
        plot_path, plot.DfPlotter(norm_data, plot.Graph()),
        plot.DfPlotter(daily_return,
                       plot.Histogram(baseline=baseline))).plot()

    for ticker in tickers:
        plot_path = os.path.join(plot_dir, "{}.pdf".format(ticker))

        t_data, t_daily_return, tb_daily_return = process.Parallel(
            process.Filter([ticker]), process.Filter([ticker]),
            process.Filter([ticker, baseline
                            ])).process([data, daily_return, daily_return])

        bands = process.Pipe(
            process.Split(
                process.Pass(),
                process.Pipe(
                    process.TickerSuffix("_mov_avg({})".format(window)),
                    process.MovingAverage(window)),
                process.Pipe(
                    process.BollingerBands(window),
                    process.Parallel(
                        process.TickerSuffix("_upper_bb({})".format(window)),
                        process.TickerSuffix("_lower_bb({})".format(window))),
                    process.Merge())), process.Merge(),
            process.Tail(window * 3)).process(t_data)

        avgs = process.Pipe(
            process.Split(
                process.Pass(),
                process.Pipe(
                    process.TickerSuffix("_mov_avg({})".format(window / 2)),
                    process.MovingAverage(window / 2)),
                process.Pipe(
                    process.TickerSuffix("_mov_avg({})".format(window / 4)),
                    process.MovingAverage(window / 4))), process.Merge(),
            process.Tail(window * 3)).process(t_data)

        macd = process.Pipe(
            process.Macd(window),
            process.Parallel(process.TickerSuffix("_emad({})".format(window)),
                             process.TickerSuffix("_macd({})".format(window))),
            process.Merge(), process.Tail(window * 3)).process(t_data)

        rsi = process.Pipe(process.RelativeStrengthIndex(window),
                           process.TickerSuffix("_rsi({})".format(window)),
                           process.Merge(),
                           process.Tail(window * 3)).process(t_data)

        st_daily_return = process.Tail(window * 3).process(t_daily_return)

        plot.PdfPlot(
            plot_path,
            plot.DfPlotter(bands, plot.Graph(title="Stock with bands")),
            plot.DfPlotter(avgs, plot.Graph(title="Stock with averages")),
            plot.DfPlotter(macd, plot.Graph(title="MACD")),
            plot.DfPlotter(rsi, plot.Graph(title="RSI")),
            plot.DfPlotter(st_daily_return,
                           plot.Graph(title="Daily return", ylabel="Return")),
            plot.DfPlotter(t_daily_return, plot.Histogram()),
            plot.DfPlotter(tb_daily_return, plot.Scatter(baseline))).plot()