def __init__(self, loss_tolerance, liquid_assets=0, invested_assets=0): self.assets = Assets(liquid_assets, invested_assets) self.price = Prices() self.price_watcher = PriceWatcher(self) self.initial_investment = None self.loss_tolerance = loss_tolerance self.loss_tolerance_price = None self.gain_threshold_met = False self.assets_are_liquid = True self.is_trading = True self.first_trade = True
def __init__(self, wallet, ticker=None, strategy=None, start_date=None, mode=MODE_SIMULATED): self._on_off = True self._ticker = ticker self._strategy = strategy self._wallet = wallet self._prices = Prices(self._ticker) if start_date != None: self._prices.setDatePoint(start_date) self._mode = mode
def __init__(self, window=None): wrapper.EWrapper.__init__(self) client.EClient.__init__(self, wrapper=self) #QtWidgets.QThread.__init__(self, None) self.reqMarketDataType( wrapper.MarketDataTypeEnum.DELAYED) #Use delayed data self.nextValidOrderId = 1 self.permId2ord = {} self.req_to_table_row = {} self.tracked_names = {} self.account_details = {} self.positions = {} self.open_orders = {} if window: self.window = window self.prices_history = Prices() self.portfolio_value_hist = {} self.req_to_strategy = {} self.strategies = {}
def getCheesePrice(save_to_db=False, check_price=False): """ Залезает на сайт parmezan.ru и вытаскивает оттуда цены""" cheesePriceId = { "Фестивальный": "fest_24-price", "Истринский": "ber_1-price", "Винный": "vai_3-price", "Медовый": "med_23-price", "Пивной": "bir_5-price", "Тирольский": "tirol_22-price", "Пошехонский": "posh_76-price", "Колмогоровский": "kolmo_15-price", "Золотой рубль": "gold_16-price", "Губернаторский": "gub_6-price", "Красногорский": "krest_17-price", "Свежий для жарки": "sve_7-price" } url = "https://parmezan.ru/Zakaz" res = requests.get(url) page = res.text soup = BeautifulSoup(page, 'html.parser') cheesePrice = {} for k, v in cheesePriceId.items(): if soup.find(id=v) is not None: cheesePrice[k] = soup.find(id=v).text.strip() if save_to_db: p = Prices(prices_db) p.create_tab() current_date = datetime.today().strftime("%d-%m-%Y") all_dates = list(set([x[0] for x in p.show_dates()])) if current_date not in all_dates: for k, v in cheesePrice.items(): p.addprice(cheesePriceId[k], k, v, current_date) print("add to db") else: print(f"На {current_date} уже загружены цены") return cheesePrice
def setup(): conf = Configuration('..') prices_manager = Prices('prices', conf['se']) today = date.today() range_dates = ('2017-01-01', today.isoformat()) ckp_manager = CheckpointManager('checkpoint') data = ckp_manager.load_base() if data is not None: print('last checkpoint loaded') symbols = data['symbols'] all_data = data['all_data'] else: blacklist = set(['CAPU', 'PESA', 'PSUR', 'POLL']) symbols = conf.symbols() all_data = load_all_data(prices_manager, blacklist, symbols, range_dates) print('calculating returns') for data in all_data.values(): # TODO there must be a better way to do this returns = pd.DataFrame(data['Adj Close']).apply( lambda x: np.log(x) - np.log(x.shift())) data['Daily Return'] = returns state = { 'all_data': all_data, 'symbols': symbols, } ckp_manager.save_base(state) print("using dates [%s - %s]" % range_dates) # strategy = StrategyFindBestMA(ckp_manager) strategy = StrategyRandom01(ckp_manager) print(f'using strategy {type(strategy).__name__}') strategy.load(all_data.keys(), all_data) return (today, range_dates, conf, prices_manager, all_data, ckp_manager, strategy)
def send_updates(): p = Prices(prices_db) p.create_tab() current_date = datetime.today().strftime("%d-%m-%Y") day_before_current_date = datetime.today() - timedelta(1) day_before_current_date = day_before_current_date.strftime("%d-%m-%Y") message = p.check_price_change(day_before_current_date, current_date) if len(message) > 0: u = Users(users_db) u.create_tab() where_to_send = u.get_users_chatid_to_update() if len(where_to_send) > 0: where_to_send = [x[0] for x in where_to_send] for user_chat_id in where_to_send: send_message(user_chat_id, cheeze_token, message)
return np.exp(-1.0 * a) * payoff, np.mean(self.prices, axis=1) def getPullOption(self, recalculate=True): days = np.ceil(self.maturity_time * 365) T = np.linspace(0, 1, days) * (self.maturity_time) if recalculate: self.prices = self.simulateTrajectories() payoff = self.strike_price - np.mean(self.prices, axis=1) return np.exp(-1.0 * self.riskless_rate * T) * payoff, np.mean( self.prices, axis=1) if __name__ == "__main__": from prices import Prices netflix = Prices() netflix.load("../../test/data/NFLX.csv") S0 = netflix.getLastPrice() K = 310 T = 0.08333 r = 0.05 sigma = netflix.getVolatility() I = 10 european_option = EuropeanOptionPricing(S0, K, T, r, sigma, I) american_option = AmericanOptionPricing(S0, K, T, r, sigma, I) print("==Option Parameters==") print("Test data:", "../../test/data/NFLX.csv") print("Initial price:", S0) print("Strike price:", K) print("Maturity time:", T, "[year]")
# for i in xrange(3,50): # for j in xrange(1, i-1): # ip.setParams(j,i) # currentProfit = calculateProfit(ip) # if currentProfit > bestProfit: # bestProfit = currentProfit # bestParams = (j,i) # print "best profit is : ", currentProfit, " with params: ", bestParams # ip.setParams(bestParams[0], bestParams[1]) # calculateProfit(ip, True) try: myTrader = trader.Trader() coinStr = 'ltc' prices = Prices(coinStr + '_usd') interval = 1800 COIN_MIN = 1 DOLLAR_MIN = 10 emaPair = (8, 17) diffPerc = 1.003 def tradeIfShould(ip): timestamp = (int(time.time()) / 60) * 60 if timestamp in ip.timeline: current = ip.timeline[timestamp] else: current = ip.timeline[ip.getMostRecentTime()] firstKey = ip.getFirstAvgKey() secondKey = ip.getSecondAvgKey() info = myTrader.getInfo()
row_date = from_req_str(datum[0]) dates.append(row_date) cols = [float(x.replace(',', '')) for x in datum[1:]] prices_data.append(cols) prices = pd.DataFrame(data=prices_data, index=dates, columns=[ 'Open', 'Max', 'Min', 'Close', 'Adj Close', 'Volumen monto', 'Volumen nominal' ]) prices.index.name = 'Date' if cur_prices is None: cur_prices = prices else: cur_prices = cur_prices.append(prices, sort=True) cur_prices.drop_duplicates(keep='last', inplace=True) prices_manager.save(symbol, cur_prices) if __name__ == '__main__': conf = Configuration('..') downloader = Downloader('cache') prices_manager = Prices('prices', conf['se']) _setup_symbols() _update_prices()
def main(): prices = Prices() weather = Weather() def wake_up_routine(number): if number == 1: w1 = Weather() send_message = "God morgen Tommy! I dag kan du forvente følgende temperaturer " + w1.min_max_weather( ) channel = "raspberry-pi" slack_client.api_call("chat.postMessage", channel=channel, text=send_message) audio = AudioPlayer() audio.music_then_radio("random", 10, 300, "random") def send_bitcoin_price(channel): price_bit = prices.get_bitcoin_price() send_msg_bit = "Den nåværende prisen for Bitcoin er: " + price_bit[0] returns_msg_bit = "Din nåværende avkastning på Bitcoin er: " + price_bit[ 1] slack_client.api_call("chat.postMessage", channel=channel, text=send_msg_bit) slack_client.api_call("chat.postMessage", channel=channel, text=returns_msg_bit) def send_dogecoin_price(channel): price_dog = prices.get_dogecoin_price() send_msg_dog = "Den nåværende prisen for Dogecoin er: " + price_dog[0] # returns_msg_dog = "Din nåværende avkastning på Bitcoin er: " + price_dog[1] slack_client.api_call("chat.postMessage", channel=channel, text=send_msg_dog) # slack_client.api_call("chat.postMessage", channel=channel, text=returns_msg_dog) def send_litecoin_price(channel): price_ltc = prices.get_litecoin_price() send_msg_ltc = "Den nåværende prisen for Litecoin er: " + price_ltc[0] returns_msg_ltc = "Din nåværende avkastning på Litecoin er: " + price_ltc[ 1] slack_client.api_call("chat.postMessage", channel=channel, text=send_msg_ltc) slack_client.api_call("chat.postMessage", channel=channel, text=returns_msg_ltc) def morning_messages(): time = datetime.now().time() hour = str(time)[0:2] global sent if hour == "09" and not sent: morning_prices() morning_weather() sent = True if hour == "10" and sent: sent = False def morning_weather(): curr_weather = weather.min_max_weather().split() minimum = curr_weather[0] maximum = curr_weather[1] send_message = f"I dag kan du forvente temperaturer mellom {minimum} og {maximum}." channel = "raspberry-pi" slack_client.api_call("chat.postMessage", channel=channel, text=send_message) def morning_prices(): channel = "raspberry-pi" good_morning_msg = "God morgen Tommy! Håper du får en fin dag :)" slack_client.api_call("chat.postMessage", channel=channel, text=good_morning_msg) send_bitcoin_price(channel) send_dogecoin_price(channel) send_litecoin_price(channel) tokens = {} with open('configs.json') as json_data: tokens = json.load(json_data) slack_client = SlackClient(tokens.get("slack_bot_token")) alarm = Alarm() if slack_client.rtm_connect(auto_reconnect=True): print("Connected!") while True: morning_messages() try: messages = slack_client.rtm_read() except: print("Disconnected.") print("Reconnecting...") time.sleep(20) slack_client.rtm_connect() messages = slack_client.rtm_read() if alarm.alarm_active(): if alarm.check_alarm(): wake_up_routine(1) # print(messages) if messages: for message in messages: if message.get("subtype") is None and message.get( 'user') is not None and message.get( 'text' ) is not None and "BOT TEST" in message.get( 'text'): channel = message["channel"] send_message = "Responding to `BOT TEST` message sent by user <@%s>" % message[ "user"] slack_client.api_call("chat.postMessage", channel=channel, text=send_message) if message.get("subtype") is None and message.get( 'user') is not None and message.get( 'text') is not None and "audio" in message.get( 'text'): command = message.get('text') command_lst = command.split() command = " ".join(command_lst[1:]) au1 = AudioPlayer() au1.audio_handler(command) if message.get("subtype") is None and message.get( 'user') is not None and message.get( 'text' ) is not None and "weather_now" in message.get( 'text'): command = message.get('text') command_lst = command.split() command = " ".join(command_lst[1:]) weather = Weather() send_message = weather.weather_handler(command) channel = message["channel"] slack_client.api_call("chat.postMessage", channel=channel, text=send_message) if message.get("subtype") is None and message.get( 'user') is not None and message.get( 'text' ) is not None and "weather_min_max" in message.get( 'text'): weather = Weather() send_message = weather.min_max_weather() channel = message["channel"] slack_client.api_call("chat.postMessage", channel=channel, text=send_message) if message.get("subtype") is None and message.get( 'user') is not None and message.get( 'text' ) is not None and "set_alarm" in message.get( 'text'): command = message.get('text') command_lst = command.split() alarm.set_alarm(int(command_lst[1]), int(command_lst[2]), int(command_lst[3]), int(command_lst[4])) if message.get("subtype") is None and message.get( 'user' ) is not None and message.get( 'text' ) is not None and "get_bitcoin_price" in message.get( 'text'): send_bitcoin_price(message["channel"]) if message.get("subtype") is None and message.get( 'user' ) is not None and message.get( 'text' ) is not None and "get_dogecoin_price" in message.get( 'text'): send_dogecoin_price(message["channel"]) if message.get("subtype") is None and message.get( 'user' ) is not None and message.get( 'text' ) is not None and "get_litecoin_price" in message.get( 'text'): send_litecoin_price(message["channel"]) if message.get("subtype") is None and message.get( 'user' ) is not None and message.get( 'text' ) is not None and "get_crypto_price" in message.get( 'text'): channel = message["channel"] send_bitcoin_price(channel) send_dogecoin_price(channel) send_litecoin_price(channel) time.sleep(4) else: print("Connection Failed")
def main(): args, err = Protocol.receiveParameters(sys.argv[1:]) if err: Protocol.sendError("invalid arguments", args) return # prices will get the company's data prices = Prices() # Enter only if we will pricing with remote data if args["download_path"] != None: Protocol.sendStatus("starting download", args["code"]) # Use this CSV file in the load step. mkdir(args["download_path"]) args["filepath_data"] = prices.download(args["code"], args["start"], args["end"], args["download_path"], "Yahoo") Protocol.sendStatus("download ended", args["filepath_data"]) # Load a downloaded CSV file. Protocol.sendStatus("loading csv", args["filepath_data"]) prices.load(args["filepath_data"]) # Check if prices loaded the CSV correctly. if not prices.isLoaded(): Protocol.sendError("data not loaded") return # Check if data doesn't have any invalid value elif not prices.isValidData(): Protocol.sendStatus("cleaning data") # If there are any wrong value, try to fix it. fixed = prices.cleanData() # Otherwise, we can handle this data. if not fixed: Protocol.sendError("invalid csv format", args["filepath_data"]) return # Data is valid and is ready to process. else: Protocol.sendStatus("loaded", args["filepath_data"]) # Plot the prices #filename = prices.getPlot() json_plot, _ = Plotter.timeSeries(prices.data.Date, High=prices.data.High, Low=prices.data.Low, Close=prices.data.Close) Protocol.sendStatus("plot generated", json_plot) Protocol.sendStatus("setting simulation params") # Initial price S0 = prices.getLastPrice() Protocol.sendStatus("setting initial price", S0) # Strike price K = float(args["strike_price"]) Protocol.sendStatus("setting strike price", K) # Maturity time T = float(args["maturity_time"]) Protocol.sendStatus("setting maturity time", T) # Simulations I = int(args["simulations"]) Protocol.sendStatus("setting Monte Carlo simulations", I) # Riskless rate r = float(args["r"]) Protocol.sendStatus("setting riskless rate", r) # Here we will price the option Protocol.sendStatus("starting simulation") # Calculate Volatility sigma = prices.getVolatility() Protocol.sendStatus("using volatility", sigma) # using the correct option type if args["option_type"] == "EU": option = EuropeanOptionPricing(S0, K, T, r, sigma, I) Protocol.sendStatus("using European Option") elif args["option_type"] == "USA": option = AmericanOptionPricing(S0, K, T, r, sigma, I) Protocol.sendStatus("using American Option") else: # European is the default option Protocol.sendError("wrong option type", args["option_type"]) option = EuropeanOptionPricing(S0, K, T, r, sigma, I) Protocol.sendStatus("using European Option") args["option_type"] = "EU" # TODO ONLY BUY CALL Protocol.sendStatus("getting call option") results = option.getCallOption() """ if args["option"] == "call": Protocol.sendStatus("getting call option") result = option.getCallOption() elif args["option"] == "pull": Protocol.sendStatus("getting pull option") result = option.getPullOption() """ Protocol.sendStatus("simulation ended") # Build result if args["option_type"] == "EU": result_data = { "type": "EU", "result": { "payoff": results[0], "price": results[1], } } elif args["option_type"] == "USA": result_data = { "type": "USA", "result": { "plot_data": Plotter.americanOption(list(results[1]), list(results[0]))[1] } } Protocol.sendResult(json.dumps(result_data)) sys.stdout.flush()
from flask import Flask from flask import request from flask import Response from flask_sslify import SSLify from cheeseprice import getCheesePrice from mortgage import Mortgage from botutils import parse_message, send_message from tokens import gipo_token, cheeze_token from datetime import datetime, timedelta from prices import Prices from users import Users prices_db = "prices.sqlite3" users_db = "users.sqlite3" p = Prices(prices_db) p.create_tab() u = Users(users_db) u.create_tab() app = Flask(__name__) sslify = SSLify(app) @app.route('/', methods=['POST', 'GET']) def index(): return '<h1>Buongiorno!!!</h1>' @app.route('/gipo', methods=['POST', 'GET']) def gipo_handler():
eps = 0.0035 use_email = False phase = 'buy' pair = "ETH/USD" if len(sys.argv) == 1 else sys.argv[1].upper() + "/USD" conn = ccxt.kraken({ "apiKey" : secrets.publickey, "secret" : secrets.privatekey }) start_usd = conn.fetchBalance()['free'][pair[-3:]] start_coin = conn.fetchBalance()['free'][pair[:3]] w = Wallet(start_usd, start_coin, phase) prices = Prices(conn, pair, short_len, long_len) if use_email: em = Emailer(secrets.myaddress, secrets.mypassword) while True: if len(prices.prices) < prices.long_len: print("%i: Warming up..." % len(prices.prices)) prices.addCurrentPrice() time.sleep(SLEEP_SEC) continue prices.addCurrentPrice() prices.updateMA() if len(prices.prices) % 20 == 0: checkin(w, prices)