Esempio n. 1
0
def main(tick, year, cash, smaPeriod, order):
    print 'Welcome, ' + os.environ['USER'] + '!'
    print 'Backtesting ' + tick + ' in ' + str(year)

    # Download daily bars
    filename = tick + '-' + str(year) + '.csv'
    yahoofinance.download_daily_bars(tick, year, filename)

    # Load CSV file
    feed = yahoofeed.Feed()
    feed.addBarsFromCSV(tick, filename)

    # Evaluate Strategy
    strategySMA = StrategySMA(feed, tick, smaPeriod, order, cash)

    # Attach a returns analyzers to the strategy.
    retAnalyzer = returns.Returns()
    strategySMA.attachAnalyzer(retAnalyzer)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strategySMA.attachAnalyzer(sharpeRatioAnalyzer)

    # Attach the plotter to the strategy.
    plt = plotter.StrategyPlotter(strategySMA)
    # Include the SMA in the instrument's subplot to get it displayed along with the closing prices.
    plt.getInstrumentSubplot(tick).addDataSeries("SMA", strategySMA.getSMA())

    # Set portfolio cash
    strategySMA.getBroker().setCash(cash)
    initial = strategySMA.getBroker().getEquity()

    # Run the strategy
    strategySMA.run()

    # Print the results
    print '*' * 60
    print 'Initial portfolio value: $%.2f' % initial

    final = strategySMA.getBroker().getEquity()
    print 'Final portfolio value: $%.2f' % final

    net = final - initial
    if net > 0:
        print 'Net gain: $%.2f' % net
    else:
        print 'Net loss: $%.2f' % net

    percentage = (final - initial) / initial * 100
    if percentage > 0:
        print 'Percentage gain: +%.2f%%' % percentage
    else:
        print 'Percentage loss: %.2f%%' % percentage

    #print 'Final portfolio value: $%.2f' % strategySMA.getResult()
    print 'Annual return: %.2f%%' % (retAnalyzer.getCumulativeReturns()[-1] * 100)
    print 'Average daily return: %.2f%%' % (stats.mean(retAnalyzer.getReturns()) * 100)
    print 'Std. dev. daily return: %.4f' % (stats.stddev(retAnalyzer.getReturns()))
    print 'Sharpe ratio: %.2f' % (sharpeRatioAnalyzer.getSharpeRatio(0))

    # Plot the strategy
    plt.plot()
Esempio n. 2
0
	def testDownloadAndParse(self):
		instrument = "orcl"
		path = "orcl-2010.csv"
		yahoofinance.download_daily_bars(instrument, 2010, path)
		bf = yahoofeed.Feed()
		bf.addBarsFromCSV(instrument, path)
		bf.loadAll()
		self.assertEqual(bf[instrument][-1].getOpen(), 31.22)
		self.assertEqual(bf[instrument][-1].getClose(), 31.30)
Esempio n. 3
0
def run_strategy():
    # Load the yahoo feed from the CSV file
    yahoofinance.download_daily_bars('600865.SS', 2015, '600865.SS-2015.csv')
    feed = yahoofeed.Feed()
    feed.addBarsFromCSV("600865.SS", "600865.SS-2015.csv")

    # Evaluate the strategy with the feed.
    myStrategy = MyStrategy(feed, "600865.SS", 10, 5, 1)
    myStrategy.run()
    print "Final portfolio value: $%.2f" % myStrategy.getBroker().getEquity()
Esempio n. 4
0
    def testDownloadAndParseDaily(self):
        instrument = "orcl"

        with common.TmpDir() as tmp_path:
            path = os.path.join(tmp_path, "orcl-2010.csv")
            yahoofinance.download_daily_bars(instrument, 2010, path)
            bf = yahoofeed.Feed()
            bf.addBarsFromCSV(instrument, path)
            bf.loadAll()
            self.assertEqual(round(bf[instrument][-1].getOpen(), 2), 31.22)
            self.assertEqual(round(bf[instrument][-1].getClose(), 2), 31.30)
Esempio n. 5
0
def build_feed(instruments, fromYear, toYear):
    feed = yahoofeed.Feed()

    for year in range(fromYear, toYear+1):
        for symbol in instruments:
            fileName = "%s-%d-yahoofinance.csv" % (symbol, year)
            if not os.path.exists(fileName):
                print "Downloading %s %d" % (symbol, year)
                yahoofinance.download_daily_bars(symbol, year, fileName)
            feed.addBarsFromCSV(symbol, fileName)
    return feed
Esempio n. 6
0
    def testDownloadAndParseDaily(self):
        instrument = "orcl"

        common.init_temp_path()
        path = os.path.join(common.get_temp_path(), "orcl-2010.csv")
        yahoofinance.download_daily_bars(instrument, 2010, path)
        bf = yahoofeed.Feed()
        bf.addBarsFromCSV(instrument, path)
        bf.loadAll()
        self.assertEqual(bf[instrument][-1].getOpen(), 31.22)
        self.assertEqual(bf[instrument][-1].getClose(), 31.30)
Esempio n. 7
0
def build_feed(instruments, fromYear, toYear):
    feed = yahoofeed.Feed()

    for year in range(fromYear, toYear + 1):
        for symbol in instruments:
            fileName = "%s-%d-yahoofinance.csv" % (symbol, year)
            if not os.path.exists(fileName):
                print "Downloading %s %d" % (symbol, year)
                yahoofinance.download_daily_bars(symbol, year, fileName)
            feed.addBarsFromCSV(symbol, fileName)
    return feed
Esempio n. 8
0
    def testDownloadAndParseDaily(self):
        instrument = "orcl"

        common.init_temp_path()
        path = os.path.join(common.get_temp_path(), "orcl-2010.csv")
        yahoofinance.download_daily_bars(instrument, 2010, path)
        bf = yahoofeed.Feed()
        bf.addBarsFromCSV(instrument, path)
        bf.loadAll()
        self.assertEqual(bf[instrument][-1].getOpen(), 31.22)
        self.assertEqual(bf[instrument][-1].getClose(), 31.30)
Esempio n. 9
0
def run_strategy():
    # Load the yahoo feed from the CSV file
    from pyalgotrade.tools import yahoofinance
    import csv
    instruments = {
        #'orcl'
        #,'aapl'
        '^HSI': {"name":"MHSI", "dollar_per_point":10},
        #'fxcm',
    }
    YEARS = [2010,2015]
    CAPITAL = 20000000
    feed = yahoofeed.Feed()
    for i in instruments:
        for y in range(YEARS[0], YEARS[1]+1):
            # print i, y
            csv_name = '%s-%s.csv' % (i,y)
            csv_name_new = "new_" + csv_name
            yahoofinance.download_daily_bars(i, y, csv_name)
            with open(csv_name, "rb") as fr:
                reader = csv.DictReader(fr)
                with open(csv_name_new, "wb")as fw:
                    w = csv.DictWriter(fw, reader.fieldnames)
                    w.writeheader()
                    for row in reader:
                        factor = float(row["Adj Close"]) / float(row["Close"])
                        row["Open"] = float(row["Open"]) * factor
                        row["High"] = float(row["High"]) * factor
                        row["Low"] = float(row["Low"]) * factor
                        row["Close"] = float(row["Close"]) * factor
                        row["Volume"] = float(row["Volume"]) * factor
                        w.writerow(row)
            feed.addBarsFromCSV(i, csv_name_new)

    # Evaluate the strategy with the feed.
    myStrategy = TurtleTrading(feed, instruments, CAPITAL)
    myStrategy.run()
    final = myStrategy.getBroker().getEquity()
    profit = final - CAPITAL
    print "Final portfolio value: $%.2f" % final
    print "Profit = %.2f, %.2f " % (profit, 100 * profit / CAPITAL)
    f = open("record.csv", "wb")
    rows = myStrategy.record.values()
    sorted(rows, key = lambda x: x["date"])
    for r in rows:
        print r["date"]
    w = csv.DictWriter(f, rows[0].keys())
    w.writeheader()
    w.writerows(rows)
Esempio n. 10
0
def run_strategy(smaPeriod):
    # download a CSV file from yahoo finance
    yahoofinance.download_daily_bars(ticker, year, csv_file)
    # Load the yahoo feed from the CSV file
    feed = yahoofeed.Feed()
    feed.addBarsFromCSV(ticker, csv_file)

    # Evaluate the strategy with the feed.
    myStrategy = MyStrategy(feed, ticker, smaPeriod)
    myStrategy.run()
    equity = myStrategy.getBroker().getEquity()

    print '\nStarting portfolio value: $%.2f' % start_capital
    print 'Final portfolio value: $%.2f' % equity
    print 'Difference: %.2f' % (equity - start_capital)
Esempio n. 11
0
def run_strategy(smaPeriod):
	# download a CSV file from yahoo finance
	yahoofinance.download_daily_bars(ticker, year, csv_file)	
	# Load the yahoo feed from the CSV file
	feed = yahoofeed.Feed()
	feed.addBarsFromCSV(ticker, csv_file)

	# Evaluate the strategy with the feed.
	myStrategy = MyStrategy(feed, ticker, smaPeriod)
	myStrategy.run()
	equity = myStrategy.getBroker().getEquity()
	
	print '\nStarting portfolio value: $%.2f' % start_capital
	print 'Final portfolio value: $%.2f' % equity
	print 'Difference: %.2f' % (equity - start_capital)
Esempio n. 12
0
def RealTime(filepath,instrument):
	
	# Download CSV from yahoo if the CSV does not already exist.
	if not isfile(filepath):
		download_daily_bars(instrument,2016,filepath)
	
	# Get Live Results from Yahoo Database and append to CSV
	s = Share(instrument)
	date = datetime.today().strftime('%Y-%m-%d')
	O,H,L,C,V,AC = (s.get_open(), s.get_days_high(), s.get_days_low(), s.get_price(), 
					s.get_volume(),s.get_price())

	#Date,Open,High,Low,Close,Volume,Adj Close
	field = [date,O,H,L,C,V,AC]
	
	with open(filepath,'a') as csvfile:
		old = csv.writer(csvfile)
		add = old.writerow(field)
Esempio n. 13
0
def download_files_for_symbol(symbol, fromYear, toYear):
	if not os.path.exists(storage):
		logger.info("Creating %s directory" % (storage))
		os.mkdir(storage)

	status = ""
	for year in range(fromYear, toYear+1):
		fileName = get_csv_filename(symbol, year)
		if not os.path.exists(fileName):
			logger.info("Downloading %s %d to %s" % (symbol, year, fileName))
			try: 
				yahoofinance.download_daily_bars(symbol, year, fileName)
				status += "1"
			except Exception, e:
				logger.error(str(e))
				status += "0"
		else:
			status += "1"
Esempio n. 14
0
def download_files_for_symbol(symbol, fromYear, toYear):
    if not os.path.exists(storage):
        logger.info("Creating %s directory" % (storage))
        os.mkdir(storage)

    status = ""
    for year in range(fromYear, toYear + 1):
        fileName = get_csv_filename(symbol, year)
        if not os.path.exists(fileName):
            logger.info("Downloading %s %d to %s" % (symbol, year, fileName))
            try:
                yahoofinance.download_daily_bars(symbol, year, fileName)
                status += "1"
            except Exception, e:
                logger.error(str(e))
                status += "0"
        else:
            status += "1"
Esempio n. 15
0
def download_files_for_symbol(symbol, fromYear, toYear):
    if not os.path.exists(storage):
        logger.info("Creating %s directory" % (storage))
        os.mkdir(storage)

    status = ""
    for year in range(fromYear, toYear+1):
        fileName = get_csv_filename(symbol, year)
        if not os.path.exists(fileName):
            logger.info("Downloading %s %d to %s" % (symbol, year, fileName))
            try:
                yahoofinance.download_daily_bars(symbol, year, fileName)
                status += "1"
            except Exception as e:
                logger.error(str(e))
                status += "0"
        else:
            status += "1"

    if status.find("1") == -1:
        logger.fatal("No data found for %s" % (symbol))
    elif status.lstrip("0").find("0") != -1:
        logger.fatal("Some bars are missing for %s" % (symbol))
Esempio n. 16
0
# Copyright 2015-2017 Isaac de la Pena
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
.. moduleauthor:: Isaac de la Pena <*****@*****.**>
"""

from pyalgotrade.tools import yahoofinance
import os
import IbexAssets as assets

if not os.path.isdir(assets.folder):
    os.mkdir(assets.folder)

for instrument, start in assets.all.items():
    for year in range(start, assets.endYear):
        store = assets.folder + instrument + "-" + str(year) + ".csv"
        print store
        yahoofinance.download_daily_bars(instrument, year, store)
Esempio n. 17
0
            "glng": 11095,
            "simo": 17293,
        }
        for instrument, quantity in orders.items():
            self.marketOrder(instrument,
                             quantity,
                             onClose=True,
                             allOrNone=True)

    def onBars(self, bars):
        pass


# Load the yahoo feed from CSV files.
feed = yahoofeed.Feed()
yahoofinance.download_daily_bars("aeti", 2011,
                                 "D:\\aeti-2011-yahoofinance.csv")
yahoofinance.download_daily_bars("egan", 2011,
                                 "D:\\egan-2011-yahoofinance.csv")
yahoofinance.download_daily_bars("glng", 2011,
                                 "D:\\glng-2011-yahoofinance.csv")
yahoofinance.download_daily_bars("simo", 2011,
                                 "D:\\simo-2011-yahoofinance.csv")
feed.addBarsFromCSV("aeti", "D:\\aeti-2011-yahoofinance.csv")
feed.addBarsFromCSV("egan", "D:\\egan-2011-yahoofinance.csv")
feed.addBarsFromCSV("glng", "D:\\glng-2011-yahoofinance.csv")
feed.addBarsFromCSV("simo", "D:\\simo-2011-yahoofinance.csv")

# Evaluate the strategy with the feed's bars.
myStrategy = MyStrategy(feed)

# Attach returns and sharpe ratio analyzers.
Esempio n. 18
0
        bar = bars[self.__instrument]
        # If a position was not opened, check if we should enter a long position.
        if self.__position is None:
            if bar.getPrice() > self.__sma[-1]:
                # Enter a buy market order for 10 shares. The order is good till canceled.
                self.__position = self.enterLong(self.__instrument, 10, True)
        # Check if we have to exit the position.
        elif bar.getPrice(
        ) < self.__sma[-1] and not self.__position.exitActive():
            self.__position.exitMarket()


def run_strategy(smaPeriod, ticker, filename):
    # Load the yahoo feed from the CSV file
    feed = yahoofeed.Feed()
    feed.addBarsFromCSV(ticker, filename)

    # Evaluate the strategy with the feed.
    myStrategy = MyStrategy(feed, ticker, smaPeriod)
    myStrategy.run()
    print "Final portfolio value: $%.2f" % myStrategy.getBroker().getEquity()


print 'Argument List:', str(sys.argv)
ticker = sys.argv[1]
smaval = sys.argv[2]
#Fetch the datafile for the given stock
yahoofinance.download_daily_bars(ticker, 2014, 'datafile.csv')
run_strategy(int(smaval), ticker, 'datafile.csv')
Esempio n. 19
0
        # Place the orders to get them processed on the first bar.
        orders = {
            "aeti": 297810,
            "egan": 81266,
            "glng": 11095,
            "simo": 17293,
        }
        for instrument, quantity in orders.items():
            self.marketOrder(instrument, quantity, onClose=True, allOrNone=True)

    def onBars(self, bars):
        pass

# Load the yahoo feed from CSV files.
feed = yahoofeed.Feed()
yahoofinance.download_daily_bars("aeti",2011, "D:\\aeti-2011-yahoofinance.csv")
yahoofinance.download_daily_bars("egan", 2011, "D:\\egan-2011-yahoofinance.csv")
yahoofinance.download_daily_bars("glng", 2011, "D:\\glng-2011-yahoofinance.csv")
yahoofinance.download_daily_bars("simo", 2011, "D:\\simo-2011-yahoofinance.csv")
feed.addBarsFromCSV("aeti", "D:\\aeti-2011-yahoofinance.csv")
feed.addBarsFromCSV("egan", "D:\\egan-2011-yahoofinance.csv")
feed.addBarsFromCSV("glng", "D:\\glng-2011-yahoofinance.csv")
feed.addBarsFromCSV("simo", "D:\\simo-2011-yahoofinance.csv")

# Evaluate the strategy with the feed's bars.
myStrategy = MyStrategy(feed)

# Attach returns and sharpe ratio analyzers.
retAnalyzer = returns.Returns()
myStrategy.attachAnalyzer(retAnalyzer)
sharpeRatioAnalyzer = sharpe.SharpeRatio()
from pyalgotrade.tools import yahoofinance

yahoofinance.download_daily_bars('AXP', 2008, 'data/AXP-2008.csv')
yahoofinance.download_daily_bars('BA', 2008, 'data/BA-2008.csv')
yahoofinance.download_daily_bars('CAT', 2008, 'data/CAT-2008.csv')
yahoofinance.download_daily_bars('CSCO', 2008, 'data/CSCO-2008.csv')
yahoofinance.download_daily_bars('CVX', 2008, 'data/CVX-2008.csv')
yahoofinance.download_daily_bars('DD', 2008, 'data/DD-2008.csv')
yahoofinance.download_daily_bars('DIS', 2008, 'data/DIS-2008.csv')
yahoofinance.download_daily_bars('GE', 2008, 'data/GE-2008.csv')
yahoofinance.download_daily_bars('GS', 2008, 'data/GS-2008.csv')
yahoofinance.download_daily_bars('HD', 2008, 'data/HD-2008.csv')
yahoofinance.download_daily_bars('IBM', 2008, 'data/IBM-2008.csv')
yahoofinance.download_daily_bars('INTC', 2008, 'data/INTC-2008.csv')
yahoofinance.download_daily_bars('JNJ', 2008, 'data/JNJ-2008.csv')
yahoofinance.download_daily_bars('JPM', 2008, 'data/JPM-2008.csv')
yahoofinance.download_daily_bars('KO', 2008, 'data/KO-2008.csv')
yahoofinance.download_daily_bars('MCD', 2008, 'data/MCD-2008.csv')
yahoofinance.download_daily_bars('MMM', 2008, 'data/MMM-2008.csv')
yahoofinance.download_daily_bars('MRK', 2008, 'data/MRK-2008.csv')
yahoofinance.download_daily_bars('MSFT', 2008, 'data/MSFT-2008.csv')
yahoofinance.download_daily_bars('NKE', 2008, 'data/NKE-2008.csv')
yahoofinance.download_daily_bars('PFE', 2008, 'data/PFE-2008.csv')
yahoofinance.download_daily_bars('PG', 2008, 'data/PG-2008.csv')
yahoofinance.download_daily_bars('T', 2008, 'data/T-2008.csv')
yahoofinance.download_daily_bars('TRV', 2008, 'data/TRV-2008.csv')
yahoofinance.download_daily_bars('UNH', 2008, 'data/UNH-2008.csv')
yahoofinance.download_daily_bars('UTX', 2008, 'data/UTX-2008.csv')
yahoofinance.download_daily_bars('V', 2008, 'data/V-2008.csv')
yahoofinance.download_daily_bars('VZ', 2008, 'data/VZ-2008.csv')
yahoofinance.download_daily_bars('WMT', 2008, 'data/WMT-2008.csv')
Esempio n. 21
0
        elif(self.sma[-1] < bar.getPrice() and self.position) :
            print "buy " + str(bar.getDateTime())
            self.position.exitMarket()
        #self.info("%s %s" % (bar.getClose(), self.__sma[-1]))

    def onEnterOk(self, position):
        execInfo = position.getEntryOrder().getExecutionInfo()
        self.info('BUY ' + str(self.order) + ' ' + tick + ' at $%.2f/share' % (execInfo.getPrice()))



    def onExitOk(self, position):
        execInfo = position.getExitOrder().getExecutionInfo()
        self.info('SELL ' + str(self.order) + ' ' + tick + ' at $%.2f/share' % (execInfo.getPrice()))
        self.position = None


# Load the yahoo feed from the CSV file
filename = 'orcl-2016.csv'
tick = 'infy.ns'
year = 2016

yahoofinance.download_daily_bars(tick, year, filename)
feed = yahoofeed.Feed()
feed.addBarsFromCSV(tick, filename)

# Evaluate the strategy with the feed's bars.
myStrategy = MyStrategy(feed, tick, 10)
myStrategy.run()

Esempio n. 22
0
import sys
from pyalgotrade.tools import yahoofinance;

yahoofinance.download_daily_bars('2342.hk',int(sys.argv[1]), 'comb-%s.csv' % sys.argv[1])
from pyalgotrade.tools import yahoofinance 
import sys
for i in range(2010,2017):
    yahoofinance.download_daily_bars(sys.argv[1], i, sys.argv[1] + '-' + str(i) + '.csv')
print 'Done..'
Esempio n. 24
0
from pyalgotrade.tools import yahoofinance
yahoofinance.download_daily_bars('aeti', 2011, 'aeti-2011-yahoofinance.csv')
yahoofinance.download_daily_bars('egan', 2011, 'egan-2011-yahoofinance.csv')
yahoofinance.download_daily_bars('glng', 2011, 'glng-2011-yahoofinance.csv')
yahoofinance.download_daily_bars('simo', 2011, 'simo-2011-yahoofinance.csv')
Esempio n. 25
0
    from pyalgotrade import strategy
    from pyalgotrade.barfeed import yahoofeed
    from pyalgotrade.technical import ma
    from pyalgotrade.tools import yahoofinance
    yahoofinance.download_daily_bars('orcl', 2000, 'orcl-2000.csv')
    main_out = []
    class MyStrategy(strategy.BacktestingStrategy):
        def __init__(self, feed, instrument, smaPeriod):
            strategy.BacktestingStrategy.__init__(self, feed, 1000)
            self.__position = None
            self.__instrument = instrument
            # We'll use adjusted close values instead of regular close values.
            self.getBroker().setUseAdjustedValues(True)
            self.__sma = ma.SMA(feed[instrument].getAdjCloseDataSeries(), smaPeriod)
            main_out = []
        def onStart(self):
            main_out.append("Initial portfolio value: $%.2f" % self.getBroker().getEquity())
    
        def onEnterOk(self, position):
            execInfo = position.getEntryOrder().getExecutionInfo()
            main_out.append("%s: BUY at $%.2f" % (execInfo.getDateTime(), execInfo.getPrice()))
    
        def onEnterCanceled(self, position):
            self.__position = None
    
        def onExitOk(self, position):
            execInfo = position.getExitOrder().getExecutionInfo()
            main_out.append("%s: SELL at $%.2f" % (execInfo.getDateTime(), execInfo.getPrice()))
            self.__position = None
    
Esempio n. 26
0
import os
import os.path

from pyalgotrade.tools import yahoofinance

dir = 'data'
if not os.path.isdir(dir): os.makedirs(dir)

years = [2016]
for year in years:
    with open("atleast20.txt", "r") as ins:
        for line in ins:
            s = line.strip()
            file_name = "%s/%s - %s.csv" % (dir, s, year)
            try:
                if not os.path.isfile(file_name):
                    yahoofinance.download_daily_bars(s, year, file_name)
            except:
                print "ERROR => %s" % s
Esempio n. 27
0
def build_feed(instruments,
               fromYear,
               toYear,
               storage,
               frequency=bar.Frequency.DAY,
               timezone=None,
               skipErrors=False,
               authToken=None,
               columnNames={},
               forceDownload=False,
               skipMalformedBars=False):
    """Build and load a :class:`pyalgotrade.barfeed.coinmarketcapfeed.Feed` using CSV files downloaded from Quandl.
    CSV files are downloaded if they haven't been downloaded before.

    :param sourceCode: The dataset source code.
    :type sourceCode: string.
    :param tableCodes: The dataset table codes.
    :type tableCodes: list.
    :param fromYear: The first year.
    :type fromYear: int.
    :param toYear: The last year.
    :type toYear: int.
    :param storage: The path were the files will be loaded from, or downloaded to.
    :type storage: string.
    :param frequency: The frequency of the bars. Only **pyalgotrade.bar.Frequency.DAY** or **pyalgotrade.bar.Frequency.WEEK**
        are supported.
    :param timezone: The default timezone to use to localize bars. Check :mod:`pyalgotrade.marketsession`.
    :type timezone: A pytz timezone.
    :param skipErrors: True to keep on loading/downloading files in case of errors.
    :type skipErrors: boolean.
    :param authToken: Optional. An authentication token needed if you're doing more than 50 calls per day.
    :type authToken: string.
    :param columnNames: Optional. A dictionary to map column names. Valid key values are:

        * datetime
        * open
        * high
        * low
        * close
        * volume
        * adj_close

    :type columnNames: dict.
    :param skipMalformedBars: True to skip errors while parsing bars.
    :type skipMalformedBars: boolean.

    :rtype: :class:`pyalgotrade.barfeed.coinmarketcapfeed.Feed`.
    """

    logger = pyalgotrade.logger.getLogger("data")
    ret = Feed(frequency, timezone)

    # Additional column names.
    for col, name in six.iteritems(columnNames):
        ret.setColumnName(col, name)

    if not os.path.exists(storage):
        logger.info("Creating %s directory" % (storage))
        os.mkdir(storage)

    for year in range(fromYear, toYear + 1):
        for instrument in instruments:
            datasource = instrument.datasource()
            fileName = os.path.join(storage,
                                    f'{instrument}-{year}-{datasource}.csv')
            if not os.path.exists(fileName) or forceDownload:
                logger.info("Downloading %s %d to %s" %
                            (instrument, year, fileName))
                try:
                    assert frequency == bar.Frequency.DAY, "Invalid frequency"
                    if datasource == DATASOURCE_COINMARKETCAP:
                        coinmarketcap.download_daily_bars(
                            instrument, year, fileName, authToken)
                    else:
                        assert datasource == DATASOURCE_YAHOOFINANCE, "Invalid data source"
                        yahoofinance.download_daily_bars(
                            instrument, year, fileName, authToken)
                except Exception as e:
                    if skipErrors:
                        logger.error(str(e))
                        continue
                    else:
                        raise e
            ret.addBarsFromCSV(instrument,
                               fileName,
                               skipMalformedBars=skipMalformedBars)
    return ret
Esempio n. 28
0
from pyalgotrade import strategy
from pyalgotrade.barfeed import yahoofeed
from pyalgotrade.technical import ma
from pyalgotrade.tools import yahoofinance
yahoofinance.download_daily_bars('orcl', 2000, 'orcl-2000.csv')
main_out = []
class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument, smaPeriod):
        strategy.BacktestingStrategy.__init__(self, feed, 1000)
        self.__position = None
        self.__instrument = instrument
        # We'll use adjusted close values instead of regular close values.
        self.getBroker().setUseAdjustedValues(True)
        self.__sma = ma.SMA(feed[instrument].getAdjCloseDataSeries(), smaPeriod)
        main_out = []
    def onStart(self):
        main_out.append("Initial portfolio value: $%.2f" % self.getBroker().getEquity())
    def onEnterOk(self, position):
        execInfo = position.getEntryOrder().getExecutionInfo()
        main_out.append("%s: BUY at $%.2f" % (execInfo.getDateTime(), execInfo.getPrice()))
    def onEnterCanceled(self, position):
        self.__position = None
    def onExitOk(self, position):
        execInfo = position.getExitOrder().getExecutionInfo()
        main_out.append("%s: SELL at $%.2f" % (execInfo.getDateTime(), execInfo.getPrice()))
        self.__position = None
    def onExitCanceled(self, position):
        # If the exit was canceled, re-submit it.
        self.__position.exit()
    def onBars(self, bars):
Esempio n. 29
0
from pyalgotrade.tools import yahoofinance; 
yahoofinance.download_daily_bars('aeti', 2011, 'aeti-2011-yahoofinance.csv')
yahoofinance.download_daily_bars('egan', 2011, 'egan-2011-yahoofinance.csv')
yahoofinance.download_daily_bars('glng', 2011, 'glng-2011-yahoofinance.csv')
yahoofinance.download_daily_bars('simo', 2011, 'simo-2011-yahoofinance.csv')
Esempio n. 30
0
def main(tick, year, cash, smaPeriod, order):
    print 'Welcome, ' + os.environ['USER'] + '!'
    print 'Backtesting ' + tick + ' in ' + str(year)

    # Download daily bars
    filename = tick + '-' + str(year) + '.csv'
    yahoofinance.download_daily_bars(tick, year, filename)

    # Load CSV file
    feed = yahoofeed.Feed()
    feed.addBarsFromCSV(tick, filename)

    # Evaluate Strategy
    strategySMA = StrategySMA(feed, tick, smaPeriod, order, cash)

    # Attach a returns analyzers to the strategy.
    retAnalyzer = returns.Returns()
    strategySMA.attachAnalyzer(retAnalyzer)
    sharpeRatioAnalyzer = sharpe.SharpeRatio()
    strategySMA.attachAnalyzer(sharpeRatioAnalyzer)

    # Attach the plotter to the strategy.
    plt = plotter.StrategyPlotter(strategySMA)
    # Include the SMA in the instrument's subplot to get it displayed along with the closing prices.
    plt.getInstrumentSubplot(tick).addDataSeries("SMA", strategySMA.getSMA())

    # Set portfolio cash
    strategySMA.getBroker().setCash(cash)
    initial = strategySMA.getBroker().getEquity()

    # Run the strategy
    strategySMA.run()

    # Print the results
    print '*' * 60
    print 'Initial portfolio value: $%.2f' % initial

    final = strategySMA.getBroker().getEquity()
    print 'Final portfolio value: $%.2f' % final

    net = final - initial
    if net > 0:
        print 'Net gain: $%.2f' % net
    else:
        print 'Net loss: $%.2f' % net

    percentage = (final - initial) / initial * 100
    if percentage > 0:
        print 'Percentage gain: +%.2f%%' % percentage
    else:
        print 'Percentage loss: %.2f%%' % percentage

    #print 'Final portfolio value: $%.2f' % strategySMA.getResult()
    print 'Annual return: %.2f%%' % (retAnalyzer.getCumulativeReturns()[-1] *
                                     100)
    print 'Average daily return: %.2f%%' % (
        stats.mean(retAnalyzer.getReturns()) * 100)
    print 'Std. dev. daily return: %.4f' % (stats.stddev(
        retAnalyzer.getReturns()))
    print 'Sharpe ratio: %.2f' % (sharpeRatioAnalyzer.getSharpeRatio(0))

    # Plot the strategy
    plt.plot()
Esempio n. 31
0
from pyalgotrade.tools import yahoofinance

yahoofinance.download_daily_bars('orcl', 2000, 'orcl-2000.csv')
Esempio n. 32
0
        # Wait for enough bars to be available to calculate a SMA.
        if self.__sma[-1] is None:
            return

        bar = bars[self.__instrument]
        # If a position was not opened, check if we should enter a long position.
        if self.__position is None:
            if bar.getPrice() > self.__sma[-1]:
                # Enter a buy market order for 10 shares. The order is good till canceled.
                self.__position = self.enterLong(self.__instrument, 10, True)
        # Check if we have to exit the position.
        elif bar.getPrice() < self.__sma[-1] and not self.__position.exitActive():
            self.__position.exitMarket()

def run_strategy(smaPeriod,ticker,filename):
    # Load the yahoo feed from the CSV file
    feed = yahoofeed.Feed()
    feed.addBarsFromCSV(ticker, filename)

    # Evaluate the strategy with the feed.
    myStrategy = MyStrategy(feed,ticker,smaPeriod)
    myStrategy.run()
    print "Final portfolio value: $%.2f" % myStrategy.getBroker().getEquity()

print 'Argument List:', str(sys.argv)
ticker=sys.argv[1]
smaval=sys.argv[2]
#Fetch the datafile for the given stock
yahoofinance.download_daily_bars(ticker,2014, 'datafile.csv')
run_strategy(int(smaval),ticker,'datafile.csv')