def caculate_model(sid, nday): s = stock("測試資料/台股/{0}d.csv".format(sid)) if s.complate_data(sid): # 如果有新的資料,再重新laod 一次 s = stock("測試資料/台股/{0}d.csv".format(sid)) tmp12 = (mdates.num2date(s.date[-1]).strftime("%Y/%m/%d")) print(tmp12)
def caculate_model(sid, nday): s = stock("測試資料/台股/{0}d.csv".format(sid)) if s.complate_data(sid) : # 如果有新的資料,再重新laod 一次 s = stock("測試資料/台股/{0}d.csv".format(sid)) tmp12 = (mdates.num2date(s.date[-1]).strftime("%Y/%m/%d")) print(tmp12)
def test_get_exp_date(self): # test accuracy of months returned from db stock_obj = stock('SVU', datetime.strptime('2016-10-12', '%Y-%m-%d')) for month in ['November2016', 'October2016']: month_check = stock_obj.exp_dates['Expiration_Date'].str.contains(month).any() assert month_check == True # test expiraiton within current month stock_obj = stock('SVU', datetime.strptime('2016-10-07', '%Y-%m-%d')) assert stock_obj.expiration == 'November2016' # test expiration next month stock_obj = stock('SVU', datetime.strptime('2016-10-19', '%Y-%m-%d')) assert stock_obj.expiration == 'October2016'
def buildDf(name, rebuild=False): try: if (rebuild == False): df = pd.read_csv(str(name) + ".csv") return df else: raise Exception except: #ZF is the zip file with all the stocks and etfs broken up into the two folders "Stocks/ for stock name or ETFs/ for etf name #I then add the columns I think might be useful such as day of week, moving averages, targetColumn which is the cross over and the #updown for other testing. zf = zipfile.ZipFile('Data.zip') df = pd.read_csv(zf.open("ETFs/" + name + '.us.txt')) targetStock = stock(df) print("adding day col") df = targetStock.addDayCol(df) print("adding MA10 col") df = targetStock.addMaCol(df, 'MA10', 10) print("adding MA50 col") #df = targetStock.addMaCol(df,'MA20',20) df = targetStock.addMaCol(df, 'MA50', 50) print("adding Target col") df = targetStock.addTargetCol(df) print("adding UpDown col") df = targetStock.addUpDownCol(df) print("adding crossUpCrossDownCols") df = targetStock.addCrossUpCrossDownCols(df) #df = targetStock.addMaCol(df,'M,A100',100) df.to_csv(path_or_buf=str(name) + ".csv") return df
def valueStocks(ticker, sheetClass, cellnumber): ''' Check When to buy when to sell. Find the risk-rewards Check how managment is doing ''' TMK = stock(ticker) ###################### Current price to book ratio ################# TMK.bookValuePerShare() TMK.pricePerBookValue() print ("Current Price: ", TMK.trade_history["Close"][-1]) print ("Book value: %0.2f" %(TMK.trading["book value per share"][0])) print ("Price - book value: %0.2f " %(TMK.trading["price-book value"][0])) #print ("Sell at: %0.2f" % (TMK.trading["book value per share"][0]*2)) print ("Percent return: %0.2f%%" %(100*(TMK.trading["book value per share"][0]-TMK.trade_history["Close"][-1])/TMK.trade_history["Close"][-1]) ) msg = "%s: \nCurrent Price:\t\t%0.2f\nBook value:\t\t%0.2f\nPercentage to BV:\t%0.2f\n\n"%(ticker, TMK.trade_history["Close"][-1], TMK.trading["book value per share"][0], float(TMK.trading["book value per share"][0]-TMK.trade_history["Close"][-1])/TMK.trade_history["Close"][-1]) sheetClass.append(range_name="Example!A" + str(cellnumber), item=str(ticker)) sheetClass.append(range_name="Example!C" + str(cellnumber), item="%0.2f" %TMK.trading["book value per share"][0]) sheetClass.append(range_name="Example!H" + str(cellnumber), item="%0.2f" %TMK.trade_history["Close"][-1]) return msg
def main(): robin = stock('/home/dosx/.tokens/info.txt') for symbol in robin.watchlist(): print(symbol) prices = robin.history(symbol) print(f"SMA: {robin.SMA(prices)}") print(f"EMA: {robin.EMA(prices)}")
def __init__(self, filename, nday=40, BIAS_std1=0.15, BIAS_std2=1): # for traning data, 自動找出最佳的 乖離率 print(filename, nday) self.nday = nday self.BIAS_std1 = BIAS_std1 self.BIAS_std2 = BIAS_std2 self.s = stock(filename, adj_fix=False) _, self.list_ma = self.s.feature_MA(nday) self.list_ma_slope = np.array(self.s.feature_MA_slope(nday)) # 均線斜率 self.list_BIAS = self.s.feature_BIAS(nday) self.BIAS_mean = self.list_BIAS[nday:].mean() self.BIAS_std = self.list_BIAS[nday:].std() self.list_line1 = (self.BIAS_mean + self.BIAS_std1 * self.BIAS_std) * self.list_ma + self.list_ma self.list_line2 = (self.BIAS_mean - self.BIAS_std1 * self.BIAS_std) * self.list_ma + self.list_ma self.list_line3 = (self.BIAS_mean + self.BIAS_std2 * self.BIAS_std) * self.list_ma + self.list_ma self.list_line4 = (self.BIAS_mean - self.BIAS_std2 * self.BIAS_std) * self.list_ma + self.list_ma # 均線向下時,放寬 self.ma_slope_down = self.list_ma_slope[nday:].mean( ) - self.BIAS_std1 * self.list_ma_slope[nday:].std() if self.ma_slope_down > 0: self.ma_slope_down = 0 # 均線向上時,放寬 self.ma_slope_up = self.list_ma_slope[nday:].mean( ) + self.BIAS_std1 * self.list_ma_slope[nday:].std()
def __init__(self, filename, nday=40, BIAS_std1=0.15, BIAS_std2=1): # for traning data, 自動找出最佳的 乖離率 print(filename, nday) self.nday = nday self.BIAS_std1 = BIAS_std1 self.BIAS_std2 = BIAS_std2 self.s = stock(filename, adj_fix = False) _, self.list_ma = self.s.feature_MA(nday) self.list_ma_slope = np.array(self.s.feature_MA_slope(nday)) # 均線斜率 self.list_BIAS = self.s.feature_BIAS(nday) self.BIAS_mean = self.list_BIAS[nday:].mean() self.BIAS_std = self.list_BIAS[nday:].std() self.list_line1 = (self.BIAS_mean + self.BIAS_std1 * self.BIAS_std) * self.list_ma + self.list_ma self.list_line2 = (self.BIAS_mean - self.BIAS_std1 * self.BIAS_std) * self.list_ma + self.list_ma self.list_line3 = (self.BIAS_mean + self.BIAS_std2 * self.BIAS_std) * self.list_ma + self.list_ma self.list_line4 = (self.BIAS_mean - self.BIAS_std2 * self.BIAS_std) * self.list_ma + self.list_ma # 均線向下時,放寬 self.ma_slope_down = self.list_ma_slope[nday:].mean() - self.BIAS_std1 * self.list_ma_slope[nday:].std() if self.ma_slope_down > 0: self.ma_slope_down = 0 # 均線向上時,放寬 self.ma_slope_up = self.list_ma_slope[nday:].mean() + self.BIAS_std1 * self.list_ma_slope[nday:].std()
def test(): symbol = 'INTC' name = 'Intel Corporation' pcp = 20.5 cp = 20.35 s1 = stock(symbol, name, pcp, cp) print(s1.getChangePercent())
def __init__(self, wl): ''' :param wl: [[code, '字段', '目标方向', '目标', '有效性'], [2078, 'price', '低',7, True]] 监控字段包括:价格、pe ''' self.__stock = stock.stock() self.__watchList = wl
def test(): nday = 20 s = stock("測試資料/台股/0056d.csv") x = s.feature_diff()[nday:] * 100 a, b = tools.normfun_ex(x) plt.plot(a, b, color='g', linewidth=1) plt.hist(x, 60, normed=1, facecolor='blue', alpha=0.5) plt.show()
def test(): nday = 20 s = stock("測試資料/台股/0056d.csv") x = s.feature_diff()[nday:]*100 a, b = tools.normfun_ex(x) plt.plot(a, b, color='g', linewidth=1) plt.hist(x, 60, normed=1, facecolor='blue', alpha=0.5) plt.show()
def test_K(): # K, D無常態分佈 nday = 10 s = stock("price_data.csv") x = s.feature_K() x = np.array(x[nday:]) a, b = tools.normfun_ex(x) plt.plot(a, b, color='g', linewidth=1) plt.hist(x, 60, normed=1, facecolor='blue', alpha=0.5) plt.show()
def stockProcess(): global strategy print "" print("DIGITAL STOCK TRADER") print( "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////BALANCE: %s" % variables.balance) print "" sleep = ''' sleep %s; ''' % (variables.sleepTime) while variables.balance >= 0: variables.hourMin = int(time.strftime("%H%M")) variables.day = datetime.datetime.now().strftime("%A") if variables.forceCycle or ( variables.hourMin > variables.startTime ) and (variables.hourMin < variables.endTime ) and variables.day != "Saturday" and variables.day != "Sunday": for strategyName in variables.strategy: strategy = getattr( __import__("strategies", fromlist=[strategyName]), strategyName) temp = variables.balance #BUYSTOCK: Buys the stock once certain criteria are met. Finviz provides the initial batch buyList = csvReader.csvReader(strategy.buyStrategy) for row in buyList: order = stock.stock(row[1]) buyStock(order) #SELLSTOCK: Sells stock in portfolio once certian criteria are met for order in reversed(variables.portfolio): sellStock(order) if temp != variables.balance: print( "///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////BALANCE: %s" % variables.balance) print "" subprocess.call(['sh', '-c', sleep]) reloadVariables.reloadVariables()
def __init__(self, filename, nday=40, BIAS_std1=0.15, BIAS_std2=1): # for traning data, 自動找出最佳的 乖離率 self.nday = nday self.BIAS_std1 = BIAS_std1 self.BIAS_std2 = BIAS_std2 self.s = stock(filename) # self.s = stock_5day(filename) self.list_ma = self.s.feature_MA(nday) self.list_ma_slope = np.array(self.s.feature_MA_slope(nday)) # 均線斜率 self.list_BIAS = self.s.feature_BIAS(nday) self.BIAS_mean = self.list_BIAS[nday:].mean() self.BIAS_std = self.list_BIAS[nday:].std() def fa(x): if x > 0: return True else: return False def fb(x): if x > 0: return False else: return True x1 = np.array(list(filter(fa, self.list_BIAS))) x2 = np.array(list(filter(fb, self.list_BIAS))) self.list_line1 = (tools.list_percentage(x1, BIAS_std1) + 1) * self.list_ma self.list_line3 = (tools.list_percentage(x1, BIAS_std2) + 1) * self.list_ma self.list_line2 = (tools.list_percentage(x2, (1 - BIAS_std1)) + 1) * self.list_ma self.list_line4 = (tools.list_percentage(x2, (1 - BIAS_std2)) + 1) * self.list_ma print(tools.list_percentage(self.list_BIAS, 0.1), tools.list_percentage(self.list_BIAS, 0.5), tools.list_percentage(self.list_BIAS, 0.6), tools.list_percentage(self.list_BIAS, 0.85)) # 均線向下時,放寬 self.ma_slope_down = self.list_ma_slope[nday:].mean( ) - 0.15 * self.list_ma_slope[nday:].std() if self.ma_slope_down > 0: self.ma_slope_down = 0 # 均線向上時,放寬 self.ma_slope_up = self.list_ma_slope[nday:].mean( ) + 0.15 * self.list_ma_slope[nday:].std()
def main(): while True: print("你可以进行如下操作:") print("c:收银系统 i:库存系统 s:进货系统 t:今日销量 g:修改商品信息 e:退出") op = input("请输入你的选择:") if op == 'c': csr.cashier() # break elif op == 'i': inventory.inventory() # break elif op == 's': stock.stock() # break elif op == 't': selltoday.selltoday() # break elif op == 'g': change.change() elif op == 'e': exit() else: print("操作不正确,请重新输入")
def get_all_stocks(self): result = [] from stock import stock high_url = 'https://www.nseindia.com/content/CM_52_wk_High_low.csv' import csv import urllib2 req = urllib2.Request(high_url, headers={'User-Agent': "Magic Browser"}) response = urllib2.urlopen(req) cr = csv.reader(response) high_dict = {} for row in cr: if len(row) < 2: continue if row[1] != 'EQ': continue #print row high_dict[row[0]] = row[2] import datetime for i in range(5): d = datetime.datetime.now() - datetime.timedelta(days=i) try: ltp_url = 'https://www.nseindia.com/archives/equities/mkt/MA' + d.strftime( "%d") + d.strftime("%m") + d.strftime("%y") + '.csv' #print ltp_url req = urllib2.Request(ltp_url, headers={'User-Agent': "Magic Browser"}) response = urllib2.urlopen(req) break except urllib2.HTTPError: continue cr = csv.reader(response) ltp_dict = {} import industry for row in cr: if len(row) != 6: continue if row[2] != 'EQ': continue if row[1] not in industry.watchlist: continue if row[1] not in high_dict: continue s = stock(name=row[1], high52=int(float(high_dict[row[1]])), ltp=int(float(row[3])), tradevalue=int(float(row[4]))) result.append(s) return result
def method1(): filename = 'sample.txt' infile = open(filename, 'r') lines = infile.readlines() l = lines[0].strip('\r\n').split() m = int(l[0]) # amount of money k = int(l[1]) # number of different stocks d = int(l[2]) # number of remaining days data = readFile(filename) stock_list = [] for stock_name in data: newStock = stock(stock_name, map(float,data[stock_name][1:]), int(data[stock_name][0]), 'NONE') stock_list.append(newStock) stock_list = analyze_stock_list(stock_list)
def __init__(self, filename, nday, Bias1, Bias2, Bias3, Bias4, ma_slope_down, ma_slope_up): # for test data, 手動帶入所有參數 self.nday = nday self.s = stock(filename) self.list_ma = self.s.feature_MA(nday) self.list_ma_slope = np.array(self.s.feature_MA_slope(nday)) # 均線斜率 self.list_line1 = (Bias1) * self.list_ma + self.list_ma self.list_line2 = (Bias2) * self.list_ma + self.list_ma self.list_line3 = (Bias3) * self.list_ma + self.list_ma self.list_line4 = (Bias4) * self.list_ma + self.list_ma self.ma_slope_down = ma_slope_down self.ma_slope_up = ma_slope_up
def solve(self): """solve the problem with a relaxed optimality constraint.""" while self.get_num_parts_left() > 0: if len(self.stocks) == 0: self.stocks.append(stock(5600))#add another stock if we run out for s in self.stocks: p = self.get_largest_fitting_part(s) if p != None: p.cut += 1 s.cut(p) else: self.patterns.append(s) self.stocks.remove(s) #add all of the partially cut stocks to the patterns self.patterns.extend(self.stocks)
def get(): n = body.args['stock'] print '\nLoading', n, '\n' x = stock.stock(n) nums = x.getPrices() fin = x.getFin() return jsonify({ 'n': x.getName(), 'p': nums[0], 'diff': nums[1], 'op': nums[2], 'cap': fin[0], 'eps': fin[1], 'pe': fin[2], 'de': fin[3], 'pb': fin[4] })
def stockProcess(): global strategy print "" print ("DIGITAL STOCK TRADER") print("////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////BALANCE: %s" % variables.balance) print "" sleep = ''' sleep %s; ''' % (variables.sleepTime) while variables.balance >= 0: variables.hourMin = int(time.strftime("%H%M")) variables.day = datetime.datetime.now().strftime("%A") if variables.forceCycle or (variables.hourMin > variables.startTime) and (variables.hourMin < variables.endTime) and variables.day != "Saturday" and variables.day != "Sunday": for strategyName in variables.strategy: strategy = getattr(__import__("strategies", fromlist=[strategyName]), strategyName) temp = variables.balance #BUYSTOCK: Buys the stock once certain criteria are met. Finviz provides the initial batch buyList = csvReader.csvReader(strategy.buyStrategy) for row in buyList: order = stock.stock(row[1]) buyStock(order) #SELLSTOCK: Sells stock in portfolio once certian criteria are met for order in reversed(variables.portfolio): sellStock(order) if temp != variables.balance: print("///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////BALANCE: %s" % variables.balance) print "" subprocess.call(['sh','-c',sleep]) reloadVariables.reloadVariables()
def __init__(self, filename, nday=40, BIAS_std1=0.15, BIAS_std2=1): # for traning data, 自動找出最佳的 乖離率 self.nday = nday self.BIAS_std1 = BIAS_std1 self.BIAS_std2 = BIAS_std2 self.s = stock(filename) # self.s = stock_5day(filename) self.list_ma = self.s.feature_MA(nday) self.list_ma_slope = np.array(self.s.feature_MA_slope(nday)) # 均線斜率 self.list_BIAS = self.s.feature_BIAS(nday) self.BIAS_mean = self.list_BIAS[nday:].mean() self.BIAS_std = self.list_BIAS[nday:].std() def fa(x): if x >0: return True else: return False def fb(x): if x >0: return False else: return True x1 = np.array(list(filter(fa,self.list_BIAS))) x2 = np.array(list(filter(fb,self.list_BIAS))) self.list_line1 = (tools.list_percentage(x1,BIAS_std1)+1)* self.list_ma self.list_line3 = (tools.list_percentage(x1,BIAS_std2)+1)* self.list_ma self.list_line2 = (tools.list_percentage(x2,(1-BIAS_std1))+1)* self.list_ma self.list_line4 = (tools.list_percentage(x2,(1-BIAS_std2))+1)* self.list_ma print(tools.list_percentage(self.list_BIAS,0.1), tools.list_percentage(self.list_BIAS,0.5), tools.list_percentage(self.list_BIAS,0.6), tools.list_percentage(self.list_BIAS,0.85)) # 均線向下時,放寬 self.ma_slope_down = self.list_ma_slope[nday:].mean() - 0.15 * self.list_ma_slope[nday:].std() if self.ma_slope_down > 0: self.ma_slope_down = 0 # 均線向上時,放寬 self.ma_slope_up = self.list_ma_slope[nday:].mean() + 0.15 * self.list_ma_slope[nday:].std()
def netAssetValue(self): self.stocks = [] current_positions = [] for item in self.portfolio_: stock_obj = stock(item['ticker']) stock_obj.get_history() time.sleep(2) current_positions.append(stock_obj.get_current()) stock_obj.driver.terminate() self.stocks.append(stock_obj) original_positions = [item['entry_price'] for item in self.portfolio_] self.netValue = 0 for index, pair in enumerate(zip(current_positions, original_positions)): running_net = (pair[0] - pair[1]) * self.portfolio_[index]['quantity'] self.stocks[index].delta = running_net self.netValue += running_net
def test_BIAS(): #計算乖離率, 有常態分佈 nday = 50 f_name = "測試資料/台股/HYGd.csv" # s = stock_daytrade(f_name) s = stock(f_name) c = np.array(s.close) o = np.array(s.opened) x = s.feature_BIAS(nday) x = x[nday:] # x = tools.time_filter(x, s.date,9*60,11*60) a, b = tools.normfun_ex(x) plt.plot(a, b, color='g', linewidth=1) plt.hist(x, 50, normed=1, facecolor='blue', alpha=0.5) plt.show() def fa(x): if x > 0: return True else: return False def fb(x): if x > 0: return False else: return True x1 = np.array(list(filter(fa, x))) x2 = np.array(list(filter(fb, x))) print(x1) a, b = tools.normfun_ex(x1) plt.plot(a, b, color='g', linewidth=1) plt.hist(x1, 50, normed=1, facecolor='blue', alpha=0.5) plt.show() a, b = tools.normfun_ex(x2) plt.plot(a, b, color='g', linewidth=1) plt.hist(x2, 50, normed=1, facecolor='blue', alpha=0.5) plt.show()
def test_BIAS(): #計算乖離率, 有常態分佈 nday = 50 f_name = "測試資料/台股/HYGd.csv" # s = stock_daytrade(f_name) s = stock(f_name) c = np.array(s.close) o = np.array(s.opened) x = s.feature_BIAS(nday) x = x[nday:] # x = tools.time_filter(x, s.date,9*60,11*60) a, b = tools.normfun_ex(x) plt.plot(a, b, color='g', linewidth=1) plt.hist(x, 50, normed=1, facecolor='blue', alpha=0.5) plt.show() def fa(x): if x >0: return True else: return False def fb(x): if x >0: return False else: return True x1 = np.array(list(filter(fa,x))) x2 = np.array(list(filter(fb,x))) print(x1) a, b = tools.normfun_ex(x1) plt.plot(a, b, color='g', linewidth=1) plt.hist(x1, 50, normed=1, facecolor='blue', alpha=0.5) plt.show() a, b = tools.normfun_ex(x2) plt.plot(a, b, color='g', linewidth=1) plt.hist(x2, 50, normed=1, facecolor='blue', alpha=0.5) plt.show()
# -*- coding: utf-8 -*- import numpy as np import sys import tools from stock import stock from stock import stock_5day from datetime import datetime import matplotlib.pyplot as plt import matplotlib.dates as mdates if __name__ == '__main__': sid = sys.argv[1] #s = stock("測試資料/台股/{0}.csv".format(sid)) s = stock("測試資料/台股/{0}.csv".format(sid), adj_fix=True) # yahoo 的還原資料 # nday = int(sys.argv[2]) #設定主軸 period = 12 date, data = s.feature_Annualized(1, period) date2, data2 = s.feature_Annualized(2, period) date3, data3 = s.feature_Annualized(3, period) date4, data4 = s.feature_Annualized(4, period) date5, data5 = s.feature_Annualized(5, period) date6, data6 = s.feature_Annualized(6, period) date7, data7 = s.feature_Annualized(7, period) date8, data8 = s.feature_Annualized(8, period) date9, data9 = s.feature_Annualized(9, period) date10, data10 = s.feature_Annualized(10, period) #print("{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10} {11} {12} {13} {14}".format( # round(np.average(data),2),round(np.std(data),2),round(np.min(data),2),
import numpy as np import matplotlib.pyplot as plt def wsbMomentum(ticker,n_days=400,fEMA_period=22,sEMA_period=11,ema_IS=13, fast_ema_IS=12, slow_ema_IS=26, `signal_IS=9): ''' Weekly Impulse: 0, red; 1, green; 2, neutral after red. Daily Impulse: 0, red; 1, green; 2, neutral after red. Daily Price: 0, above value; 1, in the value zone; 2, below value - between the two ema MACD-H bullish divergece: Perfection: ''' score = 0 # Data stock_daily = stock(ticker, days=n_days) stock_weekly = stock(ticker, days=n_days, period="weekly") # Weekly Impulse stock_weekly.Impulse_System(plot_data=False) score += (stock_weekly.impulse_data[-1] + 1) # Daily Impulse stock_daily.Impulse_System(plot_data=False) score += (stock_daily.impulse_data[-1] + 1) # Daily Price fast_ema = stock_daily.EMA(period=fEMA_period, plot_data = False) slow_ema = stock_daily.EMA(period=sEMA_period, plot_data = False)
async def on_message(message): if message.author == client.user: return if message.content.lower() == 'hi PieDE'.lower() or message.content.lower( ) == 'hello PieDE'.lower(): author = message.author.name output = "OMG, " + author + " HI HI HI HI!" await message.channel.send(output) if message.content.startswith('$'): symbol = message.content.replace('$', '') output = stock.stock(symbol) await message.channel.send(output) if message.content.startswith('alert '): symbol = message.content.replace('alert ', '') output = stock.alert(symbol) await message.channel.send(output) if message.content == '!kitty' or message.content == '!cat': kitty.getCatLink() await message.channel.send(file=discord.File('img/temp-cat.jpg')) #WORK IN PROGRESS if message.content.startswith('!t2s'): translate = message.content[5:] t2s.synthesize_ssml(translate) channel = message.author.voice.channel vc = await channel.connect() vc.play(discord.FFmpegPCMAudio('output.mp3'), after=lambda e: print(audio_complete_msg, e)) if message.content.startswith('!sax'): channel = message.author.voice.channel vc = await channel.connect() await message.channel.send(file=discord.File('preload/saxgif.gif')) time.sleep(0.5) vc.play(discord.FFmpegPCMAudio('preload/sax.mp3'), after=lambda e: print(audio_complete_msg, e)) time.sleep(8) await message.channel.purge(limit=1, check=is_me) guild = message.guild voice_client = guild.voice_client await voice_client.disconnect() if message.content.startswith('!play'): channel = message.author.voice.channel await message.delete() await message.channel.send("Playing...") url = "" url = message.content[6:] if url != "": ytaudio.createAudio(url) vc = await channel.connect() vc.play(discord.FFmpegPCMAudio('temp-audio.mp3'), after=lambda e: print(audio_complete_msg, e)) if message.content.startswith('!code'): wf = open("userUploadPie.py", "w") wf.write(message.content[5:]) wf.close() output = convertPiethon.convert() for i in output: await message.channel.send(i) if message.content == '!leave': guild = message.guild voice_client = guild.voice_client await voice_client.disconnect()
import config_fund Configs = config_fund.Configs def get_datetime_cnyes_date(tradeDate): excel_date = (tradeDate/86400) + 25569.333333333333 # to excel date a = xlrd.xldate_as_tuple(excel_date,0) day_str = "{0}-{1}-{2}".format(a[0],a[1],a[2]) #print(day_str) dt = datetime.strptime(day_str,'%Y-%m-%d') return dt for config in Configs: print ("\r\n == ",config) s = stock(config['file_path']) last_date = s.date[-1] #print(last_date) #配息 URL = "http://fund.cnyes.com/api/v1/fund/{0}/dividend?page=".format(config['cnyes_id']) with urllib.request.urlopen("{0}1".format(URL)) as url: data = json.loads(url.read().decode()) last_page = data['items']['last_page'] dividend_date = [] dividend_val = [] for page in range(1,last_page+1): print (page, "/", last_page) with urllib.request.urlopen("{0}{1}".format(URL,page)) as url:
return parts_left """return the part that minimizes stocksize - part size, return none if no part will fit""" def get_largest_fitting_part(self, stock): largest = None for p in self.parts: if p.remaining() > 0 and p.length < stock.length: if largest is None or p.length > largest.length: largest = p return largest def get_waste(self): sum_waste = 0 for p in c.patterns: sum_waste += p.get_waste() percent_waste = sum_waste / (5600*len(self.patterns)) * 100 return percent_waste, sum_waste if __name__ == "__main__": stocks = [stock(5600)] #for now assume that we have an unlimited quantitiy of stock parts = [part(1380, 22), part(1520, 25), part(1560, 12), part(1710, 14) , part(1820,18), part(1880, 18), part(1930, 20), part(2000, 10), part(2050, 12), part(2100, 14), part(2140, 16), part(2150, 18), part(2200, 20)] c = cutter(stocks, parts) c.solve() p_waste, s_waste = c.get_waste() print "percent waste: " , p_waste print "total waste: " , s_waste print "number of patterns: " , len(c.patterns)
def decorated_stock(message): stock(message)
def insertData(self, cr, uid, com, tallyData): a = tallyData pool = self.getPoolObj(cr) account, acc_type = self.getAccountObj(pool) uomObj, prodObj, prodCatObj, currencyObj = self.getStockObj(pool) godownObj = self.getStockLocationObj(pool) empObj = self.getEmployeeObj(pool) if a.has_key('TALLYMESSAGE'): l = len(a['TALLYMESSAGE']) dic = {} if l <= 0: pass elif l < 2: #for single record [TALLYMESSAGE] is dictionary. k = a['TALLYMESSAGE'].keys()[0] dic = a['TALLYMESSAGE'][k] if (k == 'GROUP' or k == 'LEDGER'): if dic.has_key('NAME') and dic['NAME']: obj_ledgers = ledgers.ledgers() obj_ledgers.insertRecords(cr, uid, dic, com, account, acc_type) elif (k == 'UNIT'): obj_stock = stock.stock() obj_stock.insertUnits(cr, uid, uomObj, dic) elif (k == 'STOCKGROUP'): obj_stock = stock.stock() obj_stock.insertStockGroups(cr, uid, prodCatObj, dic) elif (k == 'STOCKITEM'): obj_stock = stock.stock() obj_stock.insertStockItems(cr, uid, prodObj, uomObj, prodCatObj, dic, com) elif (k == 'CURRENCY'): obj_stock = stock.stock() obj_stock.insertCurrencies(cr, uid, currencyObj, dic, com) elif (k == 'GODOWN'): obj_stock = stock.stock() obj_stock.insertGodowns(cr, uid, godownObj, dic, com) elif (k == 'COSTCENTRE'): obj_employee = employee.employee() obj_employee.insertEmployees(cr, uid, empObj, dic, com) else: #for multiple records [TALLYMESSAGE] is list of dictionaries. for i in a['TALLYMESSAGE']: k = i.keys()[0] dic = i[k] if (k == 'GROUP' or k == 'LEDGER'): if dic.has_key('NAME') and dic['NAME']: obj_ledgers = ledgers.ledgers() obj_ledgers.insertRecords(cr, uid, dic, com, account, acc_type) elif (k == 'UNIT'): obj_stock = stock.stock() obj_stock.insertUnits(cr, uid, uomObj, dic) elif (k == 'STOCKGROUP'): obj_stock = stock.stock() obj_stock.insertStockGroups(cr, uid, prodCatObj, dic) elif (k == 'STOCKITEM'): obj_stock = stock.stock() obj_stock.insertStockItems(cr, uid, prodObj, uomObj, prodCatObj, dic, com) elif (k == 'CURRENCY'): obj_stock = stock.stock() obj_stock.insertCurrencies(cr, uid, currencyObj, dic, com) elif (k == 'GODOWN'): obj_stock = stock.stock() obj_stock.insertGodowns(cr, uid, godownObj, dic, com) elif (k == 'COSTCENTRE'): obj_employee = employee.employee() obj_employee.insertEmployees(cr, uid, empObj, dic, com)
tickers = [] invested = [] average_price = [] for line in text: tempLine = line.split("\n") temp = tempLine[0].split(":") tickers.append(temp[0]) invested.append(float(temp[1])) average_price.append(float(temp[2])) plot_handels = [] total_percentage = [] total_returns = [] for i in xrange(0, len(tickers)): print "Loading data from ", tickers[i] scraped_data = stock(tickers[i]) return_investment = [] percent_return = [] for j in xrange(0, len(scraped_data.historic["date"])): [return_investment, percent_return] = scraped_data.investment_return(average_price[i]) if not i: total_percentage.append(percent_return[j]) total_returns.append(return_investment[j]) else: total_percentage[j] = total_percentage[j] + percent_return[j] total_returns[j] = total_returns[j] + return_investment[j]
def main(): # Extract the data from g sheets test = Gsheet(MAINSPREADSHEET_ID) raw = test.get_values() # convert the data to list temp = [[c for c in r] for r in raw] # convert all the string date into datetime class for i in range(1, len(temp)): temp[i][0] = datetime.datetime.strptime(temp[i][0], "%m/%d/%Y") # convert list into numpy data = np.array(temp) #.astype(str) # Convert numpy into pandas Book = pd.DataFrame(data=data[1:, 1:], index=data[1:, 0], columns=data[0, 1:]) # Filter all Ticker and remove repetitve Investment_ticker = list(set(Book['Ticker'].tolist())) # Get the stock data # Book.index[0]+datetime.timedelta(15) #print (Investment_ticker) set_data = {} print("Loading stock history") for ticker in Investment_ticker: print(ticker) temp_ETF = stock(ticker, from_date=Book.index[0], to_date=datetime.datetime.today()) # Convert all the dataa tonumber of shares Investment_data(temp_ETF, Book) # Add the stock to the panel #temp_ETF.plot_line(day_value="Close") set_data[ticker] = temp_ETF.trade_history # Check the size of data. Must be equal at all times for ticker in Investment_ticker: date_index = set_data[ticker].index L = len(set_data[ticker]) try: if L < prev_L: for idx, val in enumerate(prev_dateI): if val > date_index[0]: i = idx break temp_col = list(set_data[ticker].columns.values) temp_prev_data = pd.DataFrame(data=np.zeros( (len(prev_dateI[:i - 1]), len(temp_col))), index=prev_dateI[:i - 1], columns=temp_col) set_data[ticker] = temp_prev_data.append(set_data[ticker]) continue except UnboundLocalError: pass prev_L = L prev_dateI = date_index # Convert data to Pandas total_invest_data = pd.Panel(set_data) # set up total_invest data structure total_invest = total_invest_data[Investment_ticker[0]]["Close Investment"] for ticker in Investment_ticker[1:]: total_invest = total_invest_data[ticker][ "Close Investment"] + total_invest # Sum all the money invested Principal = [] for i in range(0, len(Book.index)): if "Purchase" in Book.iloc[i]["Transaction"]: if i == 0: Principal.append(float(Book.iloc[i]["Amount"].split("$")[1])) continue Principal.append( float(Book.iloc[i]["Amount"].split("$")[1]) + Principal[i - 1]) elif "Sale" in Book.iloc[i]["Transaction"]: if i == 0: Principal.append(float(Book.iloc[i]["Amount"].split("$")[1])) continue Principal.append(Principal[i - 1] - float(Book.iloc[i]["Amount"].split("$")[1])) #Principal.append(Principal[-1]) weekFormatter = DateFormatter("%b %d '%y") #%H:%M:%S fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) ax.xaxis.set_major_formatter(weekFormatter) plt.plot(total_invest, 'g', Book.index, Principal, '-k') #plt.plot(Book.index,Principal) #fig.subplots_adjust() ax.xaxis_date() ax.autoscale_view() plt.title("Total") plt.legend(labels=["Investment", "Principal"]) plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') plt.grid() #plt.show() # Create Month to month ROI and year to year #print (Book.index) #print (Principal) #print (total_invest ) month_principal = [] month_date = [] for i, d in enumerate(Book.index): try: if d.month > prev_date.month and d.year == prev_date.year or d.year != prev_date.year: # all shenanigans #print (i, d, d.month) #print (Principal[i]) if d.day == 1: k = i #print ("Month", d.month, Book.index[i] ,Principal[i]) else: k = i - 1 #print ("Prev month", d.month,Book.index[i-1], Principal[i-1]) if d.month > prev_date.month + 1: dummy = prev_date.month + 1 while dummy < d.month: #print (datetime.datetime(d.year,dummy,1), Principal[k]) month_date.append(datetime.datetime(d.year, dummy, 1)) month_principal.append(Principal[k]) #print ("miss month", dummy, Principal[k]) dummy = dummy + 1 #Principal[k] #print (datetime.datetime(d.year,d.month,1), Principal[k]) month_date.append(datetime.datetime(d.year, d.month, 1)) month_principal.append(Principal[k]) prev_date = d except UnboundLocalError: prev_date = d continue # if the month already pass it and not investment has being made then it updates to the current month if datetime.datetime.today().month > Book.index[-1].month: print(Book.index[-1], Principal[-1]) d_dummy = Book.index[-1] month_date.append(datetime.datetime(d_dummy.year, d_dummy.month + 1, 1)) month_principal.append(Principal[-1]) # Investment total_invest_month = [] j = 0 for index, d in enumerate(total_invest.index): if j >= len(month_date): break if month_date[j].month == d.month and month_date[j].year == d.year: #print (d, index, total_invest[index] ) j = j + 1 total_invest_month.append(total_invest[index]) percent_month = [] ROI = [] for i in range(0, len(month_date)): #print (total_invest_month[i], month_principal[i]) percent_month.append((total_invest_month[i] - month_principal[i]) / month_principal[i] * 100.0) ROI.append(total_invest_month[i] - month_principal[i]) #percent_month=100.0*(total_invest_month - month_principal)/month_principal weekFormatter = DateFormatter("%b %d '%y") #%H:%M:%S fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) ax.xaxis.set_major_formatter(weekFormatter) plt.plot(month_date, ROI) #fig.subplots_adjust() ax.xaxis_date() ax.autoscale_view() plt.title("Total") plt.legend(labels=["Investment", "Principal"]) plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') plt.grid() ax2 = ax.twinx() ax2.plot(month_date, percent_month, 'g*-') plt.show()
def getChart(): n = body.args['stock'] x = stock.stock(n) c = x.renderChart() return jsonify({'n': n, 'chart': c[0], 'perf': c[1]})
from sklearn.model_selection import train_test_split from stock import stock import matplotlib.pyplot as plt # learning model from sklearn.linear_model import LinearRegression from sklearn.neighbors import KNeighborsClassifier from sklearn.tree import DecisionTreeClassifier def non_shuffling_train_test_split(X, y, test_size=0.2): i = int((1 - test_size) * X.shape[0]) + 1 X_train, X_test = np.split(X, [i]) y_train, y_test = np.split(y, [i]) return X_train, X_test, y_train, y_test stock_TPE = stock('price_data.csv') all_days = len(stock_TPE.close) K0 = np.array(stock_TPE.feature_K()) K1 = np.roll(K0, 1) K2 = np.roll(K0, 2) K3 = np.roll(K0, 3) K4 = np.roll(K0, 4) K5 = np.roll(K0, 5) K6 = np.roll(K0, 6) K7 = np.roll(K0, 7) K8 = np.roll(K0, 8) K9 = np.roll(K0, 9) B5 = stock_TPE.feature_BIAS(5) B10 = stock_TPE.feature_BIAS(10) B15 = stock_TPE.feature_BIAS(15)
def fetchP(): n = body.args['stock'] x = stock.stock(n) nums = x.getPrices() return jsonify({'n': n, 'p': nums[0], 'diff': nums[1]})
import datetime import stock import matplotlib.pyplot as plot tickers = "AAPL","SBUX","GRPN","EC","T","IBM","INTC","NFLX","GOOG","OSTK","CMG","TWX" how_long = 90 time_between = "d" ending = datetime.date.today() time_span = datetime.timedelta(days=how_long) starting = ending - time_span s = ([]) j = 0 for ticker in tickers: s.append(stock.stock(ticker,starting,ending,time_between)) print ticker + "\nNormalized Standard Deviation:\n" + repr(100*s[j].std_dev/s[j].price_avg) + \ "\nMaximum Return:\n" + repr(max(s[j].returns)*100) + \ "\nLinear Deviation:\n" + repr(s[j].r_squared) + \ "\nInitial Investment:\n" + repr(s[j].price_init) + "\n" j += 1 plot.show() #stdev = list(stdev) #which = stdev.index(max(stdev)) #print s[which].ticker #print stdev[which] #print s[which].r_squared #print s[1:2].r_squared
ax2.plot(delta, 'blue') ax3 = fig.add_subplot(223) plt.ylabel('theta') ax3.plot(theta, 'blue') else: ax2 = fig.add_subplot(222) plt.ylabel('vega') ax2.plot(vega, 'blue') ax3 = fig.add_subplot(223) plt.ylabel('volatility') ax3.plot(volatility, 'blue') ax4 = fig.add_subplot(224) plt.ylabel('Price of underlying') ax4.plot(underlying, 'red') if __name__ == '__main__': #pd.set_option("display.max_rows", None, "display.max_columns", None) s1 = stock(100, .005, .05) s1.gbm(100) c1 = bsm(call=True, x=100, r=.05, t=45, stock=s1, time_stock=40) c1.fill() c2 = bsm(call=True, x=100, r=.05, t=30, stock=s1, time_stock=40) c2.fill() plt.xlabel('stock days') plt.ylabel('vega') plt.plot(c1.history['vega'], 'orange', label='t=45') plt.plot(c2.history['vega'], 'grey', label='t=30') plt.legend(loc="upper right") plt.show()
def caculate_model(sid, nday): print("") s = stock("測試資料/台股/{0}d.csv".format(sid)) # if s.complate_data(sid) : # 如果有新的資料,再重新laod 一次 # s = stock("測試資料/台股/{0}d.csv".format(sid)) #s.reduce_data_len(250*10) # 用五年內的資料 pulldown_date, pulldown = s.feature_pulldown(20*6) # 半年 print("半年高檔拉回標準:", round(tools.list_percentage(pulldown,0.4),3), "目前:", round(pulldown[-1],3)) tmp1= round(tools.list_percentage(pulldown,0.4),3) tmp2= round(pulldown[-1],3) BIAS = s.feature_BIAS(nday) BIAS_low = list(filter(lambda x: x < 0, BIAS[nday:])) print("主軸拉回標準:", round(tools.list_percentage(BIAS_low,0.4)*100,3), "目前:", round(BIAS[-1]*100,3)) tmp3 = round(tools.list_percentage(BIAS_low,0.4)*100,3) tmp4 = round(BIAS[-1]*100,3) #1日 K list_K = s.feature_K() currnt_K = list_K[-1] print("1日K 高低檔數值:", round(tools.list_percentage(list_K,0.2),2), round(tools.list_percentage(list_K,0.8),2), "目前 K:", round(currnt_K, 2)) tmp5 = round(tools.list_percentage(list_K,0.2),2) tmp6 = round(tools.list_percentage(list_K,0.8),2) tmp7 = round(currnt_K, 2) MA_slope = s.feature_MA(nday) print("目前均線:", MA_slope[-1], " 均線漲跌:", round(MA_slope[-1] - MA_slope[-2],4)) tmp11 = round(MA_slope[-1] - MA_slope[-2],4) tmp12 = (mdates.num2date(s.date[-1]).strftime("%Y/%m/%d")) #中長 紅黑K統計 diff = s.feature_diff()[1:]*100 diff_up_list = list(filter(lambda x: x > 0, diff)) diff_down_list = list(filter(lambda x: x < 0, diff)) diff_current = diff[-1] diff_up_std1 = tools.list_percentage(diff_up_list,0.55) diff_up_std2 = tools.list_percentage(diff_up_list,0.75) diff_down_std1 = tools.list_percentage(diff_down_list,1-0.55) diff_down_std2 = tools.list_percentage(diff_down_list,1-0.75) print("中紅標準:", round(diff_up_std1,2), "\t目前:", round(diff_current,2)) print("中黑標準:", round(diff_down_std1,2), "\t目前:", round(diff_current,2)) print("長紅標準:", round(diff_up_std2,2), "\t目前:", round(diff_current,2)) print("長黑標準:", round(diff_down_std2,2), "\t目前:", round(diff_current,2)) #5日 K s5 = stock_5day("測試資料/台股/{0}d.csv".format(sid)) list_K = s5.feature_K() currnt_K = list_K[-1] print("5日K 高低檔數值:", round(tools.list_percentage(list_K,0.2),2), round(tools.list_percentage(list_K,0.8),2), "目前 K:", round(currnt_K, 2)) print(tmp12,",",s.close[-1],",",s.close[-2],",",s.close[-3],",",s.close[-4]) tmp8 = round(tools.list_percentage(list_K,0.2),2) tmp9 = round(tools.list_percentage(list_K,0.8),2) tmp10 = round(currnt_K, 2) print("") if tmp2<tmp1: print("** 高檔拉回") if tmp4<tmp3: print("** 主軸拉回") if tmp7<tmp5: print("** 1日k 低檔") if tmp10<tmp8: print("** 5日k 低檔") if diff_current > diff_up_std2: print("** 長紅") elif diff_current > diff_up_std1: print("** 中紅") if diff_current < diff_down_std2: print("** 長黑") elif diff_current < diff_down_std1: print("** 中黑") print("") print(tmp12,tmp1,tmp2,tmp3,tmp4,tmp5,tmp6,tmp7,tmp8,tmp9,tmp10, tmp11)
# -*- coding: utf-8 -*- import numpy as np import sys import tools from stock import stock from stock import stock_5day from datetime import datetime import matplotlib.pyplot as plt import matplotlib.dates as mdates if __name__ == '__main__': s = stock("測試資料/台股/{0}.csv".format(sys.argv[1])) nday = int(sys.argv[2]) #設定主軸 period = 12 date, data = s.feature_Annualized(1, period) date2, data2 = s.feature_Annualized(2, period) date3, data3 = s.feature_Annualized(3, period) date4, data4 = s.feature_Annualized(4, period) date5, data5 = s.feature_Annualized(5, period) date6, data6 = s.feature_Annualized(6, period) date7, data7 = s.feature_Annualized(7, period) date8, data8 = s.feature_Annualized(8, period) date9, data9 = s.feature_Annualized(9, period) date10, data10 = s.feature_Annualized(10, period) #print("{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10} {11} {12} {13} {14}".format( # round(np.average(data),2),round(np.std(data),2),round(np.min(data),2), # round(np.average(data3),2),round(np.std(data3),2),round(np.min(data3),2), # round(np.average(data4),2),round(np.std(data4),2),round(np.min(data4),2),
def creatingStocks(symbol): print("Creating Stocks") for x in symbolStock: stocks.append(stk.stock(x, Ticker(x)))
def add(self, i): a = stock(i) self.stock.append(a)