class UserModel(UserMixin, db.Document): meta = {'collection': 'user_models'} name = db.StringField(max_length=30) mod_type = db.StringField(max_length=3, choices=TYPES) period = db.StringField(max_length=6) interval = db.StringField(max_length=6) money = db.FloatField() buy = db.FloatField() sell = db.FloatField() av_length = db.IntField() trade_cost = db.FloatField() owner = db.LazyReferenceField('User')
class Model(UserMixin, db.Document): meta = {'collection': 'models'} keep = db.BooleanField(default=True) mod_type = db.StringField(max_length=3, choices=TYPES) ticker = db.StringField(max_length=6) period = db.StringField(max_length=6) interval = db.StringField(max_length=6) money = db.FloatField() buy = db.FloatField() sell = db.FloatField() av_length = db.IntField() trade_cost = db.FloatField()
class Ticket(db.Document): title = db.StringField(min_length=5, max_length=50, required=True) price = db.FloatField(min_value=1, required=True) user_id = db.StringField(required=True) order_id = db.StringField(default=None) version = db.IntField(default=0) def response(self): return { "id": str(self.id), "title": self.title, "price": self.price, "user_id": self.user_id, "order_id": self.order_id, "version": self.version } def update_version_if_record_exists(self): if not self.id: return existing_record = Ticket.objects(id=self.id) if existing_record: self.version += 1 def save(self, *args, **kwargs): self.update_version_if_record_exists() super().save(*args, **kwargs)
class Check(UserMixin, db.Document): meta = {'collection': 'checks'} ticker = db.StringField() name = db.StringField() previous_close = db.FloatField() three_mo_avg_vol = db.FloatField() year_range = db.StringField() def get_info(self): stock = yf.Ticker(self.ticker) info = stock.info if info['quoteType'] == 'EQUITY': self.name = info['longName'] self.previous_close = info['regularMarketPreviousClose'] self.three_mo_avg_vol = info['averageDailyVolume3Month'] self.year_range = info['fiftyTwoWeekRange'] self.save() return self.id
class D2VModel(db.Document): serialized_model = db.FileField() last_run = db.DateTimeField() vectors = db.DictField() # [ # [a1, a2], # [b1, b2] # ] vectors_2d = db.ListField(db.ListField(db.FloatField())) @property def model(self): """ load serialized model :return: """ if not self.serialized_model: return None bytes_io = io.BytesIO(self.serialized_model) model = pickle.load(bytes_io) return model @model.setter def model(self, model): # instead of a file bytes_io = io.BytesIO() # save model to bytesio model.save(bytes_io) # getvalue has the actual bytes self.serialized_model = bytes_io.getvalue() # close buffer bytes_io.close() # update timestamp and save self.touch() @staticmethod def get(): d2v_model = D2VModel.objects.first() if not d2v_model: d2v_model = D2VModel() d2v_model.touch() d2v_model.save() return d2v_model def touch(self): self.last_run = datetime.datetime.now()
class Article(db.Document): feed = db.ReferenceField(Feed, required=True) source_id = db.StringField(required=True) url = db.StringField() title = db.StringField() top_image = db.StringField() movies = db.ListField() keywords = db.ListField() tags = db.ListField() authors = db.ListField() publish_date = db.DateTimeField() summary = db.StringField() html = db.StringField() meta_data = db.DictField() language = db.StringField() text = db.StringField() active = db.BooleanField(default=True) vector = db.ListField(db.FloatField()) vector_2d = db.ListField(db.FloatField()) def as_dict(self): return dict(feed=self.feed.url, source_id=self.source_id, url=self.url, title=self.title, top_image=self.top_image, movies=self.movies, keywords=self.keywords, tags=self.tags, authors=self.authors, publish_date='%s' % self.publish_date, summary=self.summary, html=self.html, meta_data=self.meta_data, language=self.language, text=self.text, vector=self.vector, vector_2d=self.vector_2d) @staticmethod def update_vectors(model, vectors_2d=[]): # https://stackoverflow.com/questions/30943076/mongoengine-bulk-update-without-objects-update bulk_operations = [] keys = model.docvecs.doctags.keys() vectors = model.docvecs.vectors_docs for key, vector, vector_2d in zip(keys, vectors, vectors_2d): bulk_operations.append( UpdateOne({'_id': key}, { '$set': dict(vector=vector.tolist(), vector_2d=vector_2d) })) if bulk_operations: collection = Article._get_collection() \ .bulk_write(bulk_operations, ordered=False)
class LabInvoice(db.Document): date = db.DateTimeField(default=datetime.datetime.utcnow()) items = db.ListField(db.ObjectIdField()) total = db.FloatField()
class LabInventory(db.Document): name = db.StringField() price = db.FloatField()
class PahrmacyInventory(db.Document): name = db.StringField() quantity = db.IntField() price = db.FloatField()
class PharmacyInvoice(db.Document): date = db.DateTimeField(default=datetime.datetime.utcnow()) items = db.ListField(db.DictField()) total = db.FloatField()
class Calculation(UserMixin, db.Document): meta = {'collection': 'entries'} keep = db.BooleanField(default=True) date_stamp = db.StringField(max_length=40) type_info = db.StringField() buy = db.FloatField() sell = db.FloatField() av_length = db.IntField() ticker = db.StringField() period = db.StringField() interval = db.StringField() money = db.FloatField() trade_cost = db.FloatField() owner = db.LazyReferenceField('User') final_money = db.FloatField() final_owned = db.FloatField() final_liquid = db.FloatField() td = db.ListField() tt = db.ListField() ty = db.ListField() tp = db.ListField() tv = db.ListField() graph_x = db.ListField() graph_y = db.ListField() chart_x = db.ListField() chart_y = db.ListField() model = db.LazyReferenceField('Model') user_model = db.LazyReferenceField('UserModel') def static_range(self): stock = yf.Ticker(self.ticker) df = stock.history(period=self.period, interval=self.interval) owned = 0 count = 0 trade_money = self.money trade_cost = self.trade_cost buy = self.buy sell = self.sell td = [] #trade date tt = [] #trade time ty = [] #trade type tp = [] #trade price tv = [] #trade volume store_chart_x = [] store_chart_y = [] for index, row in df.iterrows(): count += 1 available_money = trade_money - trade_cost available_volume = row['Volume']/40 low = round(row['Low'], 4) high = round(row['High'], 4) date = index.to_pydatetime().strftime("%d-%m-%Y") time = index.to_pydatetime().strftime("%H:%M") etime = index.to_pydatetime() + timedelta(minutes=2) endtime = etime.strftime("%H:%M") if low != high: if float(row['Open']) > float(row['Close']): store_chart_y.append(float(high)) store_chart_x.append(date[6:10]+'-'+date[3:5]+'-'+date[0:2] + 'T' + time + ':00') store_chart_y.append(float(low)) store_chart_x.append(date[6:10] + '-' + date[3:5] + '-' + date[0:2] + 'T' + endtime + ':00') elif float(row['Close']) > float(row['Open']): store_chart_y.append(float(low)) store_chart_x.append(date[6:10] + '-' + date[3:5] + '-' + date[0:2] + 'T' + time + ':00') store_chart_y.append(float(high)) store_chart_x.append(date[6:10] + '-' + date[3:5] + '-' + date[0:2] + 'T' + endtime + ':00') elif low == high: store_chart_y.append(low) store_chart_x.append(date[6:10] + '-' + date[3:5] + '-' + date[0:2] + 'T' + time + ':00') lvalue = (low * available_volume) hvalue = (high * available_volume) if available_money > 0 and low <= buy and lvalue > trade_cost: if lvalue>available_money>0: owned += (available_money/low) trade_money = 0 td.append(date) tt.append(time) ty.append('b') tp.append(low) tv.append(available_volume) elif available_money>lvalue>0: owned += (lvalue/low) trade_money -= trade_cost trade_money -= lvalue td.append(date) tt.append(time) ty.append('b') tp.append(low) tv.append(available_volume) if owned > 0 and high >= sell and hvalue > trade_cost: if available_volume > owned: trade_money += (owned*high) trade_money -= trade_cost owned = 0 td.append(date) tt.append(time) ty.append('s') tp.append(high) tv.append(available_volume) elif owned > available_volume: trade_money += (available_volume*high) trade_money -= trade_cost owned -= available_volume td.append(date) tt.append(time) ty.append('s') tp.append(high) tv.append(available_volume) if owned > 0: liquid_money = (trade_money - trade_cost) + df.Low.ix[count-1]*owned else: liquid_money = trade_money self.chart_x = store_chart_x self.chart_y = store_chart_y self.final_money = round(trade_money, 2) self.final_owned = round(owned) self.final_liquid = round(liquid_money, 2) self.td = td self.tt = tt self.ty = ty self.tp = tp self.tv = tv self.save() return self.id def moving_average(self): stock = yf.Ticker(self.ticker) df = stock.history(period=self.period, interval='1d') owned = 0 count = 0 trade_money = self.money trade_cost = self.trade_cost bd = self.buy sd = self.sell ma_length = self.av_length ma_conv = ma_length - 1 ma_sum = 0 td = [] # trade date tt = [] # trade time ty = [] # trade type tp = [] # trade price tv = [] # trade volume store_ma = [] store_ma_x = [] store_chart_x = [] store_chart_y = [] for i in range(0, df.shape[0] - ma_conv): for j in range(0, ma_length): ma_sum += df.iloc[i + j, 3] df.loc[df.index[i + ma_conv], 'SMA_' + str(ma_length)] = np.round((ma_sum / ma_length), 4) ma_sum = 0 for index, row in df.iloc[ma_length:].iterrows(): count += 1 available_money = trade_money - trade_cost available_volume = row['Volume'] / 40 low = round(row['Low'], 4) high = round(row['High'], 4) date = index.to_pydatetime().strftime("%d-%m-%Y") time = index.to_pydatetime().strftime("%H:%M") if low != high: if float(row['Open']) > float(row['Close']): store_chart_y.append(float(high)) store_chart_x.append(date[6:10]+'-'+date[3:5]+'-'+date[0:2]+'T09:30:00') store_chart_y.append(float(low)) store_chart_x.append(date[6:10] + '-' + date[3:5] + '-' + date[0:2] + 'T16:00:00') elif float(row['Close']) > float(row['Open']): store_chart_y.append(float(low)) store_chart_x.append(date[6:10] + '-' + date[3:5] + '-' + date[0:2] + 'T09:30:00') store_chart_y.append(float(high)) store_chart_x.append(date[6:10] + '-' + date[3:5] + '-' + date[0:2] + 'T16:00:00') elif low == high: store_chart_y.append(low) store_chart_x.append(date[6:10] + '-' + date[3:5] + '-' + date[0:2] + 'T12:45:00') lvalue = (low * available_volume) hvalue = (high * available_volume) buy = row['SMA_' + str(ma_length)] - bd sell = row['SMA_' + str(ma_length)] + sd store_ma.append(float(row['SMA_' + str(ma_length)])) store_ma_x.append(date[6:10] + '-' + date[3:5] + '-' + date[0:2] + 'T' + time + ':00') if available_money > 0 and low <= buy and lvalue > trade_cost: if lvalue > available_money > 0: owned += (available_money / low) trade_money = 0 td.append(date) tt.append(time) ty.append('b') tp.append(low) tv.append(available_volume) elif available_money > lvalue > 0: owned += (lvalue / low) trade_money -= trade_cost trade_money -= lvalue td.append(date) tt.append(time) ty.append('b') tp.append(low) tv.append(available_volume) if owned > 0 and high >= sell and hvalue > trade_cost: if available_volume > owned: trade_money += (owned * high) trade_money -= trade_cost owned = 0 td.append(date) tt.append(time) ty.append('s') tp.append(high) tv.append(available_volume) elif owned > available_volume: trade_money += (available_volume * high) trade_money -= trade_cost owned -= available_volume td.append(date) tt.append(time) ty.append('s') tp.append(high) tv.append(available_volume) if owned > 0: liquid_money = (trade_money - trade_cost) + df.Low.ix[count - 1] * owned else: liquid_money = trade_money self.chart_x = store_chart_x self.chart_y = store_chart_y self.graph_y = store_ma self.graph_x = store_ma_x self.final_money = round(trade_money, 2) self.final_owned = round(owned) self.final_liquid = round(liquid_money, 2) self.td = td self.tt = tt self.ty = ty self.tp = tp self.tv = tv self.save() return self.id def weighted_moving_average(self): stock = yf.Ticker(self.ticker) df = stock.history(period=self.period, interval='1d') owned = 0 count = 0 trade_money = self.money trade_cost = self.trade_cost bd = self.buy sd = self.sell wma_length = self.av_length wma_conv = wma_length - 1 wma_sum = 0 weight = 0 weight_sum = 0 for k in range(1, wma_length + 1): weight_sum += k td = [] # trade date tt = [] # trade time ty = [] # trade type tp = [] # trade price tv = [] # trade volume store_wma = [] store_wma_x = [] store_chart_y = [] store_chart_x = [] for i in range(0, df.shape[0] - wma_conv): for j in range(0, wma_length): weight += 1 wma_sum += (df.iloc[i + j, 3]*weight) weight = 0 df.loc[df.index[i + wma_conv], 'WMA_' + str(wma_length)] = np.round((wma_sum / weight_sum), 4) wma_sum = 0 for index, row in df.iloc[wma_length:].iterrows(): count += 1 available_money = trade_money - trade_cost available_volume = row['Volume'] / 40 low = round(row['Low'], 4) high = round(row['High'], 4) date = index.to_pydatetime().strftime("%d-%m-%Y") time = index.to_pydatetime().strftime("%H:%M") if low != high: if float(row['Open']) > float(row['Close']): store_chart_y.append(float(high)) store_chart_x.append(date[6:10]+'-'+date[3:5]+'-'+date[0:2]+'T09:30:00') store_chart_y.append(float(low)) store_chart_x.append(date[6:10] + '-' + date[3:5] + '-' + date[0:2] + 'T16:00:00') elif float(row['Close']) > float(row['Open']): store_chart_y.append(float(low)) store_chart_x.append(date[6:10] + '-' + date[3:5] + '-' + date[0:2] + 'T09:30:00') store_chart_y.append(float(high)) store_chart_x.append(date[6:10] + '-' + date[3:5] + '-' + date[0:2] + 'T16:00:00') elif low == high: store_chart_y.append(low) store_chart_x.append(date[6:10] + '-' + date[3:5] + '-' + date[0:2] + 'T12:45:00') lvalue = (low * available_volume) hvalue = (high * available_volume) buy = row['WMA_' + str(wma_length)] - bd sell = row['WMA_' + str(wma_length)] + sd store_wma.append(float(row['WMA_' + str(wma_length)])) store_wma_x.append(date[6:10]+'-'+date[3:5]+'-'+date[0:2]+'T'+time+':00') if available_money > 0 and low <= buy and lvalue > trade_cost: if lvalue > available_money > 0: owned += (available_money / low) trade_money = 0 td.append(date) tt.append(time) ty.append('b') tp.append(low) tv.append(available_volume) elif available_money > lvalue > 0: owned += (lvalue / low) trade_money -= trade_cost trade_money -= lvalue td.append(date) tt.append(time) ty.append('b') tp.append(low) tv.append(available_volume) if owned > 0 and high >= sell and hvalue > trade_cost: if available_volume > owned: trade_money += (owned * high) trade_money -= trade_cost owned = 0 td.append(date) tt.append(time) ty.append('s') tp.append(high) tv.append(available_volume) elif owned > available_volume: trade_money += (available_volume * high) trade_money -= trade_cost owned -= available_volume td.append(date) tt.append(time) ty.append('s') tp.append(high) tv.append(available_volume) if owned > 0: liquid_money = (trade_money - trade_cost) + df.Low.ix[count - 1] * owned else: liquid_money = trade_money self.chart_x = store_chart_x self.chart_y = store_chart_y self.graph_x = store_wma_x self.graph_y = store_wma self.final_money = round(trade_money, 2) self.final_owned = round(owned) self.final_liquid = round(liquid_money, 2) self.td = td self.tt = tt self.ty = ty self.tp = tp self.tv = tv self.save() return self.id