示例#1
0
    def test_get_set1(self):
        quotes = Quotes()
        sets = quotes.sets()

        for k in sets:
            arr = quotes.get_set(k)
            self.assertIsInstance(arr, list)
示例#2
0
 def get_candle_data(self):
     """株価データ(始値、高値、安値、終値、出来高、日付)を取得する"""
     quotes = Quotes(self.code, self.start, self.end)
     try:
         quotes.get_stock_data()
     except:
         print("存在しないコードです。")
         self.is_exist_code = False
         return
     
     # 株価情報をリスト形式に変換する
     """
     date = [data.date.strftime("%Y-%m-%d") for data in target]
     open = [data.open for data in target]
     close = [data.close for data in target]
     high = [data.high for data in target]
     low = [data.low for data in target]
     volume = [data.volume for data in target]
     """
     # 日付が古い順に並べ替える
     self.ohcl["date"] = quotes.date[::-1]
     self.ohcl["open"] = quotes.open[::-1]
     self.ohcl["close"] = quotes.close[::-1]
     self.ohcl["high"] = quotes.high[::-1]
     self.ohcl["low"] = quotes.low[::-1]
     self.ohcl["volume"] = quotes.volume[::-1]
示例#3
0
def quotes():

    quotes = Quotes()
    persons = quotes.random()
    l = str(persons[1])
    print(l, "\n")
    speak(l)
示例#4
0
def test_add():
    q = Quotes(':memory:', connection)
    q.add("test_id", "author", "text")
    c = connection.cursor()
    c.execute(
        'SELECT * from quotes WHERE chat_id=? and author = ? and quote = ?',
        ('test_id', 'author', 'text'))
    assert c.fetchone() is not None
    return "Quotes adding works"
示例#5
0
def test_search():
    q = Quotes(':memory:', connection)
    q.add('test', 'antani', 'cacca')
    q.add('test', 'antani', 'culo')
    q.add('no', 'antani', 'cacca')
    res = q.search('test', 'cacca')
    assert res[0][2] == 'antani'
    assert len(res) == 1
示例#6
0
    def test_random(self):
        quotes = Quotes()
        keys = ['albert_einstein', 'henry_ford']
        q = quotes.random(keys=keys)
        self.assertTrue(q[0] in ['Albert Einstein', 'Henry Ford'])

        keys = ['emily_carr', 'does not exist']
        q = quotes.random(keys=keys)
        self.assertEqual(q[0], 'Emily Carr')

        q = quotes.random(keys=[])
        self.assertTrue(q is None)
示例#7
0
文件: pages.py 项目: svip/SvipBot
	def fix_quotes(self, content, title):
		# first detect if this article has a detect section.
		if not quotes.has_quote_section(content):
			return content
		# let's get that section out
		section = quotes.get_quote_section(content)
		if section == None:
			return content
		# throw it off to our parser.
		q = Quotes(section)
		tmp = q.get_content()
		if self.debugmode:
			print q.get_content()
		final = content.replace(section, tmp)
		self.log_obtain(q)
		if final==None: # in case we got nothing.
			return content
		return final
示例#8
0
    def test_pick(self):
        quotes = Quotes()
        quote = quotes.pick('albert_einstein', 0)
        self.assertEqual(quote[0], 'Albert Einstein')
        self.assertEqual(quote[1], "You can't blame gravity for falling in love.")

        with self.assertRaises(KeyError):
            quotes.pick('harry_foobar')

        with self.assertRaises(IndexError):
            quotes.pick('albert_einstein', -1)
示例#9
0
def backtest_bollingerband(symbol, start_date, end_date, strategy_id,
                           strategy_option, ma, sigma1, sigma2, initial_cash):
    q = Quotes(symbol, start_date, end_date, ma, sigma1, sigma2)
    t = tick.get_tick(symbol)
    bollinger_butler = bollingerband.Butler(t, ma)
    if strategy_id == 1:
        title = "BollingerBand/DailyTrail SMA%dSD%s" % (
            ma, '{:.1f}'.format(sigma1))
    else:
        title = "BollingerBand/CloseOnDaily SMA%dSD%s" % (
            ma, '{:.1f}'.format(sigma1))
    a = Assets(initial_cash)
    Market().simulator_run(title, strategy_id, strategy_option, q,
                           bollinger_butler, symbol, a, trade_fee)
示例#10
0
 def __get_current_candle_data(self):
     """最新のローソク足のデータを取得する(jsmでは現在値を取得することができないため)"""
     _quotes = Quotes()
     # 過去のデータではなく、最新の日付をend_dateに指定した場合の処理を以下に示す
     if  self.end_date == datetime.date.today().strftime("%Y-%m-%d"):
         # 日本経済新聞のページから現在値(当日の終値) を取得する
         # ※get_priceメソッドで取得したデータの終値が前日の終値のままになっていたため
         _res = requests.get("https://www.nikkei.com/nkd/company/?scode=" + str(self.code))
         _soup = BeautifulSoup(_res.content, 'html.parser')
         _tags = _soup.find(attrs={"class": "m-stockPriceElm_value now"})
         _target = _quotes.get_price(self.code)
         
         if _tags != None:  
             for i, _stock_price_tag in enumerate(_tags):
                 # 2番目の文字は「円」のため、無視する
                 if i == 0:
                     _current_price = float(_stock_price_tag.string.replace(",", ""))
         else:
             # 日経新聞のページから現在の終値を取得できなかった場合はやむを得ずget_priceメソッドの値を採用する
             _current_price = _target.close
         
         # 当日の日足の更新時間が不明なため、前日の値と比較して動作を変える
         # 書き方が汚いため、改善する必要あり
         if (self.ohcl["high"][-1] == _target.high and
            self.ohcl["low"][-1] == _target.low and
            self.ohcl["open"][-1] == _target.open):
                
             self.ohcl["close"][-1] = _current_price
         
         else:
             self.ohcl["date"].append(_target.date)
             self.ohcl["open"].append(_target.open)
             self.ohcl["high"].append(_target.high)
             self.ohcl["low"].append(_target.low)
             self.ohcl["volume"].append(_target.volume)
             self.ohcl["close"].append(_current_price)
示例#11
0
def perform_login():
    if validate_field([usernameEntry, passwordEntry]):
        if is_data_in_file(usernameEntry.get()):
            if is_authentication_valid(usernameEntry.get(),
                                       passwordEntry.get()):
                quote = Quotes().random()
                messagebox.showinfo(
                    'Login successful',
                    'Welcome {0}'.format(get_name(usernameEntry.get())) +
                    '\n\nQuote of the Day \n\n\t{0} \n\t\t\t\t- {1}'.format(
                        quote[1], quote[0]))
            else:
                messagebox.showerror(
                    'Incorrect Login', 'Invalid login credentials.'
                    '\nPlease enter correct username and password')
        else:
            messagebox.showerror(
                'No registered user',
                'Sorry No User found with entered username. Register first')
    else:
        messagebox.showerror('Missing required fields',
                             'Please Enter all fields and try again')
示例#12
0
from quotes import Quotes
import random
my_quote = Quotes()


def get_quotes():
    return my_quote.random()[1]


def get_video():
    arr = [
        "..\static\\admin\img\Pexels%20Videos%201409899.mp4",
        "https://player.vimeo.com/external/269971860.hd.mp4?s=eae965838585cc8342bb5d5253d06a52b2415570&profile_id=175&oauth2_token_id=57447761",
        "https://player.vimeo.com/video/473655823?title=0&portrait=0&byline=0&autoplay=1",
        "https://player.vimeo.com/video/299108946?title=0&portrait=0&byline=0&autoplay=1",
        "https://player.vimeo.com/video/269983448?title=0&portrait=0&byline=0&autoplay=1"
    ]
    return arr[0]
示例#13
0
mysql = MySQL()

#Config MySQL
app.config['MYSQL_DATABASE_USER'] = '******'
app.config['MYSQL_DATABASE_PASSWORD'] = '******'
app.config['MYSQL_DATABASE_DB'] = 'flaskdb'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'

#Initialize MySQL
mysql.init_app(app)
con = mysql.connect()
cursor = con.cursor()

the_quotes = Quotes()
print the_quotes


@app.route('/')
def index():
    return render_template('home.html')


@app.route('/about')
def about():
    return render_template('about.html')


@app.route('/quotes')
def quotes():
def quotes1():
    quotes = Quotes()
    persons = quotes.random()
    l = str(persons[1])
    k = emojis.encode(":sunny:")
    return l + k * 2
示例#15
0
文件: test.py 项目: lkuligin/quotes
#!/usr/bin/env python
# coding: utf8

from quotes import Quotes, Asset
from config import SQLITE_DB_NAME
import sqlite3
from datetime import datetime, date, timedelta
import csv
import get_micex_data
import re

if __name__ == "__main__":
	#res = float(get_micex_data.get_curr_quot('gazprom'))
	#print res, type(res)
	q = Quotes()
	#a1 = q.get_asset_by_id(4)
	assets = q.get_list_of_assets(update = 'yes')
	tbl = q.get_index_view()
	print tbl
	#a1.upload_available_history()
	#a1.download_from_csv('table.csv')
	#a1.upload_available_history()
	#a1.update_current_quote()
	#a = q.get_current_view()
	#print a1
	
	#a1 = q.get_list_of_assets()
	#print a1[0].name
	con = sqlite3.connect(SQLITE_DB_NAME, detect_types=sqlite3.PARSE_DECLTYPES)
	cur = con.cursor()
	d = date.today()
示例#16
0
文件: main.py 项目: admiral0/KiwiBot
from dbutil import minimigrate
from bot_commands import quote_dispatch, help_message

logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO)

logger = logging.getLogger(__name__)

conn_string = 'data/data.sqlite3'

def main():
    bot_api = getenv('KIWI_BOT_API_KEY')
    updater = Updater(bot_api)

    dp = updater.dispatcher

    dp.addTelegramCommandHandler("help", help_message)
    dp.addTelegramCommandHandler("quote", quote_dispatch)

    updater.start_polling()

    updater.idle()

if __name__ == '__main__':
    conn = sqlite3.connect(conn_string)
    minimigrate(conn)
    conn.close()
    Quotes(conn_string)
    main()
示例#17
0
def test_random():
    q = Quotes(':memory:', connection)
    q.add('a', 'b', 'c')
    assert q.random('a') is not None
示例#18
0
from flask import Flask, render_template
from flask_ask import Ask, statement, question
import logging
from quotes import Quotes
from constants import AppConstants

app = Flask(__name__)
app.config['ASK_APPLICATION_ID'] = AppConstants.ALEXA_SKILL_ID

ask = Ask(app, '/')
quoteObj = Quotes()


@app.route('/')
def index():
    return 'welcome to Quotes for the day'


@ask.launch
@ask.intent('quotes')
def quotes():
    info = quoteObj.info()
    text = render_template('quote_not_found')

    if not isinstance(info, dict):
        return statement(text)
    text = info['quote']

    return statement(text).simple_card(title=info['author'],
                                       content=info['quote'])
示例#19
0
from flask import Blueprint,render_template,request,redirect,session,flash,url_for
from quotes import Quotes
from threading import Timer
from datetime import datetime
from Web import db
from functools import wraps
from .functions import attendance,do_process
qt = Quotes()
mod = Blueprint('admin',__name__,template_folder='templates',static_folder='./static',static_url_path='/static/cdn/')

def login_required(f):
    @wraps(f)
    def wrap(*args, **kwargs):
        if 'logged_in' in session:return f(*args, **kwargs)
        else:
            flash("You need to login first")
            return redirect(url_for('admin.do_admin_login'))
    return wrap

@mod.route('/login/', methods=['POST',"GET"])
def do_admin_login():
 if request.method == "POST":
  if request.form['password'] == 'shivjeet' and request.form['username'] == 'Shivjeet':
    session['logged_in'] = True
    return redirect("/admin/")
  else:
    flash("Check Password Or Username!")
    return redirect(url_for('admin.do_admin_login'))
 else:
   if 'logged_in' in session:return redirect("/admin/")
   else:return render_template("admin_login.html")
示例#20
0
 def test_sets(self):
     quotes = Quotes()
     sets = quotes.sets()
     self.assertTrue(type(sets) == list)
     print(sets)
示例#21
0
from quotes import Quotes
from stats import Stats
from urban import Urban
from shared import *

load_dotenv()

#Must be https://discordapp.com/api/webhooks/your_id with no token after the id
WEBHOOK_URL = os.getenv('WEBHOOK_URL')

BOT_TOKEN = os.getenv('BOT_TOKEN')
WEBHOOK_ID = WEBHOOK_URL.split('/')[-1]

bot = commands.Bot(command_prefix='/')
bot.add_cog(Quotes(bot))
bot.add_cog(Stats(bot))
bot.add_cog(Urban(bot))

#### Bot event handlers ####


@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')


@bot.event
示例#22
0
    def perform_backtest(self, strategy):
        """ Perform backtest of strategy (class: Strategy)""" 
            
        # 1 ---- load quotes data ---------------------------------------------
        # get relevant coins
        currency_ids = strategy.currency_ids()
        
        data = Quotes.import_data(currency_ids = currency_ids,
                                  start_date = self.start_date,
                                  end_date = self.end_date)
            
        # 2 ---- use generate_orders() to generate orders ---------------------        
        strategy_orders = strategy.generate_orders(data)

        if not isinstance(strategy_orders, Orders):
            raise TypeError("Orders is not of class 'orders'")        
        
        print(strategy_orders)
        strategy_orders = strategy_orders.get_orders()
        
        # 3 ---- perform backtest ---------------------------------------------
        
        # add cash and columns for currencies
        data["capital"] = 0
        data["actions"] = ""      
        data["description"] = ""
        data["capital"].iloc[0] = self.initial_capital
        data["worth_usd"] = 0
        
        for currency_id in currency_ids:
            data[currency_id + '_position'] = 0
        
        # a sell or buy can influence subsequent positions, so calculate iteratively
        for observation in range(1, len(data.index)):
            
            date = data.index[observation]
            
            print(date)
            
            # investment this period is zero
            investment_capital_period = 0
            
            # amount of currency_ids initially same as last period
            for currency_id in currency_ids:
                data[currency_id + '_position'].iloc[observation] = data[currency_id + '_position'].iloc[observation-1]                    
          
            # at each point, compute size of each position (cash and currencies), and record actions
            if(data.index[observation] in strategy_orders.index):
                                
                action_df = pd.DataFrame(columns=list(["Currency","NominalAmount", "CapitalAmount"]))
                
                # could be multiple actions
                for index, action in strategy_orders.loc[date].iterrows():    
                    currency_id = action['currency_id']
                    signal = action['signal']
                    
                    # Buy
                    if signal == 1:
                        
                        # buy for 10% currency_id
                        investment_capital = data["capital"].iloc[observation-1] * 0.10   

                        # estimate how many coins
                        investment_nominal = round(investment_capital / data[currency_id].iloc[observation])
                        
                        # calculate exact capital needed
                        investment_capital_exact = investment_nominal * data[currency_id].iloc[observation]
                        investment_capital_period = investment_capital_period + investment_capital_exact 
                        
                        # change the amount of currency hold
                        data[currency_id + '_position'].iloc[observation] = data[currency_id + '_position'].iloc[observation-1] + investment_nominal
                        
                        # report action by appending a Series to the (empty) dataframe
                        action_df = action_df.append(pd.Series({"Currency": currency_id, 
                                                                   "NominalAmount": investment_nominal, 
                                                                   "CapitalAmount": investment_capital_exact}),ignore_index=True)
                        
                        # report description
                        data["description"].iloc[observation] = (data["actions"].iloc[observation] + "\n Buy " + 
                                                            str(investment_nominal) + " " + str(currency_id) + 
                                                            " for " + str(investment_capital_exact))
                    
                    # Sell
                    if signal == -1:
                        
                        # sell currency_id for 10% of total capital
                        investment_capital = data["capital"].iloc[observation-1] * 0.10   
                        
                        # estimate how many coins
                        investment_nominal = round(investment_capital / data[currency_id].iloc[observation])
                        
                        # calculate exact capital needed
                        investment_capital_exact = investment_nominal * data[currency_id].iloc[observation]
                        investment_capital_period = investment_capital_period - investment_capital_exact
                        
                        # change the amount of currency hold
                        data[currency_id + '_position'].iloc[observation] = data[currency_id + '_position'].iloc[observation-1] - investment_nominal
                                                
                        # report action
                        action_df = action_df.append(pd.Series({"Currency": currency_id, 
                                                                   "NominalAmount": investment_nominal, 
                                                                   "CapitalAmount": investment_capital_exact}),ignore_index=True)
                                           
                        # report description
                        data["description"].iloc[observation] = data["actions"].iloc[observation] + "Sell " + str(investment_nominal) + " " + str(currency_id) + " for " + str(investment_capital_exact)
                 
                # report actions
                data["actions"].iloc[observation] = action_df.to_json()
                
            # calculate resulting cash capital
            data["capital"].iloc[observation] = data["capital"].iloc[observation-1] - investment_capital_period
            
            # calculate worth by capital (usd) and each currency * price
            data["worth_usd"].iloc[observation] = data["capital"].iloc[observation]
            
        # return a backtest dict, which is a dict
        return {"backtest_df": data, "strategy": strategy}
示例#23
0
 def test_random_pick(self):
     quotes = Quotes()
     picked = [('albert_einstein', 0), ('henry_ford', 1)]
     quote = quotes.random(pick=picked)
     expected = ['Albert Einstein', 'Henry Ford']
     self.assertTrue(quote[0] in expected)
示例#24
0
 def test_rigorous(self):
     quotes = Quotes()
     print(quotes.random())
     self.assertTrue(True)
示例#25
0
from quotes import Quotes
q = Quotes()
qt = q.random()
print('a quote by ' + qt[0] + ' ' + qt[1])
示例#26
0
文件: units.py 项目: cf33/panoandaV20
class Units(object):
    """
    Units calculation class
    
    """
    
    def __init__(self):
        
        self.__quotes = Quotes()
        self.__tickers = Tickers()
        self.__account = Account()
        
            
    def ticker(self, ticker, pips, amount):
        """
        Returns units calculated according an currency account amount
        
        :param: ticker
        :type: str
        
        :param: pips
        :type: int
        
        :param: amount (account currency)
        :type: float
        
        :return: int
        """
        #Define variables
        quote = ticker.split('_')[1]
        
        
        
        #It is not available EUR_XXX quotes but we can get this value
        # doing (1 / XXX_EUR)
        curr = self.__account.currency

        if curr == 'USD':
        
            position_risk_quote = (amount * (1 / 
                                self.__quotes.__currency_account_pricing_USD(
                                quote + '_' +  self.__account.currency)))
        else:

            position_risk_quote = (amount * (1 / 
                                self.__quotes.__currency_account_pricing_notUSD(
                                quote + '_' +  self.__account.currency)))

        
        pip_value_quote = position_risk_quote / pips
        
        units = (pip_value_quote * (1 / 
                             self.__tickers.tick_value(ticker)))
        
        return int(round(units,0))
    
    def dataframe(self, *args):
        """
        Returns units calculated dataframe format
        
        Example:
            
            units.dataframe( 300, *(tickers, pips))
            
            tickers, pips -> list, tuple or dataframe index
    
        """
        
        df_total = pd.DataFrame()
        
        for instr, pips, amount  in zip(*args):
            
            units = self.ticker(instr,pips, amount)
            
            df_output = pd.DataFrame({'ticker': instr, 
                                      'units': [units]})            
            df_output.set_index('ticker',inplace = True)
            
            df_total = df_total.append(df_output)
        
        return df_total
示例#27
0
 def gonoobs(self):
     q=Quotes()
     qt=q.random()
     speak('a quote by '+qt[0]+' '+qt[1])
示例#28
0
文件: units.py 项目: cf33/panoandaV20
 def __init__(self):
     
     self.__quotes = Quotes()
     self.__tickers = Tickers()
     self.__account = Account()
示例#29
0
async def on_ready():
    print('We have logged in as {0.user}'.format(client))


@client.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandNotFound):
        msg = ctx.message.content[1:]
        words = msg.split(' ')
        cmd = words[0]
        args = words[1:]
        aliased_command = session.query(Alias).filter(
            Alias.server_id == ctx.guild.id, Alias.alias == cmd).one_or_none()
        if not (aliased_command is None):
            new_msg = ' '.join([aliased_command.command] + args)
            ctx.message.content = new_msg
            await client.get_command(aliased_command.command).invoke(ctx)
        elif '*' in msg:
            # This was just someone using italics
            return
        else:
            await ctx.send(f"Unrecognized command: '{cmd}'")
    else:
        raise error


client.add_cog(Quotes(client))
client.add_cog(ModRoles(client))
client.add_cog(Mutes(client))
client.add_cog(Aliases(client))
示例#30
0
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
My first Flask app
"""
# Importera relevanta moduler
from flask import Flask, render_template
from person import Person
from quotes import Quotes

pn = Person('olov')
qu = Quotes('quotes.json')

app = Flask(__name__, static_url_path="/static")

course = "Objektorienterad Python"


@app.route("/")
def main():
    """ Main route """
    return (render_template("index.html",
                            name=pn.name,
                            school=pn.school,
                            img=pn.get_image_link(),
                            age=pn.calculate_age(),
                            course=course,
                            quote=qu.random_quote()))


@app.route("/about")
示例#31
0
 def test_persons(self):
     quotes = Quotes()
     persons = quotes.persons()
     self.assertTrue(type(persons) == list)
     print(persons)
示例#32
0
type_def = """
    type Quote {
        name: String
        progress: Int
        quote: String
    }
    type Query {
        _unused: Boolean
    }
    type Subscription {
        quote(author: String!): Quote!
    }
"""

subscription = SubscriptionType()
q = Quotes()


@subscription.source('quote')
async def quote_gen(obj, info, author):
    try:
        print(info.context)
        print('quote generator started')
        seq = 0
        for i in range(100):
            await asyncio.sleep(1)
            quote = q.random()
            print(f'generate quotei {i}')
            yield {
                'name': quote[0] + ' ' + author,
                'progress': i,