PyAlgoTrade - An excellent open source python library

vagar11

Well-Known Member
#42
In layman's terms, we download the EOD data of a script, run your predetermined test and show end result the portfolio all in one go with the below one line code

Code:
python program.py script_name


Is it not cool.

Hi I have download the csv file from yahoo for SBIN.

I tried running the script that you gave above it didn't return me anything like graph or output.

Is the script complete as I cannot see a matplot lib and no parsing of arguments.
 

pannet1

Well-Known Member
#43
Hi I have download the csv file from yahoo for SBIN.

I tried running the script that you gave above it didn't return me anything like graph or output.

Is the script complete as I cannot see a matplot lib and no parsing of arguments.
its dead simple. can you believe PyAlgoTrade program was may be my 3rd or 4th python copy paste program. no matplot lib is required. I am sure because i could not install matplot package in my elementary linux system.

this one line code download the necessary oracle 2000 year daily timeframe file

Code:
python -c "from pyalgotrade.tools import yahoofinance; yahoofinance.download_daily_bars('orcl', 2000, 'orcl-2000.csv')"
thats it we have the EOD data in CSV format.

PyAlgoTrade makes it very easy to plot a strategy execution. Save this as sma_crossover.py:
Code:
from pyalgotrade import strategy
from pyalgotrade.technical import ma
from pyalgotrade.technical import cross


class SMACrossOver(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument, smaPeriod):
        super(SMACrossOver, self).__init__(feed)
        self.__instrument = instrument
        self.__position = None
        # We'll use adjusted close values instead of regular close values.
        self.setUseAdjustedValues(True)
        self.__prices = feed[instrument].getPriceDataSeries()
        self.__sma = ma.SMA(self.__prices, smaPeriod)

    def getSMA(self):
        return self.__sma

    def onEnterCanceled(self, position):
        self.__position = None

    def onExitOk(self, position):
        self.__position = None

    def onExitCanceled(self, position):
        # If the exit was canceled, re-submit it.
        self.__position.exitMarket()

    def onBars(self, bars):
        # If a position was not opened, check if we should enter a long position.
        if self.__position is None:
            if cross.cross_above(self.__prices, self.__sma) > 0:
                shares = int(self.getBroker().getCash() * 0.9 / bars[self.__instrument].getPrice())
                # Enter a buy market order. The order is good till canceled.
                self.__position = self.enterLong(self.__instrument, shares, True)
        # Check if we have to exit the position.
        elif not self.__position.exitActive() and cross.cross_below(self.__prices, self.__sma) > 0:
            self.__position.exitMarket()
now we have the strategy. now lets plot the strategy tester.

save the below code as plot_sma_crossover.py (not necessary to have the same file name).

Code:
from pyalgotrade import plotter
from pyalgotrade.barfeed import yahoofeed
from pyalgotrade.stratanalyzer import returns
import sma_crossover

# Load the yahoo feed from the CSV file
feed = yahoofeed.Feed()
feed.addBarsFromCSV("orcl", "orcl-2000.csv")

# Evaluate the strategy with the feed's bars.
myStrategy = sma_crossover.SMACrossOver(feed, "orcl", 20)

# Attach a returns analyzers to the strategy.
returnsAnalyzer = returns.Returns()
myStrategy.attachAnalyzer(returnsAnalyzer)

# Attach the plotter to the strategy.
plt = plotter.StrategyPlotter(myStrategy)
# Include the SMA in the instrument's subplot to get it displayed along with the closing prices.
plt.getInstrumentSubplot("orcl").addDataSeries("SMA", myStrategy.getSMA())
# Plot the simple returns on each bar.
plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returnsAnalyzer.getReturns())

# Run the strategy.
myStrategy.run()
myStrategy.info("Final portfolio value: $%.2f" % myStrategy.getResult())

# Plot the strategy.
plt.plot()
The code is doing 3 things:

Loading the feed from a CSV file.
Running the strategy with the bars supplied by the feed
Plotting the strategy.

substitue orcl with the script name as per yahoo's naming convention. For example ... to plot State Bank of India on NSE substitute orcl with SBIN.NS in the above code.

now run the file with python
Code:
python plot_sma_crossover.py

good luck.
 
Last edited:

vagar11

Well-Known Member
#44
its dead simple. can you believe PyAlgoTrade program was may be my 3rd or 4th python copy paste program. no matplot lib is required. I am sure because i could not install matplot package in my elementary linux system.

this one line code download the necessary oracle 2000 year daily timeframe file

Code:
python -c "from pyalgotrade.tools import yahoofinance; yahoofinance.download_daily_bars('orcl', 2000, 'orcl-2000.csv')"
thats it we have the EOD data in CSV format.

PyAlgoTrade makes it very easy to plot a strategy execution. Save this as sma_crossover.py:
Code:
from pyalgotrade import strategy
from pyalgotrade.technical import ma
from pyalgotrade.technical import cross


class SMACrossOver(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument, smaPeriod):
        super(SMACrossOver, self).__init__(feed)
        self.__instrument = instrument
        self.__position = None
        # We'll use adjusted close values instead of regular close values.
        self.setUseAdjustedValues(True)
        self.__prices = feed[instrument].getPriceDataSeries()
        self.__sma = ma.SMA(self.__prices, smaPeriod)

    def getSMA(self):
        return self.__sma

    def onEnterCanceled(self, position):
        self.__position = None

    def onExitOk(self, position):
        self.__position = None

    def onExitCanceled(self, position):
        # If the exit was canceled, re-submit it.
        self.__position.exitMarket()

    def onBars(self, bars):
        # If a position was not opened, check if we should enter a long position.
        if self.__position is None:
            if cross.cross_above(self.__prices, self.__sma) > 0:
                shares = int(self.getBroker().getCash() * 0.9 / bars[self.__instrument].getPrice())
                # Enter a buy market order. The order is good till canceled.
                self.__position = self.enterLong(self.__instrument, shares, True)
        # Check if we have to exit the position.
        elif not self.__position.exitActive() and cross.cross_below(self.__prices, self.__sma) > 0:
            self.__position.exitMarket()
now we have the strategy. now lets plot the strategy tester.

save the below code as plot_sma_crossover.py (not necessary to have the same file name).

Code:
from pyalgotrade import plotter
from pyalgotrade.barfeed import yahoofeed
from pyalgotrade.stratanalyzer import returns
import sma_crossover

# Load the yahoo feed from the CSV file
feed = yahoofeed.Feed()
feed.addBarsFromCSV("orcl", "orcl-2000.csv")

# Evaluate the strategy with the feed's bars.
myStrategy = sma_crossover.SMACrossOver(feed, "orcl", 20)

# Attach a returns analyzers to the strategy.
returnsAnalyzer = returns.Returns()
myStrategy.attachAnalyzer(returnsAnalyzer)

# Attach the plotter to the strategy.
plt = plotter.StrategyPlotter(myStrategy)
# Include the SMA in the instrument's subplot to get it displayed along with the closing prices.
plt.getInstrumentSubplot("orcl").addDataSeries("SMA", myStrategy.getSMA())
# Plot the simple returns on each bar.
plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returnsAnalyzer.getReturns())

# Run the strategy.
myStrategy.run()
myStrategy.info("Final portfolio value: $%.2f" % myStrategy.getResult())

# Plot the strategy.
plt.plot()
The code is doing 3 things:

Loading the feed from a CSV file.
Running the strategy with the bars supplied by the feed
Plotting the strategy.

substitue orcl with the script name as per yahoo's naming convention. For example ... to plot State Bank of India on NSE substitute orcl with SBIN.NS in the above code.

now run the file with python
Code:
python plot_sma_crossover.py

good luck.

Thanks. It is working now.

Made some change in the plotting python script to accept the stock name as argument. Keeping the strategy file as it is.

from pyalgotrade.tools import yahoofinance
from pyalgotrade import plotter
from pyalgotrade.barfeed import yahoofeed
from pyalgotrade.stratanalyzer import returns
import sma_crossover
import sys

#Download the file
yahoofinance.download_daily_bars(sys.argv[1], 2000, 'orcl-2000.csv')


# Load the yahoo feed from the CSV file
feed = yahoofeed.Feed()
feed.addBarsFromCSV("orcl", "orcl-2000.csv")

# Evaluate the strategy with the feed's bars.
myStrategy = sma_crossover.SMACrossOver(feed, "orcl", 20)

# Attach a returns analyzers to the strategy.
returnsAnalyzer = returns.Returns()
myStrategy.attachAnalyzer(returnsAnalyzer)

# Attach the plotter to the strategy.
plt = plotter.StrategyPlotter(myStrategy)
# Include the SMA in the instrument's subplot to get it displayed along with the closing prices.
plt.getInstrumentSubplot("orcl").addDataSeries("SMA", myStrategy.getSMA())
# Plot the simple returns on each bar.
plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returnsAnalyzer.getReturns())

# Run the strategy.
myStrategy.run()
myStrategy.info("Final portfolio value: $%.2f" % myStrategy.getResult())

# Plot the strategy.
plt.plot()
Example :
python plot_sma_crossover.py SBIN.NS
 

pannet1

Well-Known Member
#46
Made some change in the plotting python script to accept the stock name as argument. Keeping the strategy file as it is.
Wow. exactly the same change i did first. The next improvement would be to run the script in a loop so it scans all the instruments to find an entry for me.

Good work. Vagar.
 

Similar threads