示例#1
0
文件: server.py 项目: diingyu/stock
def kdj():
    if request.method == 'POST':
        code = request.form['code']
    else:
        # code = request.args.get('code')
        return render_template('kdj.html')
    end_date = datetime.date.today()
    start_date = end_date - datetime.timedelta(days=30)
    end_date = end_date.strftime("%Y-%m-%d")
    start_date = start_date.strftime("%Y-%m-%d")
    stock = Stock(code, start_date=start_date, end_date=end_date)
    e, m = stock.get_data()
    if e == 1:  # error
        return m

    k, d, j = stock.kdj_sig(-7)  # 从过去7个交易日起算
    if j > 100:
        flash("卖!卖!卖!")
        return render_template('kdj_answer.html',
                               result="j=" + str(int(j)) + ", 可卖出!")
        # return "j=" + str(int(j)) + ", 可卖出!"
    elif j < 0:
        return "j=" + str(int(j)) + ", 可买入!"
    else:
        return "j=" + str(int(j)) + ", 不动!"
示例#2
0
    def set_highest_chosen(self):
        print(self.json_top_stocks.items())
        for key, value in self.json_top_stocks.items():
            if key == "data_set":
                self.list_top_stocks_json = value
                # print(self.list_top_stocks_json)
        for val in self.list_top_stocks_json:
            self.top_stock = Stock()
            is_applicable_stock = True
            for key, value in val.items():
                if key == 'symbol':
                    #if symbol cotains non-alphabetic characters, continue
                    if ("." in value):
                        print("value", value, "contains a .'")
                        is_applicable_stock = False
                        break
                    if ("\'" in value):
                        print("value", value, "contains a .'")
                        is_applicable_stock = False
                        break
                    self.top_stock.set_sym(value)
                if key == 'pchg':
                    self.top_stock.set_pchg(value)
                if key == 'pcls':
                    self.top_stock.set_pcls(value)
                if key == 'last':
                    self.top_stock.set_last(value)

            if (is_applicable_stock):
                self.list_top_stocks.append(self.top_stock)
示例#3
0
 def test_add_transaction_after_Stock_Object_creation(self):
     second_transaction = Transaction("Google", datetime.now(), self.buy,36.23,10)
     listOfTran = []
     listOfTran.append(self.testTran)
     testObj = Stock("IBM", listOfTran)
     testObj.add_transactions(second_transaction)
     self.assertEqual(len(testObj.transactions), 2)
class OrderFacade:
    def __init__(self):
        self.stock = Stock()
        self.shoppingCart = ShoppingCart()
        self.order = Order()
        self.shipment = Shipment()
        self.payment = Payment()

    def doOperation(self, name, value=''):
        if name == "вибрати":
            index = -1
            for item in self.stock.product.products:
                index += 1
                if item == value:
                    self.stock.selectStockItem(index)
        elif name == "добавити у кошик":
            self.shoppingCart.addItem(value)
        elif name == "замовлення":
            self.shoppingCart.addItem(value)
        elif name == "доставити":
            self.shipment.createShipment(value)
        elif name == "заплатити":
            if self.payment.verifyPayment(value):
                print("Підтвердження оплати")
                return True
            else:
                if input("Не існує картки, бажаєте зареєструвати одну?\n"
                         ) == "так":
                    self.payment.addCardDetails(value)
                    print("Підтвердження оплати")
                    return True
                else:
                    return False
        elif name == "поновити":
            self.shoppingCart.checkout()
示例#5
0
    def _handle_search(self):

        target_market_idx = self.target_market_combo_box.currentIndex()
        search_condition_idx = self.target_search_condition_combo_box.currentIndex()
        key = self.target_search_line_edit.text()

        if key == "":
            return

        self.found = None

        # 종목 코드로 검색한 경우.
        if search_condition_idx == SEARCH_CONDITION_CODE \
                and self.markets[target_market_idx].get_name(key) is not None:
            self.found = Stock(target_market_idx, key, self.markets[target_market_idx].get_name(key))

        # 종목 이름으로 검색한 경우.
        elif search_condition_idx == SEARCH_CONDITION_NAME \
                and self.markets[target_market_idx].get_code(key) is not None:
            self.found = Stock(target_market_idx, self.markets[target_market_idx].get_code(key), key)

        if self.found is None:
            self.target_search_result_line_edit.setText(NOT_EXIST_MESSAGE)
        else:
            self.target_search_result_line_edit.setText(self.found.code + " " + self.found.name)
示例#6
0
    def setUp(self):
        # Change the config value.
        Config.MINIMUM_AMOUNT_DATA = 4
        Config.DAYS_IN_YEAR = 1

        test_data = OrderedDict()
        test_data['2018-01-01'] = Decimal('100.00')
        test_data['2018-01-02'] = Decimal('102.00')
        test_data['2018-01-03'] = Decimal('104.00')
        test_data['2018-01-04'] = Decimal('108.00')
        test_data['2018-01-05'] = Decimal('110.00')
        stock1 = Stock(test_data, '1', 0)

        test_data = OrderedDict()
        test_data['2018-01-01'] = Decimal('200.00')
        test_data['2018-01-02'] = Decimal('202.00')
        test_data['2018-01-03'] = Decimal('206.00')
        test_data['2018-01-04'] = Decimal('208.00')
        test_data['2018-01-05'] = Decimal('210.00')
        stock2 = Stock(test_data, '2', 0)

        test_data = OrderedDict()
        test_data['2018-01-01'] = Decimal('300.00')
        test_data['2018-01-02'] = Decimal('309.00')
        test_data['2018-01-03'] = Decimal('318.00')
        test_data['2018-01-04'] = Decimal('327.00')
        test_data['2018-01-05'] = Decimal('336.00')
        stock3 = Stock(test_data, '3', 0)

        test_stock_dict = {'1': stock1, '2': stock2, '3': stock3}

        self.stock_db = StockDatabase(test_stock_dict)
示例#7
0
def load_stocks(stocks, start, end):
    start_time = time.time()
    session = DatabaseService.setup_db()
    # in_db = session.query(Stock).filter(Stock.ticker.in_(stocks)).filter(Stock.timestamp >= start).filter(Stock.timestamp <= end).all()

    # removed = []
    # for row in in_db:
    #     if row.ticker not in removed:
    #         stocks.remove(row.ticker)
    #         removed.append(row.ticker)

    if len(stocks) > 0:
        panel = Scraper.lookup(stocks, start, end)
        for date in panel.major_axis:
            for company in panel.minor_axis:
                frame = panel.loc[:, date, company]

                high = frame["High"]
                low = frame["Low"]
                open = frame["Open"]
                close = frame["Close"]
                vol = frame["Volume"]
                adj_close = frame["Adj Close"]
                s = Stock(company, high, low, open, close, vol, adj_close, date)
                if not s.is_nan():
                    session.add(s)
                    # print("{}: high[{}] low[{}] date[{}]".format(stock, hi, low, date))

        session.commit()
    end_time = time.time()
    print("Time taken to load stocks: %s seconds" % (end_time - start_time))
示例#8
0
    def setUp(self):
        # Change the config value.
        Config.MINIMUM_AMOUNT_DATA = 4

        test_data = OrderedDict()
        test_data['2018-01-09'] = Decimal('145.69')
        test_data['2018-01-08'] = Decimal('146.25')
        test_data['2018-01-07'] = Decimal('147.17')
        test_data['2018-01-06'] = Decimal('147.27')
        test_data['2018-01-05'] = Decimal('147.41')
        test_data['2018-01-04'] = Decimal('146.93')
        test_data['2018-01-03'] = Decimal('146.27')
        test_data['2018-01-02'] = Decimal('145.78')
        test_data['2018-01-01'] = Decimal('144.92')
        stock1 = Stock(test_data, '1', 0)

        test_data = OrderedDict()
        test_data['2018-01-09'] = Decimal('79.19')
        test_data['2018-01-08'] = Decimal('79.18')
        test_data['2018-01-07'] = Decimal('79.02')
        test_data['2018-01-06'] = Decimal('78.87')
        test_data['2018-01-05'] = Decimal('78.89')
        test_data['2018-01-04'] = Decimal('79.03')
        test_data['2018-01-03'] = Decimal('78.96')
        test_data['2018-01-02'] = Decimal('78.79')
        test_data['2018-01-01'] = Decimal('78.75')
        stock2 = Stock(test_data, '2', 0)

        test_stock_dict = {'1': stock1, '2': stock2}

        self.stock_db = StockDatabase(test_stock_dict)
示例#9
0
	def __init__(self, budget, symbol, period, live, debug, since, broker,  market, mylogger, email=False, daily=False,liquidate=False):
		self.data = None
		self.botname = "MMBot"
		self.budget = budget
		self.symbol = symbol
		self.period = int(period)
		self.daily = daily
		self.live = live
		self.debug = debug
		self.email = email
		self.since = since
		self.liquidate=liquidate
		self.buyriskfactor = 0.5
		self.sellriskfactor = 0.5
		self.signal = 0
		self.mylogger = mylogger
		self.market = market
		self.strategy = MMStrategy(mylogger)
		self.broker = broker
		self.stock = Stock(symbol, self.mylogger, self.broker)
		self.thread = threading.Thread(target = self.run_bot)
		self.BUY = -1
		self.SELL = 1
		self.HOLD = 0
		self.exit = False

		signal.signal(signal.SIGINT, self.sighandler)
示例#10
0
    def main(self):

        index = Index()
        stock = Stock()
        sise = Sise()

        average_per_business_category_dict = self.read_average_per_file()
        stock_item_list = stock.get_all_stock_item_list()

        print("종목명/PER/업종PER/상승률/상승하락/2019시초가/현재가/업종코드/업종설명")

        for stock_item in stock_item_list:
            stock_code = stock_item[0]
            per_pair = index.get_stock_item_per(stock_code)
            stock_item_per = per_pair[0].replace(",", "")
            business_average_per = per_pair[1].replace(",", "")

            if stock_item_per == '-' or business_average_per == '-':
                continue

            if float(stock_item_per) > float(business_average_per):
                continue

            increase_rate = sise.get_increase_rate_by_code(stock_code, None)

            if increase_rate is None:
                continue

            print(stock_item[1] + "/" + stock_item_per + "/" +
                  business_average_per + "/" + str(increase_rate[0]) + "/" +
                  increase_rate[1] + "/" + str(increase_rate[2]) + "/" +
                  str(increase_rate[3]) + "/" + stock_item[2] + "/" +
                  average_per_business_category_dict[stock_item[2]][1])
示例#11
0
class Trade():
    def __init__(self,funds):
        self.money = MoneyManage(funds)
        self.stock = Stock()

    #購入判定処理    
    def buyDecision(self,code,day):
        #始値を取得
        startPrice=self.stock.currentStartPrice(code,day)
        #終値を取得
        endPrice=self.stock.currentEndPrice(code,day)
        #標準偏差(10日間)を取得
        std=self.stock.singleStd(code,day,10)

        #始値から標準偏差を引いた分より終値が下回った場合購入
        if (startPrice-std) > endPrice: 
            buyDay = dateTools.dateNext(day)
            buyCount = 100
            buyPrice = self.stock.currentStartPrice(code,buyDay)
            self.money.buy(buyDay,code,buyPrice,buyCount,1)

    #売却判定処理    
    def sellDecision(self,day):
        #保有銘柄分処理を実施
        for key,value in self.money.stockHold().items():
            #現在株価を取得
            currentStockPrice = self.stock.currentStartPrice(key[1],day)

            #株価が購入時より10%値上がりした際に売却
            if int(value[0])*int(value[1])*1.1 < int(currentStockPrice) * int(value[1]):
                self.money.sell(key[0],key[1],currentStockPrice)
            #株価が購入時より10%値下がりした際に売却
            elif int(value[0])*int(value[1]) * 0.9 > int(currentStockPrice) * int(value[1]):
                self.money.sell(key[0],key[1],currentStockPrice)
示例#12
0
    def setUp(self):
        # Change the config value.
        Config.MINIMUM_AMOUNT_DATA = 4

        test_data = OrderedDict()
        test_data['2018-01-01'] = Decimal('101.00')
        test_data['2018-01-02'] = Decimal('102.00')
        test_data['2018-01-03'] = Decimal('103.00')
        stock1 = Stock(test_data, '1', 0)

        test_data = OrderedDict()
        test_data['2018-01-01'] = Decimal('200.00')
        test_data['2018-01-02'] = Decimal('202.00')
        test_data['2018-01-03'] = Decimal('206.00')
        test_data['2018-01-04'] = Decimal('208.00')
        test_data['2018-01-05'] = Decimal('210.00')
        stock2 = Stock(test_data, '2', 0)

        test_data = OrderedDict()
        test_data['2018-01-01'] = Decimal('300.00')
        test_data['2018-01-02'] = Decimal('303.00')
        test_data['2018-01-03'] = Decimal('306.00')
        test_data['2018-01-04'] = Decimal('309.00')
        stock3 = Stock(test_data, '3', 0)

        self.test_stock_dict = {'1': stock1, '2': stock2, '3': stock3}
示例#13
0
    def get_per_all_business_category(self):

        per_all_business_category_code_list = []

        stock = Stock()

        business_category_code_list = self.get_business_category_code()

        for business_category_code in business_category_code_list:
            business_code = business_category_code[0]
            description = business_category_code[1]

            stock_item_list = stock.get_all_stock_item_list()

            for stock_item in stock_item_list:

                if stock_item[2] == business_code:

                    per_pair = self.get_stock_item_per(stock_item[0])
                    business_category_per = (business_code, per_pair[1],
                                             description)
                    per_all_business_category_code_list.append(
                        business_category_per)
                    break

        return per_all_business_category_code_list
示例#14
0
 def setUp(self):
     test_data = OrderedDict()
     test_data['2018-01-01'] = Decimal('100.00')
     test_data['2018-01-02'] = Decimal('101.00')
     test_data['2018-01-03'] = Decimal('102.00')
     test_data['2018-01-04'] = Decimal('103.00')
     test_data['2018-01-05'] = Decimal('104.00')
     self.stock = Stock(test_data, '', 0)
示例#15
0
def modificar_compra(clave, valor):
    try:
        stock = Stock()
        stock = dbroot[clave]
        stock.cantidad = stock.cantidad + valor
        transaction.commit()
        return True
    except ValueError:
        return False
    def outPutStockData(self, code):
        s = Stock(atr=['20'], ma=['20'], index=code)

        # s = Stock(atr = ['20'], ma = ['20'])
        # s.setCode(code)
        # s.setFunc({'func':self.sss, 'funcName':'sss'})
        # s.create()

        s.outPutXML()
示例#17
0
def initialise():
    # Create Stock Objects
    # ToDo - Accept stock from other inputs ie files
    stockDic['TEA'] = Stock("TEA", "Common", 0, None, 100)
    stockDic['POP'] = Stock("POP", "Common", 8, None, 100)
    stockDic['ALE'] = Stock("ALE", "Common", 23, None, 60)
    stockDic['GIN'] = Stock("GIN", "Preferred", 8, 2, 100)
    stockDic['JOE'] = Stock("JOE", "Common", 13, None, 250)
    print("Stock intialsed")
示例#18
0
def test_random_split():
    record = Record({"c": .0, "h": .0, "l": .0, "o": .0, "t": 0, "v": 0})
    stock = Stock("SYMBOL")
    for i in range(10):
        stock.append_record(record)

    for i in range(1000):
        future_size = stock.random_split(2, 3)
        assert future_size >= 3
        assert stock.split_idx >= 2
示例#19
0
 def testContainsItem(self, type='dll'):
     stock = Stock(type)
     self.assertFalse(stock.containsItem(55))
     self.assertFalse(stock.containsItem("Pan Galactic Gargle Blaster"))
     self.assertTrue(stock.containsItem(WhiteChocolate(2)))
     self.assertTrue(stock.containsItem(Marshmallow(3)))
     self.assertTrue(stock.containsItem(Honey(2)))
     self.assertTrue(stock.containsItem(BrownChocolate(5)))
     self.assertTrue(stock.containsItem(MilkChocolate(3)))
     self.assertTrue(stock.containsItem(Chilipepper(2)))
示例#20
0
    def test_wrong_object_type_added_to_excisting_object(self):
        tranItem1 = Transaction("Google", datetime.now(), self.buy, 23.32, 20)
        tranItem2 = "WrongObject"

        listOfTrans = []
        listOfTrans.append(tranItem1)
        testObj = Stock("Google", listOfTrans)

        with self.assertRaises(ValueError):
            testObj.add_transactions(tranItem2)
示例#21
0
def main():
    stock = Stock()
    cart = Cart()
    stock.load_items("stock.txt")
    display_separator()
    display_intro()
    display_separator()
    main_menu(stock, cart)
    display_separator()
    stock.save_items("stock2.txt")
def addNewStock():
    stock = Stock()
    stock.name = input("Enter stock name for new stock : \n")
    stock.sale_price = input("Enter sale price for new stock : \n")
    stock.purchase_price = input("Enter purchase price for new stock : \n")
    displayAllCategory()
    stock.stock_in_qty = 0
    stock.stock_out_qty = 0
    stock.category_id = input("Enter category code for new stock : \n")
    stock.save()
示例#23
0
def guardar_mueble(clave, cantidad):
    try:
        stock = Stock()
        stock = dbroot[clave]
        stock.cantidad = stock.cantidad + cantidad
        dbroot[clave] = stock
        transaction.commit()
        return True
    except ValueError:
        return False
 def main(self):
     self.gui = Gui()
     self.Intervals = [
         '1 Minute', '5 Minutes', '15 Minutes', '30 Minutes', '60 Minutes',
         '1 Day', '1 Week', '1 Month'
     ]
     previous_ticker = ''
     while True:
         event, values = self.gui.data()
         self.getMonths(values)
         if values['Ticker'] != previous_ticker:
             self.gui.updateTickers()
             previous_ticker = values['Ticker']
         elif values['Ticker'] in ['Ticker', '']:
             self.gui.window.FindElement('Ticker').Update(
                 values=self.gui.allTickers,
                 value=values['Ticker'],
                 size=(10, 10))
         if event in [PySimpleGUI.WIN_CLOSED, 'Exit']:
             exit()
         elif event == 'Run':
             toEnter = [
                 values['Ticker'],
                 self.Intervals.index(values['Interval']),
                 values['StartMonth'],
                 values['EndMonth'],
             ]
             self.gui.update('SD', "Calculating...")
             self.gui.update('SMVI', "Calculating...")
             self.gui.update('Terminal', 'Calculating...')
             if values['Handle'] in ['', 'Handle']:
                 PySimpleGUI.popup(
                     'Error, please enter a valid Twitter handle')
                 continue
             stock = Stock(toEnter[0], toEnter[1], toEnter[2], toEnter[3],
                           self.gui.Months, False)
             if stock.hasErrors:
                 error_message = 'An error occured'
                 self.gui.update('Terminal', error_message)
                 self.gui.update('SD', error_message)
                 self.gui.update('SMVI', error_message)
                 continue
             else:
                 SDToDisplay = str(stock.SDToDisplay)[0:8]
                 self.gui.update('SD', SDToDisplay)
                 self.gui.update('Terminal', 'Calculating baseline...')
                 DIA = Stock('DIA', toEnter[1], toEnter[2], toEnter[3],
                             self.gui.Months, True)
                 self.gui.update('Terminal', 'Calculating SVMI')
                 cor = Correlation(stock, DIA,
                                   self.parseHandles(values['Handle']))
                 self.gui.update('SMVI',
                                 str(cor.SMVI * float(SDToDisplay))[0:8])
                 self.gui.update('Terminal', 'Done!')
示例#25
0
 def show(self):
     stock = Stock()
     print "*" * 20
     print "stockCode:%s"  % str(",".join(map(str,self.stock.keys())) if len(self.stock) > 1 else self.stock.keys()[0])
     print "money:%s"      % str(self.money)
     #購入時の株価にて算出
     print "stockPrice1:%s" % str(sum([price * number  for (day,code),(price,number,kind) in self.stock.items()]))
     print "totalPrice1:%s" % str(self.money + sum([price * number  for (day,code),(price,number,kind) in self.stock.items()]))
     #現在の株価にて算出
     print "stockPrice2:%s" % str(sum([stock.currentEndPrice(code,dateTools.dateBusinessDay()) * number  for (day,code),(price,number,kind) in self.stock.items()]))
     print "totalPrice2:%s" % str(self.money + sum([stock.currentEndPrice(code,dateTools.dateBusinessDay()) * number  for (day,code),(price,number,kind) in self.stock.items()]))
     print "*" * 20
示例#26
0
def load_stock_data(index):
    stocks = []
    directory = os.path.join(os.curdir, "data", index)
    file_paths = [os.path.join(directory, name) for name in os.listdir(directory)]
    for file_path in file_paths:
        symbol = os.path.basename(file_path).split(".")[0]
        stock = Stock(symbol)
        with open(file_path, "r", newline='') as fobj:
            reader = csv.DictReader(fobj)
            for row in reader:
                stock.append_record(Record(row))
        stocks.append(stock)
    return stocks
示例#27
0
 def create_stocks(self):
     """creates the stocks that are going to be used in the stock market game"""
     names = self.stock_names.copy()
     for i in range(0, 10):
         name_to_remove = random.choice(names)
         if i < 4:
             new_stock = Stock(name_to_remove, round(random.uniform(2, 50), 2))
         elif 4 <= i < 8:
             new_stock = Stock(name_to_remove, round(random.uniform(51, 150), 2))
         else:
             new_stock = Stock(name_to_remove, round(random.uniform(150, 310), 2))
         names.remove(name_to_remove)
         self.stocks.append(new_stock)
示例#28
0
 def __init__(
     self,
     symbol,
     purchasePrice,
     currentPrice,
     quantity,
     coupon,
     yieldAmount,
     purchaseDate,
 ):
     Stock.__init__(self, symbol, purchasePrice, currentPrice, quantity,
                    purchaseDate)
     self.coupon = coupon
     self.yieldAmount = yieldAmount
    def outPutStockmeanFR(self):
        # 波动幅度排序
        indexs = NameList.getList()

        array = []
        for _item in indexs:
            _key = _item.keys()[0]
            s = Stock(atr=['20'], ma=['20'], index=_key)
            array.append({'code': _key, 'mfr': s.getMeanFR(20)})

        array.sort(key=lambda x: x['mfr'], reverse=True)

        for _item in array:
            print _item['code'], NameList.getName(_item['code']), _item['mfr']
示例#30
0
 def __init__(self,**kwds):
     '''
     Input:
     Keyword Usage:
     if filename is used, it will read the yahoo API based minute to minute data:
     
     Stock(filename="Filename.csv")
     
     - or -
     
     if tickerParams is used, it will use the google API to retrieve minute to minute data
     
     Stock(tickerParams=['appl',10,60,False])
     where 
     Input
     Parameters = [ticker,days,period,isNYSE,companyName]
     1)the first element in the list is a string of the ticker symbol, e.g. 'appl'
     2)the second element in the list is the historical data period, e.g. 10 days
     3)the third element in the list is the period of data in seconds, e.g. 60 (seconds)
     4)the fourth element in the list is True or False.  True -> ticker is on NYSE, False -> ticker is on NASDAQ
     5)the fifth element in the list is the company name as a string
     Description: Step1: From stock, it will give us sigma(x)
                  Step2: Interpolate sigma(x) using step1.
     '''
     if 'tickerParams' in kwds:
         Stock.__init__(self,tickerParams=kwds)
     elif 'filename' in kwds:
         Stock.__init__(self,filename=kwds)
     elif 'en' in kwds:
         EulerMaruyama.__init__(self,kwds['en'])
     if not hasattr(self,'StockPrices'):
         pass
     else:
         if len(self.StockPrices) > 30 :
             self.GridPoints = self.GetGridPoints()
             self.UsableGridPoints, self.StockPricesByGridPointDictionary = self.DoGridAnalysis(self.T,self.StockPrices,self.GridPoints,self.n,self.h_n,.05)
             if len(self.UsableGridPoints) >= 3:
                 self.EstimatedVariance = [self.Volatility_estimation(self.T,self.StockPrices,ex,self.n,self.h_n)**2 for ex in self.StockPrices]# these are the sigma values evulated at the grid points
                 self.PriceEstimatedVarianceDictionary = {ex:self.Volatility_estimation(self.T,self.StockPrices,ex,self.n,self.h_n)**2 for ex in self.StockPrices} 
                 self.CreateZmirouTable()
                 self.EstimatedStandardDeviation = [i**(1.0/2.0) for i in self.EstimatedVariance]
                 self.InverseVariance = [1.0/i for i in self.EstimatedVariance]
                 self.InverseStandardDeviation = [1.0/i for i in self.EstimatedStandardDeviation]
                 self.CubicInterpolatedVariance = self.GetCubicInterpolatedVariance()
                 self.CubicInterpolatedStandardDeviation = self.GetCubicSplineInterpolatedStandardDeviation()
                 self.GridVariance = self.GetGridVariance()
                 self.InterpolatedRange = (self.minPrice,self.maxPrice)
                 self.InterpolationBubbleTestResult = self.InterpolationBubbleTest(self.EstimatedVariance, self.StockPrices)
                 self.InterpolationBubbleTest = self.InterpolationBubbleTestResult <= 0  #if true, the not a bubble.  if false, then perhaps a bubble.
示例#31
0
 def investing(self):
     inv = pd.DataFrame()
     rows = len(inv)
     difference = self.EndDate - self.StartDate
     dif_in_years = (difference.days +
                     difference.seconds / 86400) / 365.2425
     if rows == 0:
         #we define the top line of our dataframe in case it is the first investment
         inv = pd.DataFrame(columns=[
             'TYPE', 'PRICE', 'Quantity', 'Total Amount', 'P_Date',
             'S_Date', 'AbsReturn', 'Volatility'
         ])
     while self.Budget >= 100:
         #we select a random stock from the list of stocks
         stock = random.choice([
             'AAPL', 'GOOGL', 'YHOO', 'AXP', 'XOM', 'KO', 'NOK', 'MS',
             'IBM', 'FDX'
         ])
         #an instance of class stock is initialized
         new_stock = Stock(self.StartDate, self.EndDate, stock)
         #we look for the price on the first day
         first_price = new_stock.getFirstPrice()
         #and thus determine how many stock we could buy
         max_nmbr = int(self.Budget / first_price)
         #a random number of stock between 0 and the max_nmbr is chosen
         nmbr_invested = random.randint(0, max_nmbr)
         #we add a line to our portfolio, stating the stock, the day of purchase and the number of stocks we buy
         inv_new = pd.DataFrame({
             'TYPE': [stock],
             'PRICE': [first_price],
             'Quantity': [nmbr_invested],
             'Total Amount': [nmbr_invested * first_price],
             'P_Date': [self.StartDate],
             'S_Date': [self.EndDate],
             'AbsReturn': [(1 + new_stock.stkCCReturn(self.EndDate)) *
                           nmbr_invested * first_price]
         })
         for i in range(1, int(dif_in_years)):
             x = self.StartDate
             y = datetime.timedelta(days=(i * 365.24))
             z = x + y
             inv_new[str(i)] = new_stock.stkCCReturn(
                 z) * nmbr_invested * first_price
         tot_inv = [inv, inv_new]
         inv = pd.concat(tot_inv, axis=0)
         #our budget is reduced with the amount invested
         self.Budget = self.Budget - nmbr_invested * first_price
         self.Portfolio = inv
     return self.Portfolio
示例#32
0
    def test_calculate_total_shares_non_zero_number_of_transactions(self):
        tranItem1 = Transaction("Google", datetime.now(), self.buy, 23.32, 20)
        tranItem2 = Transaction("IBM", datetime.now(), self.buy,23.36, 20)
        tranItem3 = Transaction("FaceBook", datetime.now(), self.sell, 23.36, 10)
        tranItem4 = Transaction("Apple", datetime.now(), self.sell, 36.23 , 10)

        listOfTrans = []
        listOfTrans.append(tranItem1)
        listOfTrans.append(tranItem2)
        listOfTrans.append(tranItem3)
        listOfTrans.append(tranItem4)

        testObj = Stock("Test", listOfTrans)

        self.assertEqual(testObj.calculate_current_shares(), 20)
示例#33
0
    def apply(self, agent: Agent, stock: Stock):
        portfolio_history = [copy(self._portfolio)]
        evaluation_steps = stock.random_split(self._min_past_steps, self._min_eval_steps)
        try:
            for step in range(evaluation_steps):
                past = stock.get_past(step)
                print(past[-1].close)
                #action = agent.run(past)
                #current_state = copy(portfolio_history[-1])
                #new_portfolio = current_state.apply_action(action, past[-1].close)
                #portfolio_history.append(new_portfolio)
        except:
            print("Agent failed to survive!")

        return portfolio_history
示例#34
0
def GetHoldingsFor(investor,fileName,type="stock"):
    '''function to generate a set of sample holdings from a csv'''       
    holdings = []
    try:
        with open(fileName) as csv_file:
            csv_reader = csv.reader(csv_file, delimiter=',')
            line_count =0
            for row in csv_reader:
                if line_count == 0:
                    pass
                else:
                    purchaseDate = DateFromMmddyyyyString(row[4])
                    if type=="bond":
                        stock = Bond(row[0],float(row[3]),float(row[5]),float(row[6]))
                    else:
                        stock = Stock(row[0],float(row[3]))
                    thisHolding=Holding.new(investor,stock,int(row[1]),float(row[2]),purchaseDate)
                    holdings.append(thisHolding)  
                    Database().Insert(thisHolding)                  
                line_count += 1
    except FileNotFoundError:
        print(f"File not found: {fileName}")    
    except ValueError:
        print(f"There was an issue getting values from {fileName} on line {line_count}")
    return holdings
def form_data(init_param):
    """ This function constructs the training, testing and cross validation
        objects for the stock market analysis """
    stocks = Stock.read_stocks('../data/stocks_read.txt', init_param.max_stocks)
    stocks_train = []
    stocks_cv = []
    stocks_test = []
    count = 0
    for stock in stocks:
        if count % init_param.cv_factor == 0:
            stocks_train.append(stock)
        else:
            stocks_cv.append(stock)
        count = count + 1
    
    day_history = []
    for i in range(init_param.train_increment, init_param.train_days, init_param.train_increment):
        day_history.append(i)
        
    for date in init_param.reference_dates:
        try:
            training_data
        except NameError:
            training_data = LearningData()
            training_data.construct(stocks_train,[date, day_history, init_param.future_day])
            cv_data = LearningData()
            cv_data.construct(stocks_cv,[date, day_history, init_param.future_day])
        else:
            training_data.append(stocks_train,[date, day_history, init_param.future_day])
            cv_data.append(stocks_cv,[date, day_history, init_param.future_day])
            
    for date in init_param.test_dates:
        try:
            test_data
        except NameError:
            test_data = LearningData()
            test_data.construct(stocks,[date, day_history, init_param.future_day])
        else:
            test_data.append(stocks,[date, day_history, init_param.future_day])
    
    #reference_date = dateutil.days_since_1900('1991-01-01')
    #test_data.construct(stocks,[reference_date, day_history, init_param.future_day])
    
    return training_data, cv_data, test_data
示例#36
0
 def __init__(self, symbol, lastDividend, parValue):
     Stock.__init__(self, symbol, lastDividend, parValue)
示例#37
0
 def __init__(self,funds):
     self.money = MoneyManage(funds)
     self.stock = Stock()
示例#38
0
def _readFinvizLine(line, stocks):
    "Imports stock metrics from the data line and stores it in the list of \
    Stock objects"

    # Parse html
    (stkraw, dl) = _parseHtml(line)

    # Create new stock object
    stock = Stock()

    # Get ticker symbol
    stock.tick = stkraw[dl[1] + 1: dl[2]]
    # Get company name
    stock.name = stkraw[dl[2] + 1 : dl[3]]

    # Get market cap multiplier (either MM or BB)
    if stkraw[dl[4] - 1] == 'B':
        capmult = 1000000000
    else:
        capmult = 1000000

    # Get market cap
    stock.mktcap = capmult * _toFloat(stkraw[dl[3] + 1 : dl[4] - 1])
    # Get P/E ratio
    stock.pe = _toFloat(stkraw[dl[4] + 1 : dl[5]])
    # Get P/S ratio
    stock.ps = _toFloat(stkraw[dl[5] + 1 : dl[6]])
    # Get P/B ratio
    stock.pb = _toFloat(stkraw[dl[6] + 1 : dl[7]])
    # Get P/FCF ratio
    stock.pfcf = _toFloat(stkraw[dl[7] + 1 : dl[8]])
    # Get Dividend Yield
    stock.div = _toFloat(stkraw[dl[8] + 1 : dl[9] - 1])
    # Get 6-mo Relative Price Strength
    stock.mom = _toFloat(stkraw[dl[9] + 1 : dl[10] - 1])
    # Get Current Stock Price
    stock.price = _toFloat(stkraw[dl[11] + 1 : dl[12]])

    # Append stock to list of stocks
    stocks.append(stock)

    return
示例#39
0
 def __init__(self, symbol, lastDividend, fixedDividend, parValue):
     Stock.__init__(self, symbol, lastDividend, parValue)
     self.parValue = parValue
示例#40
0
def main():
    
    max_stocks = 100
    stocks = Stock.read_stocks('../data/stocks_read.txt', max_stocks)
    stocks_train = []
    stocks_cv = []
    count = 0
    for stock in stocks:
        if count % 2 == 0:
            stocks_train.append(stock)
        else:
            stocks_cv.append(stock)
        count = count + 1

    training_data = LearningData()
    cv_data = LearningData()
    
    day_history = []
    for i in range(5, 101, 5):
        day_history.append(i)
        
    reference_date = dateutil.days_since_1900('1980-01-01')
    training_data.construct(stocks_train,[reference_date, day_history, 25])
    cv_data.construct(stocks_cv,[reference_date, day_history, 25])
    
    reference_date = dateutil.days_since_1900('1981-01-01')
    training_data.append(stocks_train,[reference_date, day_history, 25])
    cv_data.append(stocks_cv,[reference_date, day_history, 25])
    
    """reference_date = dateutil.days_since_1900('1981-01-01')
    training_data.append(stocks_train,[reference_date, [50, 100, 150], 50])
    cv_data.append(stocks_cv,[reference_date, [50, 100, 150], 50])"""
    """reference_date = dateutil.days_since_1900('1980-01-01')
    i_day = dateutil.find_ref_date_idx(stocks[0], reference_date)
   # trainingData.construct(stocks,['1/1/1980', [50, 100, 150], 50])
    training_data.construct(stocks,[reference_date, [50, 100, 150], 50])
    reference_date = dateutil.days_since_1900('1981-01-01')
    training_data.append(stocks,[reference_date, [50, 100, 150], 50])
	
    cv_data = LearningData()
    reference_date = dateutil.days_since_1900('1982-01-01')
    cv_data.construct(stocks,[reference_date, [50, 100, 150], 50])
    reference_date = dateutil.days_since_1900('1983-01-01')
    cv_data.append(stocks,[reference_date, [50, 100, 150], 50])"""
	
    XX = training_data.X
    clf = linear_model.Ridge(alpha=0.1, fit_intercept=False)
    clf.fit(training_data.X, training_data.y)
	

    # To look for overfitting the code loops through values of alpha plotting distance between
    # the predicted values and actual data and various alphas
    print(training_data.m, cv_data.m)
    aa = a = np.array((0, 0, 0, 0))
    bb = a = np.array((1, 1, 1, 1))
    print(np.linalg.norm(bb - aa))
    alph = 0.02
    f = open('alpha.txt', 'w')
    while alph < 0.2:  #0.2
        # First fit the data for each alpha
        clf = linear_model.Ridge (alpha=alph, fit_intercept=False)
        clf.fit(training_data.X, training_data.y)
        # Now measure how close model comes for both training data and cross validation data
        # The clf.predict produces a vector with one element for each element in the sample
        predict_data = clf.predict(training_data.X)
        predict_cv = clf.predict(cv_data.X)
        # The linagl function in np takes a L2 norm of the difference
        diff_data = (1.0/training_data.m) * np.linalg.norm(predict_data - training_data.y)
        diff_cv = (1.0/cv_data.m) * np.linalg.norm(predict_cv - cv_data.y)
        print("lengths are ", len(predict_data), len(training_data.y), len(predict_cv), len(cv_data.y))
        # Write out the values
        f.write(str(alph) +  " " + str(diff_data) + " " + str(diff_cv) +  "\n")
        """print(diff_data, diff_cv)
        print(predict_data - training_data.y)
        print(predict_cv - cv_data.y)"""
        alph = alph * 1.5 # Increment alph
    f.close()
     
     # Do the fit based on best alpha value   
    clf = linear_model.Ridge (alpha=0.05, fit_intercept=False)
    clf.fit(training_data.X, training_data.y)
    
    portfolio_value = 1.0 # Start with a portfolio value of 1.0
    average_value = 1.0
    investing_data = LearningData()
    
    # Construct an LearningData set
    reference_date = dateutil.days_since_1900('1984-01-01')
    i_day = dateutil.find_ref_date_idx(stocks[0], reference_date)
  #  print (i_day, stocks[0].dates[i_day] )
    """ f = open('value.txt', 'w')
    
    while i_day > 100:
        investing_data.construct(stocks,[reference_date, [50, 100, 150], 50])  
        # Predict growth of stock values based on history
        predict_data = clf.predict(investing_data.X)
        # Predict the stock that will have best growth
        index_max, value = max(enumerate(predict_data), key=itemgetter(1))
        # Upgrade portfolio value based on its actual performance
        portfolio_value = portfolio_value * investing_data.y[index_max]
        average_value = average_value * np.mean(investing_data.y)
        f.write(str(reference_date) + " " + str(portfolio_value) + " " + str(average_value) + "\n")
        #print(portfolio_value)
        i_day = i_day - 50
        reference_date = stocks[0].dates[i_day]
    f.close() """
    
    print("run finished")
示例#41
0
"""

if __name__ == "__main__":
    pass

    logging.basicConfig()
    logger = logging.getLogger()

    stockListCSV = FinViz.getStockData()

    stockList = []
    skipHeader = True
    for stockData in stockListCSV:

        if skipHeader == False:
            stock = Stock(stockData)
            # Populate Enterprise.Value/EBITDA information from Yahoo's key stats
            stock.updateKeyStats(Yahoo.getKeyStats(stockData[1]))
            print "Update keystats on " + stockData[1]

            # Populate buy back yield
            stock.updateCashFlow(Yahoo.getCashFlow(stockData[1]))
            print "Update cashFlow on " + stockData[1]
            print stock.toString()
            stockList.append(stock)
            logging.debug("Updated stock ticker: " + stockData[1])

        else:
            skipHeader = False

    ratedStocks = []
示例#42
0
  def get_data_list(self):
    """Read file of stock data, create list of Stock objects"""
    line=self._fileObj.readline() #read first line, trash because headers
    line=self._fileObj.readline()
    while line:
      stockObj=Stock() #create Stock object
      data=line.split() #split line read in

      #assign parts to object
      stockObj.setDate(data[0])
      stockObj.setOpeningVal(float(data[1]))
      stockObj.setHighVal(float(data[2]))
      stockObj.setLowVal(float(data[3]))
      stockObj.setClosingVal(float(data[4]))
      stockObj.setVolume(int(data[5]))
      self._stocks.append(stockObj)

      line=self._fileObj.readline()
    self._fileObj.close()