def create_history_object(**kwargs):
    stock = make_tuple(kwargs)
    stock.open_, stock.high, stock.low, stock.close = [
        float(x) for x in [stock.open_, stock.high, stock.low, stock.close]
    ]
    all_stock_dates = set(
        db.query(History.date).filter_by(symbol=stock.symbol).all())

    # Lets check if we already have that day's data
    have_data = True if (stock.dt, ) in all_stock_dates else False
    if have_data:
        print 'Already have the data for this date! Updating!'
        # continue
        h = db.query(History).filter_by(date=stock.dt).first()
        h.__dict__ = History(kwargs).__dict__.copy()
        return h

    # init new object and add it to the db session
    h = History(symbol=stock.symbol,
                date=stock.dt,
                open=stock.open_,
                high=stock.high,
                low=stock.low,
                close=stock.close,
                volume=stock.volume.replace('\n', ''))
    return h
def save_data(symbol):
    try:
        for data in list_of_datas[symbol]:
            last_update_date = db.query(History.date).filter_by(symbol=symbol).order_by(History.date.desc()).first()
            last_update_date = last_update_date[0].date() if last_update_date else datetime.datetime.today().date()
            today_date = datetime.datetime.today().date()
            if last_update_date >= today_date:
                for row in xrange(7, len(data)):
                    if data[row].count(',') != 5:
                        continue

                    offset, close, high, low, open_, volume = data[row].split(',')
                    if offset[0] == 'a':
                        day = float(offset[1:])
                        offset = 0
                    else:
                        offset = float(offset)
                    open_, high, low, close = [float(x) for x in [open_, high, low, close]]
                    dt = datetime.datetime.fromtimestamp(day + (86400 * offset))
                    h = History(symbol=symbol,
                                date=dt,
                                open=open_,
                                high=high,
                                low=low,
                                close=close,
                                volume=volume.replace("\n", ""))
                    db.add(h)

                    print "Saved " + symbol
                db.commit()
            else:
                print "already got the data for this date!"
    except:
        print "Failed to save the data to " + symbol
Esempio n. 3
0
def create_history_object(**kwargs):
    stock = make_tuple(kwargs)
    stock.open_, stock.high, stock.low, stock.close = [float(x) for x in
                                                       [stock.open_, stock.high, stock.low, stock.close]]
    all_stock_dates = set(db.query(History.date).filter_by(symbol=stock.symbol).all())

    # Lets check if we already have that day's data
    have_data = True if (stock.dt,) in all_stock_dates else False
    if have_data:
        print 'Already have the data for this date! Updating!'
        # continue
        h = db.query(History).filter_by(date=stock.dt).first()
        h.__dict__ = History(kwargs).__dict__.copy()
        return h

    # init new object and add it to the db session
    h = History(symbol=stock.symbol,
                date=stock.dt,
                open=stock.open_,
                high=stock.high,
                low=stock.low,
                close=stock.close,
                volume=stock.volume.replace('\n', ''))
    return h
Esempio n. 4
0
def find_resistance_line(symbol, show_resets=False, include_history=False, start_date=datetime.date(2086, 8, 26)):
    """
    @symbol: Symbol of specific stock
    @show_resets: While iterating the stock data we gives point every time the close price is close to the
                  resistance line. When the close price goes over the line we reset the points. This option
                  will determine if we want to print or not the resets.
    @include_history: When reset occurs should we continue or stop iterate this stock. This good if we want
                      to find resistance line older then the last break. Most of the time we will turn this
                      off because the most important is the last resistance line.
    @start_date: Date that the loop start from.
    """

    try:
        stocks = db.query(History).filter(History.symbol == symbol, History.date < start_date).order_by(History.date.desc()).all()
        if not stocks:
            return
    except:
        print 'error'
        return
    today_price = stocks[0].close
    points = 0
    for day_number in xrange(5, 100):

        # Make sure we wont go more then the stock data have(for new stocks)
        if day_number > len(stocks)-1:
            return
        # Check if we passed the resistance line
        if stocks[day_number].close > today_price * 1.025:
            if show_resets:
                print 'point reset for {} - {}: {}, {}, {}'.format(stocks[day_number].symbol, stocks[day_number].date.strftime("%d/%m/%y"), stocks[day_number+5].close, stocks[day_number].close, stocks[day_number-5].close)
            points = 0
            if include_history:
                continue
            else:
                return
        # check if current close is +- % of the given close(today)
        if today_price * 0.985 < stocks[day_number].close < today_price * 1.125:
            #check if we have a parabola max
            if stocks[day_number+5].close * 1.025 < stocks[day_number].close > stocks[day_number-5].close * 1.025:
                # print 'point - {}: {}, {}, {}'.format(stocks[i].date, stocks[i+5].close, stocks[i].close, stocks[i-5].close)
                # Add point, points given as long as the price didn't broke throe our line
                points += 1
                if points == 4:
                    print 'Found: {}'.format(stocks[day_number].symbol)
Esempio n. 5
0
def find_behavior(symbol, weeks):
    """
    iterate over closep and look for technical behaviors
    """
    days_period = 7  # The days differences between the 3 points.
    highlighted_dates = []  # We will append dates that chosen by change rate.

    start_date = datetime.datetime.now() - datetime.timedelta(weeks=weeks)

    # Get all the stocks from start_date
    stocks = db.query(History).filter((History.symbol == symbol) & (History.date > start_date)).all()

    for index, stock in enumerate(stocks):
        # Check we don't get out of list size
        if index < days_period or index > len(stocks) - days_period-1: continue

        # define 3 points: +- *days_period* days from current day
        close_left = stocks[index - days_period].close
        close_right = stocks[index + days_period].close
        close_center = stocks[index].close

        # Get the percentage change between all the points
        left_per = get_percentage_change(close_left, close_center)
        right_per = get_percentage_change(close_right, close_center)
        # print "left-val: {}, center-val: {}, right-val: {}".format(close_left, close_center, close_right)

        # Find points where the change from the center is 4 or -4 percentages
        if (left_per > 4 and right_per > 4) or (left_per < -4 and right_per < -4):
            highlighted_dates.append(stock)

        if len(highlighted_dates) > 2:
            print "#########################################################"
            print "FOUND IT! left:{}, center:{}, right:{}".format(close_left, close_center, close_right)
            print "percentage-left: {}, percentage-right: {}".format(left_per, right_per)
            print highlighted_dates
            highlighted_dates = []

        # Drop old date from highlghteds!
        if highlighted_dates and highlighted_dates[0].date < stock.date - datetime.timedelta(weeks=10):
            del highlighted_dates[0]
Esempio n. 6
0
import time
import matplotlib.pyplot as plt
import matplotlib.ticker as mticket
import matplotlib.dates as mdates
from matplotlib.finance import candlestick
from project import db
from project.models.history import History
t0 = time.time()
import matplotlib
matplotlib.rcParams.update({'font.size': 9})

symbol = 'AMG'
stocks = db.query(History.date, History.open, History.close, History.high,
                  History.low, History.volume).filter_by(symbol=symbol).all()
stocks_list = [list(tup) for tup in stocks]
# stocks_list = [for x in stocks_list if stocks_list.index(x) == 1]

dates = [stock[0] for stock in stocks]
opens = [stock[1] for stock in stocks]
closes = [stock[2] for stock in stocks]
highs = [stock[3] for stock in stocks]
lows = [stock[4] for stock in stocks]
volumes = [stock[5] for stock in stocks]

x = 0
y = len(dates)
newAr = []
while x < y:
    appendLine = mdates.date2num(
        dates[x]), opens[x], closes[x], highs[x], lows[x], volumes[x]
    newAr.append(appendLine)
Esempio n. 7
0
def set_money(money):
    new_money = db.query(User).first()
    new_money.money = money
    save(new_money)
Esempio n. 8
0
import time
import matplotlib.pyplot as plt
import matplotlib.ticker as mticket
import matplotlib.dates as mdates
from matplotlib.finance import candlestick
from project import db
from project.models.history import History
t0 = time.time()
import matplotlib
matplotlib.rcParams.update({'font.size': 9})

symbol = 'AMG'
stocks = db.query(History.date, History.open, History.close, History.high, History.low, History.volume).filter_by(symbol=symbol).all()
stocks_list = [list(tup) for tup in stocks]
# stocks_list = [for x in stocks_list if stocks_list.index(x) == 1]


dates = [stock[0] for stock in stocks]
opens = [stock[1] for stock in stocks]
closes = [stock[2] for stock in stocks]
highs = [stock[3] for stock in stocks]
lows = [stock[4] for stock in stocks]
volumes = [stock[5] for stock in stocks]

x = 0
y = len(dates)
newAr = []
while x < y:
    appendLine = mdates.date2num(dates[x]), opens[x], closes[x], highs[x], lows[x], volumes[x]
    newAr.append(appendLine)
    x += 1
Esempio n. 9
0
def get_money():
    return db.query(User).first().money
Esempio n. 10
0
 def get_all_stocks_symbols():
     all_stocks = db.query(Stock.symbol).all()
     return [x[0] for x in all_stocks]
Esempio n. 11
0
 def get_all_stocks():
     return db.query(Stock).all()
Esempio n. 12
0
def set_money(money):
    new_money = db.query(User).first()
    new_money.money = money
    save(new_money)
Esempio n. 13
0
def get_money():
    return db.query(User).first().money