def run_step(loc_g_q=600,
             scale_g_q=31,
             loc_g_p=12.5,
             scale_g_p=0.07,
             loc_r_q=600,
             scale_r_q=31,
             loc_r_p=11.5,
             scale_r_p=0.07):
    #data = cd.create_test_data()
    data = cd.create_normal_data(loc_g_q=600,
                                 scale_g_q=31,
                                 loc_g_p=12.5,
                                 scale_g_p=0.07,
                                 loc_r_q=600,
                                 scale_r_q=31,
                                 loc_r_p=11.5,
                                 scale_r_p=0.07)
    generators, retailers = group(data)
    market = mk.Market(generators, retailers)
    prices = market.match()
    prices = np.array(prices).round(3)
    print(prices)
    final_price = (sum(prices) / len(prices)).round(3)
    print("final price:", final_price)
    generators_list = []
    retailers_list = []
    for i in generators:
        generators_list.append(i.price)
    for i in retailers:
        retailers_list.append(i.price)
    return final_price, generators_list, retailers_list
Ejemplo n.º 2
0
def command(argument):
    cmds = [["quit", "q"], ["restart", "r"], ["help", "h"], ["debug", "d"],
            ["shop"], ["inventory", "i"], ["status", "s"], ["terminal", "t"],
            ["exchange"], ["market"], ["equipment", "e"]]  # list of commands
    help = [
        "Quits the game", "Restarts", "Displays this help file",
        "Debug on or off", "Opens the legal store",
        "Takes invetory of your goods", "Updates the game state",
        "Opens the in game terminal", "Currency exchange",
        "The illegal market", "Displays equipment"
    ]
    print("\n")
    if argument in (cmds[0]):
        quit()
    elif argument in cmds[1]:
        print("Restarting the game...")
        start()

    elif argument in cmds[2]:
        print("Availible commands are:")
        print(tabulate({"Command": cmds, "Description": help}, headers="keys"))
        print("For most comands you can use the first letter as a shortcut")

    elif argument in cmds[3]:
        game.debug = (game.debug + 1) % 2
        print("Debug set to:", game.debug)

    elif argument in cmds[4]:
        game.shop.display_inventory(game)

    elif argument in cmds[5]:
        print(
            "You do not own anything. Try buying something in the shop or on the market."
        )

    elif argument in cmds[6]:
        pass  #just updates the game

    elif argument in cmds[7]:
        print("Not yet implemented.")
        # will open a 'terminal'

    elif argument in cmds[8]:
        exchange()

    elif argument in cmds[9]:
        market.Market()
    elif argument in cmds[10]:
        if len(game.equipment) > 1:
            print(tabulate(game.equipment))
            print(
                "Here you will be able to use your items (as soon as it is implemented)."
            )
        else:
            print(
                "You have no equipment at the moment. Try shopping for something."
            )
    else:
        print("Sorry, command not found :(")
Ejemplo n.º 3
0
def instantiatemarkets(marketdata):
    global coins
    global markets
    window.txtdebug.insert(tk.END, "Creating Market Objects ...\r\n")
    imarkets = 0
    ibasecurrencies = 0
    for item in marketdata:
        # json variables below
        status = item.get("Status")
        basesymbol = item.get("BaseSymbol")
        mintrade = item.get("MinimumTrade")
        maxtrade = item.get("MaximumTrade")
        maxprice = item.get("MaximumPrice")
        symbol = item.get("Symbol")
        maxbasetrade = item.get("MaximumBaseTrade")
        label = item.get("Label")
        currency = item.get("Currency")
        statusmsg = item.get("StatusMessage")
        tradefee = item.get("TradeFee")
        minprice = item.get("MinimumPrice")
        marketid = item.get("Id")
        basecurrency = item.get("BaseCurrency")
        minbasetrade = item.get("MinimumBaseTrade")
        # Instantiate a market
        newmarkobj = market.Market(
            status,
            basesymbol,
            mintrade,
            maxtrade,
            maxprice,
            symbol,
            maxbasetrade,
            label,
            currency,
            statusmsg,
            tradefee,
            minprice,
            marketid,
            basecurrency,
            minbasetrade,
        )
        markets[label] = newmarkobj
        imarkets = imarkets + 1
        # Mark the coin objects which represent base trading markets.
        if not coins[basesymbol].IsBaseCurrency:
            # Make it so!
            coins[basesymbol].IsBaseCurrency = True
            ibasecurrencies = ibasecurrencies + 1
            # Update GUI
            window.lstbasemarkets.insert(tk.END, coins[basesymbol].Symbol)
    # Let us know
    window.txtdebug.insert(
        tk.END,
        str(imarkets) + " Markets Instantiated\r\n" + str(ibasecurrencies) +
        " New Base Currencies Identified.\r\n")
    window.txtdebug.see(tk.END)
Ejemplo n.º 4
0
 def __init__(self):
     print "Creating BTC-e trader"
     self.btce_trader = btcetrade.BTCeTrader(configure.btc_e_key,
                                             configure.btc_e_secret)
     #self.bitstamp_trader = bitstampsetup.BitStampTicker()
     print "Creating Bitfinex trader"
     self.bitfinex_trader = bitfinextrade.BitfinexTrader(
         configure.bitfinex_key, configure.bitfinex_secret)
     print "Creating market for btc-usd"
     self.current_market = market.Market()
Ejemplo n.º 5
0
 def __init__(self):
     self.server = None
     self.timer = None
     self.world = world.StarSystem()
     self.market = market.Market(self.world)
     self.warden = warden.Warden()
     self.state = LAUNCHING
     self.next_game_time = datetime.datetime.now() \
         + datetime.timedelta(seconds=5)
     self.pregame_delay = 5
     self.tick = 0
     self.tick_length = 1500
     self.players = {}
 def init(self, sid, eid_prefix, start, step_size, debug=False):
     if start is not None:
         self.start_datetime = dt.datetime.strptime(start,
                                                    '%d/%m/%Y - %H:%M:%S')
         self.step_size = step_size
         self.debug = debug
         self.market = market.Market(energy=1.0e3,
                                     max_kwh=5.0,
                                     grid_from_buy_value=0.71504,
                                     grid_to_sell_value=0.5 * 0.71504,
                                     start_datetime=self.start_datetime)
         self.completed_transactions = list()
     if eid_prefix is not None:
         self.eid_prefix = eid_prefix
     return self.meta
Ejemplo n.º 7
0
    def __init__(self, dbsession):
        self.dbsession = dbsession

        self.markets = []
        self.markets_hash = {}
        self.markets_hash_reverse = {}

        # Create a market for each pair of assets
        self.assets = dbsession.query(model.Asset).order_by(model.Asset.name)
        for combo in itertools.combinations(self.assets, 2):
            asset1 = combo[0]
            asset2 = combo[1]
            newmarket = market.Market(self.exchange_payment, asset1, asset2)
            self.markets.append(newmarket)
            self.markets_hash[(str(asset1.name), str(asset2.name))] = newmarket
            self.markets_hash_reverse[(str(asset2.name),
                                       str(asset1.name))] = newmarket

        self.order_num = ordernum_generator(69105)
Ejemplo n.º 8
0
def main(SYMBOL, UNIT, COUNT, PERIOD):
    args = get_args()
    assert args.partition > 0, 'The data must be partitioned!'

    m = market.Market(symbol=SYMBOL, unit=UNIT, count=COUNT, period=PERIOD)
    '''
    m = market.Market(symbol=args.symbol, unit=args.unit,
                      count=args.count, period=args.period)
    '''
    features = m.set_features(partition=1)
    if args.long is not None:
        features = m.set_long_features(features,
                                       columns_to_set=args.long,
                                       partition=args.partition)

    targets = market.set_targets(features, delta=args.delta)
    features = features.drop(['close'], axis=1)

    model = market.setup_model(features[:-1],
                               targets,
                               model_type=args.model.lower(),
                               seed=args.seed,
                               n_estimators=args.trees,
                               n_jobs=args.jobs)

    next_date = features.tail(
        1)  # Remember the entry we didn't train?  Predict it.

    trends = model._predict_trends(next_date)
    # print('Predicted Trend: {0}'.format(market.target_code_to_name(trends[0])))

    if args.proba:
        probas = model._predict_probas(next_date)
        print('Probability: {0}'.format(probas[0]))
    if args.proba_log:
        logs = model._predict_logs(next_date)
        print('Log Probability: {0}'.format(logs[0]))

    return market.target_code_to_name(trends[0])
Ejemplo n.º 9
0
}


def get_parameters():
    return parameters


data = get_parameters()

config = config.Config(**data['config'])
energy_sources = [
    energy_source.EnergySource(**kwargs) for kwargs in data['energy_sources']
]
for ess in energy_sources:
    ess.tuning_parameter_fit()
markets = [market.Market(**kwargs) for kwargs in data['markets']]
mpc = mpc_solver.MPCSolver(config=config,
                           markets=markets,
                           energy_sources=energy_sources)

# Fake run
cc = cyclic_coordinate.CyclicCoordinate(markets,
                                        mpc, [10, 10],
                                        really_run=False)
solutions_fake = cc.Algo5()
print("totl: " + str(len(solutions_fake)))

cc = cyclic_coordinate.CyclicCoordinate(markets, mpc, [10, 10])
solutions = cc.Algo5()
print(solutions[0])
# pe = pareto.ParetoEfficient(solutions)
Ejemplo n.º 10
0
import market

import requests
import bs4 as bs
import csv
import sys

marketAPI = market.Market()
graphicsCardAvgPrices = []

# event loop like a true programmer
while True:
    cycleWeightedAvg = 0
    cycleWeightedSum = 0
    toCsv = []

    # loop over first three pages of ebay graphics card searches
    for i in range(1, 3):
        ebayUrl = "https://www.ebay.com/sch/i.html?_from=R40&_nkw=graphics+card&_sacat=0&_pgn=" + str(
            i)
        req = requests.get(ebayUrl)
        data = req.text
        soup = bs.BeautifulSoup(data, features="lxml")

        # get all of the item groupboxes
        listings = soup.find_all('li', attrs={'class': 's-item'})

        # go over the listings and get the prices for each one that has a title
        for listing in listings:
            prodName = ""
            for name in listing.find_all('h3',
Ejemplo n.º 11
0
__author__ = 'sangchae'

import pandas as pd
import pandas.io.data as web
from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.finance import candlestick_ohlc
from matplotlib.dates import date2num
import bollingerband, envelope, golden, menu, market

test = 1

if __name__ == "__main__":
    # below contents will belong to another file, menu.py
    me = menu.Menu()

    # selelct what you want to do
    sel_menu = me.menu_decide(test)

    # select what you want to see the result of the simulation
    mar = market.Market(test)

    # select starting date and ending date
Ejemplo n.º 12
0
number_of_issues = 10  # how many issues we create every day
funder_starting_funds = 1000000  # how much money the funder starts with
worker_starting_funds = 0  # how much money a worker starts with
simulation_time = 3  # how many days to simulate
print(" [DONE]")

# Step 2: load issue tracker
print("load issue tracker", end="")
sys.stdout.flush()
tracker = issuetracker.IssueTracker()
print(" [DONE]")

# Step 2: load market
print("load futures trading market", end="")
sys.stdout.flush()
bmx = market.Market()
print(" [DONE]")

# Step 3: instantiate people (agents)
print("instantiate agents", end="")
sys.stdout.flush()
funder = person.PTrivialCase1Funder("funder", tracker, bmx)
funder.set_money(funder_starting_funds)
list_of_workers = []  # array to store all workers
for w in range(number_of_workers):
    new_worker = person.PTrivialCase1Worker("worker" + str(w), tracker, bmx)
    new_worker.set_money(worker_starting_funds)
    list_of_workers.append(new_worker)
    # print(list_of_workers)
print(" [DONE]")
Ejemplo n.º 13
0
        i += 1
        j += 1
    return x_list, xi


######### ******** MAIN ****** #########
if __name__ == '__main__':

    prod = {"id": "BTC-USD", "display_name": "BTC-USD"}

    #CBPRO
    class gdax:
        name = "CBPRO"

    m_cb = market.Market(product=prod, exchange=gdax)
    m_cb._import_historic_candles(local_only=True)
    m_cb._calculate_historic_indicators()
    m_cb._process_historic_strategies()

    print("Model init complete, training starts.. \n")
    indicator_list = m_cb.get_indicator_list()
    strategies_list = m_cb.get_strategies_list()
    x_cb_list = create_x_list(indicator_list, strategies_list)

    y_cb_list = create_y_list(x_cb_list)

    #Binance
    class bnc:
        name = "binance"
Ejemplo n.º 14
0
        a = a['prices']
        a.pop()
        plt.plot(a)
        plt.show()
    print("end")


if __name__ == '__main__':
    print("Hello")
    running = Value('b', True)
    maxRequests = 4
    print('Initialization of the weather')
    a = Array('f', range(3))
    w = weather.Weather(a, running, 1)
    q = Queue(maxRequests)
    n = 12
    pol = CVOUKIVOI
    h = Process(target=homes.homes, args=(a, q, running, n, pol))
    m = market.Market(q, running, 2)
    m.start()
    w.start()
    h.start()
    print("gogogo")
    if input("Press any key") is not None:
        running.value = False
        print('STOPP')
    w.join()
    h.join()
    m.join()
    graph()