### Initialize Event Profiler Example Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/eventprofiler.html Initial setup for an event profiler strategy based on Ernie Chan's 'Buy-on-Gap' model. ```python from __future__ import print_function from pyalgotrade import eventprofiler from pyalgotrade.technical import stats from pyalgotrade.technical import roc from pyalgotrade.technical import ma from pyalgotrade.tools import quandl # Event inspired on an example from Ernie Chan's book: ``` -------------------------------- ### Server Console Output Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/tutorial.html Example log output from the optimizer server. ```text 2017-07-21 22:56:51,944 pyalgotrade.optimizer.server [INFO] Starting server 2017-07-21 22:56:51,944 pyalgotrade.optimizer.xmlrpcserver [INFO] Loading bars 2017-07-21 22:56:52,609 pyalgotrade.optimizer.xmlrpcserver [INFO] Started serving 2017-07-21 22:58:50,073 pyalgotrade.optimizer.xmlrpcserver [INFO] Best result so far 1261295.07089 with parameters ('ibm', 150, 5, 2, 83, 24) . . ``` -------------------------------- ### Install PyAlgoTrade via pip Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/_sources/intro.txt Use this command to install the library and its dependencies into your Python environment. ```bash pip install pyalgotrade ``` -------------------------------- ### Local Optimizer Console Output Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/tutorial.html Example log output when running the local optimizer. ```text 2017-07-21 22:59:26,921 pyalgotrade.optimizer.local [INFO] Starting server 2017-07-21 22:59:26,922 pyalgotrade.optimizer.xmlrpcserver [INFO] Loading bars 2017-07-21 22:59:26,922 pyalgotrade.optimizer.local [INFO] Starting workers 2017-07-21 22:59:27,642 pyalgotrade.optimizer.xmlrpcserver [INFO] Started serving 2017-07-21 23:01:14,306 pyalgotrade.optimizer.xmlrpcserver [INFO] Best result so far 1261295.07089 with parameters ('ibm', 150, 5, 2, 83, 24) . . ``` -------------------------------- ### pyalgotrade.optimizer.server.serve Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/optimizer.html Starts a server to provide bars and strategy parameters to worker processes for backtesting. ```APIDOC ## Function pyalgotrade.optimizer.server.serve ### Description Executes a server that will provide bars and strategy parameters for workers to use. ### Method POST ### Endpoint /optimizer/server/serve ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **barFeed** (pyalgotrade.barfeed.BarFeed) - The bar feed that each worker will use to backtest the strategy. - **strategyParameters** - The set of parameters to use for backtesting. An iterable object where each element is a tuple that holds parameter values. - **address** (string) - The address to listen for incoming worker connections. - **port** (int) - The port to listen for incoming worker connections. - **batchSize** (int) - Optional, defaults to 200. The number of strategy executions that are delivered to each worker. ### Request Example ```json { "barFeed": "", "strategyParameters": [ [1, 2], [3, 4] ], "address": "127.0.0.1", "port": 9000, "batchSize": 200 } ``` ### Response #### Success Response (200) - **results** (Results) - A Results instance with the best results found or None if no results were obtained. #### Response Example ```json { "results": "" } ``` ``` -------------------------------- ### Quandl Integration Output Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/_sources/sample_quandl.txt Expected console output after running the Quandl integration example. ```text Final portfolio value: $1000000.00 ``` -------------------------------- ### Worker Console Output Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/tutorial.html Example log output from an optimizer worker. ```text 2017-07-21 22:56:57,884 localworker [INFO] Started running 2017-07-21 22:56:57,884 localworker [INFO] Started running 2017-07-21 22:56:58,439 localworker [INFO] Running strategy with parameters ('ibm', 150, 5, 2, 84, 15) 2017-07-21 22:56:58,498 localworker [INFO] Running strategy with parameters ('ibm', 150, 5, 2, 94, 5) 2017-07-21 22:56:58,918 localworker [INFO] Result 1137855.88871 2017-07-21 22:56:58,918 localworker [INFO] Running strategy with parameters ('ibm', 150, 5, 2, 84, 14) 2017-07-21 22:56:58,996 localworker [INFO] Result 1027761.85581 2017-07-21 22:56:58,997 localworker [INFO] Running strategy with parameters ('ibm', 150, 5, 2, 93, 25) 2017-07-21 22:56:59,427 localworker [INFO] Result 1092194.67448 2017-07-21 22:57:00,016 localworker [INFO] Result 1260766.64479 . . ``` -------------------------------- ### CSV Data Format Example Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/feed.html Example of the expected CSV file structure for the feed. ```text Date,USD,GBP,EUR 2013-09-29,1333.0,831.203,986.75 2013-09-22,1349.25,842.755,997.671 2013-09-15,1318.5,831.546,993.969 2013-09-08,1387.0,886.885,1052.911 . . . ``` -------------------------------- ### Basic PyAlgoTrade Strategy Example Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/tutorial.html A simple backtesting strategy that inherits from BacktestingStrategy and logs the closing price of a specified instrument on each bar. Requires importing strategy and quandlfeed modules. ```python from pyalgotrade import strategy from pyalgotrade.barfeed import quandlfeed class MyStrategy(strategy.BacktestingStrategy): def __init__(self, feed, instrument): super(MyStrategy, self).__init__(feed) self.__instrument = instrument def onBars(self, bars): bar = bars[self.__instrument] self.info(bar.getClose()) # Load the bar feed from the CSV file feed = quandlfeed.Feed() feed.addBarsFromCSV("orcl", "WIKI-ORCL-2000-quandl.csv") ``` -------------------------------- ### Load CSV Data Feed Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/_sources/feed.txt Example demonstrating how to load a CSV file with specific columns into a feed. ```python from pyalgotrade.feed import csvfeed feed = csvfeed.Feed("Date", None) feed.addValuesFromCSV("data.csv") for dateTime, values in feed: print(dateTime, values) ``` ```text 2013-09-29 {'USD': 1333.0, 'GBP': 831.203, 'EUR': 986.75} 2013-09-22 {'USD': 1349.25, 'GBP': 842.755, 'EUR': 997.671} 2013-09-15 {'USD': 1318.5, 'GBP': 831.546, 'EUR': 993.969} 2013-09-08 {'USD': 1387.0, 'GBP': 886.885, 'EUR': 1052.911} ``` -------------------------------- ### Strategy Execution Output Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/tutorial.html Example log output generated after running the SMA crossover strategy. ```text 2000-01-26 00:00:00 strategy [INFO] BUY at $25.84 2000-01-28 00:00:00 strategy [INFO] SELL at $23.45 2000-02-03 00:00:00 strategy [INFO] BUY at $25.22 2000-02-22 00:00:00 strategy [INFO] SELL at $26.92 2000-02-23 00:00:00 strategy [INFO] BUY at $27.41 2000-03-31 00:00:00 strategy [INFO] SELL at $36.51 2000-04-07 00:00:00 strategy [INFO] BUY at $38.11 2000-04-12 00:00:00 strategy [INFO] SELL at $35.49 2000-04-19 00:00:00 strategy [INFO] BUY at $35.80 2000-04-20 00:00:00 strategy [INFO] SELL at $33.61 2000-04-28 00:00:00 strategy [INFO] BUY at $35.74 2000-05-05 00:00:00 strategy [INFO] SELL at $33.70 2000-05-08 00:00:00 strategy [INFO] BUY at $34.29 2000-05-09 00:00:00 strategy [INFO] SELL at $33.55 2000-05-16 00:00:00 strategy [INFO] BUY at $35.35 2000-05-19 00:00:00 strategy [INFO] SELL at $32.78 2000-05-31 00:00:00 strategy [INFO] BUY at $33.35 2000-06-23 00:00:00 strategy [INFO] SELL at $36.80 2000-06-27 00:00:00 strategy [INFO] BUY at $37.51 2000-06-28 00:00:00 strategy [INFO] SELL at $37.37 2000-06-29 00:00:00 strategy [INFO] BUY at $37.37 2000-06-30 00:00:00 strategy [INFO] SELL at $36.60 2000-07-03 00:00:00 strategy [INFO] BUY at $36.94 2000-07-05 00:00:00 strategy [INFO] SELL at $34.97 2000-07-21 00:00:00 strategy [INFO] BUY at $35.26 2000-07-24 00:00:00 strategy [INFO] SELL at $35.12 2000-07-26 00:00:00 strategy [INFO] BUY at $34.06 2000-07-28 00:00:00 strategy [INFO] SELL at $34.21 2000-08-01 00:00:00 strategy [INFO] BUY at $34.24 2000-08-02 00:00:00 strategy [INFO] SELL at $33.24 2000-08-04 00:00:00 strategy [INFO] BUY at $35.66 2000-09-11 00:00:00 strategy [INFO] SELL at $39.19 2000-09-29 00:00:00 strategy [INFO] BUY at $37.05 2000-10-02 00:00:00 strategy [INFO] SELL at $36.31 2000-10-20 00:00:00 strategy [INFO] BUY at $32.90 2000-10-31 00:00:00 strategy [INFO] SELL at $29.72 2000-11-20 00:00:00 strategy [INFO] BUY at $22.14 2000-11-21 00:00:00 strategy [INFO] SELL at $22.59 2000-12-01 00:00:00 strategy [INFO] BUY at $24.02 2000-12-15 00:00:00 strategy [INFO] SELL at $26.81 2000-12-18 00:00:00 strategy [INFO] BUY at $27.32 2000-12-21 00:00:00 strategy [INFO] SELL at $25.33 2000-12-22 00:00:00 strategy [INFO] BUY at $27.67 Final portfolio value: $974.87 ``` -------------------------------- ### Sample CSV Data Output Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/_sources/tutorial.txt This is an example of the expected output when running the simple strategy that prints closing prices. It shows the date and closing price for each processed bar. ```text Date: 2000-12-29 00:00:00, Close: 29.06 Date: 2000-12-28 00:00:00, Close: 31.06 Date: 2000-12-27 00:00:00, Close: 30.69 Date: 2000-12-26 00:00:00, Close: 30.94 Date: 2000-12-22 00:00:00, Close: 31.88 Date: 2000-12-21 00:00:00, Close: 29.50 Date: 2000-12-20 00:00:00, Close: 28.50 Date: 2000-12-19 00:00:00, Close: 30.63 Date: 2000-12-18 00:00:00, Close: 32.00 Done! ``` -------------------------------- ### SMA Crossover Strategy Example Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/_sources/stratanalyzer.txt This Python script demonstrates a Simple Moving Average (SMA) crossover strategy. It requires the pyalgotrade library and is intended to be used with a strategy analyzer. ```python from pyalgotrade import strategy from pyalgotrade.technical import ma class SMACrossover(strategy.Strategy): def __init__(self, feed, short_window, long_window): super(SMACrossover, self).__init__(feed) self.__feed = feed self.__position = None self.__sma_short = ma.SMA(feed.get_bars(), short_window) self.__sma_long = ma.SMA(feed.get_bars(), long_window) def onBars(self, bars): if self.__sma_long[-1] is None: return bar = bars.getBar(self.__feed.bars.getCurrencies()[0]) if self.__position is None: if self.__sma_short > self.__sma_long: self.__position = self.enterLong(bar.getClose(), 1) elif not self.__position.is_open(): if self.__sma_short < self.__sma_long: self.__position.close() self.__position = self.enterLong(bar.getClose(), 1) ``` -------------------------------- ### Main Function for Twitter Feed Setup Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/twitter_example.html This function sets up the Twitter feed with provided API credentials and configures a live bar feed and paper trading broker. It's crucial to add the twitterFeed to the dispatcher before running the strategy. ```python def main(): # Go to http://dev.twitter.com and create an app. # The consumer key and secret will be generated for you after that. consumer_key = "" consumer_secret = "" # After the step above, you will be redirected to your app's page. # Create an access token under the the "Your access token" section access_token = "" access_token_secret = "" # Create a twitter feed to track BitCoin related events. track = ["bitcoin", "btc", "mtgox", "bitstamp", "xapo"] follow = [] languages = ["en"] twitterFeed = twitterfeed.TwitterFeed(consumer_key, consumer_secret, access_token, access_token_secret, track, follow, languages) barFeed = barfeed.LiveTradeFeed() brk = broker.PaperTradingBroker(1000, barFeed) strat = Strategy(barFeed, brk, twitterFeed) # It is VERY important to add twitterFeed to the event dispatch loop before running the strategy. strat.getDispatcher().addSubject(twitterFeed) strat.run() if __name__ == "__main__": main() ``` -------------------------------- ### Custom Accumulator Filter Example Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/technical.html Demonstrates how to combine EventWindow and EventBasedFilter to create a custom filter that sums values in a moving window. Ensure enough values are appended to the underlying DataSeries before accessing results. ```python from __future__ import print_function from pyalgotrade import dataseries from pyalgotrade import technical # An EventWindow is responsible for making calculations using a window of values. class Accumulator(technical.EventWindow): def getValue(self): ret = None if self.windowFull(): ret = self.getValues().sum() return ret # Build a sequence based DataSeries. seqDS = dataseries.SequenceDataSeries() # Wrap it with a filter that will get fed as new values get added to the underlying DataSeries. accum = technical.EventBasedFilter(seqDS, Accumulator(3)) # Put in some values. for i in range(0, 50): seqDS.append(i) # Get some values. print(accum[0]) # Not enough values yet. print(accum[1]) # Not enough values yet. print(accum[2]) # Ok, now we should have at least 3 values. print(accum[3]) # Get the last value, which should be equal to 49 + 48 + 47. print(accum[-1]) ``` -------------------------------- ### Strategy with SMA Calculation in pyalgotrade Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/tutorial.html This example extends a basic strategy to include a 15-period Simple Moving Average (SMA) calculated on closing prices. Note that the first 14 SMA values will be None as they require sufficient historical data. ```python from pyalgotrade import strategy from pyalgotrade.barfeed import quandlfeed from pyalgotrade.technical import ma def safe_round(value, digits): if value is not None: value = round(value, digits) return value class MyStrategy(strategy.BacktestingStrategy): def __init__(self, feed, instrument): super(MyStrategy, self).__init__(feed) # We want a 15 period SMA over the closing prices. self.__sma = ma.SMA(feed[instrument].getCloseDataSeries(), 15) self.__instrument = instrument def onBars(self, bars): bar = bars[self.__instrument] self.info("%s %s" % (bar.getClose(), safe_round(self.__sma[-1], 2))) # Load the bar feed from the CSV file feed = quandlfeed.Feed() feed.addBarsFromCSV("orcl", "WIKI-ORCL-2000-quandl.csv") # Evaluate the strategy with the feed's bars. myStrategy = MyStrategy(feed, "orcl") myStrategy.run() ``` -------------------------------- ### Event Profiler Analysis Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/_sources/eventprofiler.txt This section details the usage of the event profiler module, inspired by QSTK, to analyze the statistical impact of events on equity prices. It includes an example of the 'Buy-on-Gap Model' and explains the steps involved in running the analysis and interpreting the results. ```APIDOC ## Event Profiler Module ### Description The **eventprofiler** module is a tool designed to statistically analyze how specific events affect future equity prices. It scans historical data for a given event and calculates its impact on equity prices over a defined lookback period, both historically and in the future. This tool is intended to help validate trading ideas quickly before proceeding with backtesting. ### Example: Buy-on-Gap Model This example demonstrates the 'Buy-on-Gap Model' inspired by Ernie Chan's book 'Algorithmic Trading: Winning Strategies and Their Rationale'. The model identifies stocks that have 'gapped down' (returns from previous day's low to today's open are lower than one standard deviation of the last 90 days' close-to-close returns) and whose open price is higher than the 20-day moving average of the closing price. #### Steps: 1. **Declare a :class:`Predicate`**: Implement the 'Buy-on-Gap Model' event identification logic. 2. **Load Bars**: Load historical price data for selected stocks. 3. **Run Analysis**: Execute the event profiling analysis. 4. **Plot Results**: Visualize the analysis outcomes. **Note**: Cumulative returns are normalized to the time of the event. ### Output Visualization An example output image (`../samples/eventstudy.png`) and a sample output log (`../samples/eventstudy.output`) are provided to illustrate the expected results of the analysis. ``` -------------------------------- ### Initialize and Run Strategy Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/tutorial.html Instantiate your custom strategy with a data feed and ticker, then execute the strategy's run method. Ensure the data feed and ticker are correctly configured before initialization. ```python myStrategy = MyStrategy(feed, "orcl") myStrategy.run() ``` -------------------------------- ### Run Buy-on-Gap Strategy Analysis in Python Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/eventprofiler.html Loads stock data, initializes the BuyOnGap predicate and event profiler, runs the analysis, and prints the number of events found. Optionally plots the results if `plot` is True. Requires the quandl and pyalgotrade.eventprofiler modules. ```python def main(plot): instruments = ["IBM", "AES", "AIG"] feed = quandl.build_feed("WIKI", instruments, 2008, 2009, ".") predicate = BuyOnGap(feed) eventProfiler = eventprofiler.Profiler(predicate, 5, 5) eventProfiler.run(feed, True) results = eventProfiler.getResults() print("%d events found" % (results.getEventCount())) if plot: eventprofiler.plot(results) if __name__ == "__main__": main(True) ``` -------------------------------- ### onOrderFilled Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/broker.html Override (optional) to get notified when an order was filled, or partially filled. ```APIDOC ## onOrderFilled(broker, order) ### Description Override (optional) to get notified when an order was filled, or partially filled. ### Parameters #### Path Parameters - **broker** (Broker) - Required - The broker. - **order** (pyalgotrade.broker.Order) - Required - The order filled. ``` -------------------------------- ### onBars Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/broker.html Override (optional) to get notified when the broker is about to process new bars. ```APIDOC ## onBars(broker, bars) ### Description Override (optional) to get notified when the broker is about to process new bars. ### Parameters #### Path Parameters - **broker** (Broker) - Required - The broker. - **bars** (pyalgotrade.bar.Bars) - Required - The current bars. ``` -------------------------------- ### Sample Strategy Analyzer Usage Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/_sources/stratanalyzer.txt This Python script shows how to use strategy analyzers with a trading strategy. It initializes a strategy, attaches analyzers, and runs the backtest. Save this code in a separate file from your strategy. ```python from pyalgotrade import strategy from pyalgotrade.technical import ma from pyalgotrade.stratanalyzer import returns, sharpe, drawdown, trades class SMACrossover(strategy.Strategy): def __init__(self, feed, short_window, long_window): super(SMACrossover, self).__init__(feed) self.__feed = feed self.__position = None self.__sma_short = ma.SMA(feed.get_bars(), short_window) self.__sma_long = ma.SMA(feed.get_bars(), long_window) def onBars(self, bars): if self.__sma_long[-1] is None: return bar = bars.getBar(self.__feed.bars.getCurrencies()[0]) if self.__position is None: if self.__sma_short > self.__sma_long: self.__position = self.enterLong(bar.getClose(), 1) elif not self.__position.is_open(): if self.__sma_short < self.__sma_long: self.__position.close() self.__position = self.enterLong(bar.getClose(), 1) def main(broker, values): feed = quandl.Feed( values, [quandl.QuandlDownloader.TICKER_SYMBOL], ['2010-01-01'], ['2010-12-31'] ) sma_crossover = SMACrossover(feed, 5, 15) returns_analyzer = returns.Returns() sma_crossover.addAnalyzer(returns_analyzer) sharpe_ratio_analyzer = sharpe.SharpeRatio() sma_crossover.addAnalyzer(sharpe_ratio_analyzer) draw_down_analyzer = drawdown.DrawDown() sma_crossover.addAnalyzer(draw_down_analyzer) trades_analyzer = trades.Trades() sma_crossover.addAnalyzer(trades_analyzer) broker.add_strategy(sma_crossover) broker.add_analyzer(returns_analyzer) broker.add_analyzer(sharpe_ratio_analyzer) broker.add_analyzer(draw_down_analyzer) broker.add_analyzer(trades_analyzer) broker.run(sma_crossover, feed) broker.join() print("Final portfolio value: $%.2f" % broker.get_portfolio_value()) print("Returns: %.2f%%" % (returns_analyzer.get_returns()[-1] * 100)) print("Sharpe ratio: %.2f" % sharpe_ratio_analyzer.get_sharpe_ratio(0.05)) # Assuming risk-free rate of 5%. print("Max drawdown: %.2f%%" % (draw_down_analyzer.get_max_drawdown() * 100)) print("Total trades: %d" % trades_analyzer.get_execs_count()) ``` -------------------------------- ### Basic Strategy Execution in pyalgotrade Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/tutorial.html This snippet shows the fundamental steps of defining a strategy, loading a data feed, and running the backtest. Ensure the 'MyStrategy' class is defined with an '_onBars_' method. ```python from pyalgotrade import strategy from pyalgotrade.barfeed import quandlfeed class MyStrategy(strategy.BacktestingStrategy): def __init__(self, feed, instrument): super(MyStrategy, self).__init__(feed) self.__instrument = instrument def onBars(self, bars): bar = bars[self.__instrument] self.info("%s" % bar.getClose()) # Load the bar feed from the CSV file feed = quandlfeed.Feed() feed.addBarsFromCSV("orcl", "WIKI-ORCL-2000-quandl.csv") # Evaluate the strategy with the feed's bars. myStrategy = MyStrategy(feed, "orcl") myStrategy.run() ``` -------------------------------- ### On Bars Notification Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/broker.html Override (optional) to get notified when the broker is about to process new bars. ```python onBars(_broker__ , _bars_) ``` -------------------------------- ### Download financial data with Quandl Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/_sources/compinvpart1.txt Use these commands to download daily stock data for specific tickers from Quandl for the year 2011. ```bash python -m "pyalgotrade.tools.quandl" --source-code="WIKI" --table-code="IBM" --from-year=2011 --to-year=2011 --storage=. --force-download --frequency=daily python -m "pyalgotrade.tools.quandl" --source-code="WIKI" --table-code="AES" --from-year=2011 --to-year=2011 --storage=. --force-download --frequency=daily python -m "pyalgotrade.tools.quandl" --source-code="WIKI" --table-code="AIG" --from-year=2011 --to-year=2011 --storage=. --force-download --frequency=daily python -m "pyalgotrade.tools.quandl" --source-code="WIKI" --table-code="ORCL" --from-year=2011 --to-year=2011 --storage=. --force-download --frequency=daily ``` -------------------------------- ### Build and Attach Strategy Analyzers Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/sample_market_timing.html Constructs the MarketTiming strategy, attaches Sharpe Ratio and Returns analyzers, and sets up plotting if enabled. The strategy requires a data feed and initial cash. ```python # Build the strategy and attach some metrics. strat = MarketTiming(feed, instrumentsByClass, initialCash) sharpeRatioAnalyzer = sharpe.SharpeRatio() strat.attachAnalyzer(sharpeRatioAnalyzer) returnsAnalyzer = returns.Returns() strat.attachAnalyzer(returnsAnalyzer) ``` -------------------------------- ### CSV Feed Output Example Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/feed.html The expected output format when iterating over a loaded CSV feed. ```text 1968-04-07 00:00:00 {'USD': 37.0, 'GBP': 15.3875, 'EUR': ''} 1968-04-14 00:00:00 {'USD': 38.0, 'GBP': 15.8208, 'EUR': ''} 1968-04-21 00:00:00 {'USD': 37.65, 'GBP': 15.6833, 'EUR': ''} 1968-04-28 00:00:00 {'USD': 38.65, 'GBP': 16.1271, 'EUR': ''} 1968-05-05 00:00:00 {'USD': 39.1, 'GBP': 16.3188, 'EUR': ''} 1968-05-12 00:00:00 {'USD': 39.6, 'GBP': 16.5625, 'EUR': ''} 1968-05-19 00:00:00 {'USD': 41.5, 'GBP': 17.3958, 'EUR': ''} 1968-05-26 00:00:00 {'USD': 41.75, 'GBP': 17.5104, 'EUR': ''} 1968-06-02 00:00:00 {'USD': 41.95, 'GBP': 17.6, 'EUR': ''} 1968-06-09 00:00:00 {'USD': 41.25, 'GBP': 17.3042, 'EUR': ''} . . . 2013-07-28 00:00:00 {'USD': 1331.0, 'GBP': 864.23, 'EUR': 1001.505} 2013-08-04 00:00:00 {'USD': 1309.25, 'GBP': 858.637, 'EUR': 986.921} 2013-08-11 00:00:00 {'USD': 1309.0, 'GBP': 843.156, 'EUR': 979.79} 2013-08-18 00:00:00 {'USD': 1369.25, 'GBP': 875.424, 'EUR': 1024.964} 2013-08-25 00:00:00 {'USD': 1377.5, 'GBP': 885.738, 'EUR': 1030.6} 2013-09-01 00:00:00 {'USD': 1394.75, 'GBP': 901.292, 'EUR': 1055.749} 2013-09-08 00:00:00 {'USD': 1387.0, 'GBP': 886.885, 'EUR': 1052.911} 2013-09-15 00:00:00 {'USD': 1318.5, 'GBP': 831.546, 'EUR': 993.969} 2013-09-22 00:00:00 {'USD': 1349.25, 'GBP': 842.755, 'EUR': 997.671} 2013-09-29 00:00:00 {'USD': 1333.0, 'GBP': 831.203, 'EUR': 986.75} ``` -------------------------------- ### Bitstamp Strategy Implementation Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/_sources/bitstamp_example.txt This script demonstrates a simple SMA crossover strategy using realtime feeds from Bitstamp. ```python .. literalinclude:: ../samples/tutorial_bitstamp_1.py ``` -------------------------------- ### On Order Filled Notification Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/broker.html Override (optional) to get notified when an order was filled, or partially filled. ```python onOrderFilled(_broker__ , _order_) ``` -------------------------------- ### Bitstamp Strategy Output Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/_sources/bitstamp_example.txt Example log output showing order book updates and trade signals. ```text 2014-03-15 00:35:59,085 bitstamp [INFO] Initializing websocket client. 2014-03-15 00:35:59,452 bitstamp [INFO] Connection established. 2014-03-15 00:35:59,453 bitstamp [INFO] Initialization ok. 2014-03-15 00:36:30,726 strategy [INFO] Order book updated. Best bid: 629.6. Best ask: 630.0 2014-03-15 00:39:04,829 strategy [INFO] Order book updated. Best bid: 628.89. Best ask: 630.0 2014-03-15 00:44:18,845 strategy [INFO] Price: 630.0. Volume: 0.01. 2014-03-15 00:44:18,894 strategy [INFO] Order book updated. Best bid: 630.0. Best ask: 631.49 2014-03-15 00:44:29,719 strategy [INFO] Price: 630.0. Volume: 0.02. 2014-03-15 00:44:59,861 strategy [INFO] Price: 631.49. Volume: 0.03360823. 2014-03-15 00:45:37,425 strategy [INFO] Order book updated. Best bid: 630.0. Best ask: 631.6 2014-03-15 00:45:39,848 strategy [INFO] Price: 631.6. Volume: 3.35089782. 2014-03-15 00:45:39,918 strategy [INFO] Price: 632.24. Volume: 0.136. 2014-03-15 00:45:39,971 strategy [INFO] Price: 632.24. Volume: 0.138. 2014-03-15 00:45:40,057 strategy [INFO] Price: 632.25. Volume: 0.09076537. 2014-03-15 00:45:40,104 strategy [INFO] Price: 632.42. Volume: 0.74011681. 2014-03-15 00:45:40,205 strategy [INFO] Order book updated. Best bid: 630.0. Best ask: 632.42 2014-03-15 00:48:30,005 strategy [INFO] Price: 630.0. Volume: 4.97. 2014-03-15 00:48:30,039 strategy [INFO] Price: 629.6. Volume: 0.09. 2014-03-15 00:48:30,121 strategy [INFO] Price: 629.54. Volume: 0.09. . . . 2014-03-15 00:48:33,053 strategy [INFO] Price: 625.55. Volume: 1.296299. 2014-03-15 00:48:33,164 strategy [INFO] Price: 625.52. Volume: 0.0924981. 2014-03-15 00:48:33,588 strategy [INFO] Price: 625.45. Volume: 13.46260589. 2014-03-15 00:48:33,635 strategy [INFO] Order book updated. Best bid: 629.26. Best ask: 632.42 2014-03-15 00:48:33,727 strategy [INFO] Price: 625.45. Volume: 1.75. 2014-03-15 00:48:34,261 strategy [INFO] Price: 625.48. Volume: 0.1. 2014-03-15 00:48:34,908 strategy [INFO] Order book updated. Best bid: 629.26. Best ask: 631.39 2014-03-15 00:48:36,203 strategy [INFO] Order book updated. Best bid: 629.26. Best ask: 632.42 . . . 2014-03-15 00:49:01,945 strategy [INFO] Order book updated. Best bid: 629.26. Best ask: 631.39 2014-03-15 00:49:34,743 strategy [INFO] Order book updated. Best bid: 629.26. Best ask: 631.28 2014-03-15 00:49:57,651 strategy [INFO] Price: 629.26. Volume: 0.66893865. 2014-03-15 00:49:57,651 strategy [INFO] Entry signal. Buy at 631.28 2014-03-15 00:50:09,934 strategy [INFO] Order book updated. Best bid: 629.26. Best ask: 631.39 2014-03-15 00:50:20,786 strategy [INFO] Order book updated. Best bid: 627.02. Best ask: 631.39 2014-03-15 00:50:25,658 strategy [INFO] Price: 631.39. Volume: 0.01. 2014-03-15 00:50:25,732 strategy [INFO] Price: 631.39. Volume: 0.01. 2014-03-15 00:50:25,791 strategy [INFO] Price: 631.93. Volume: 0.5. 2014-03-15 00:50:25,847 strategy [INFO] Price: 632.42. Volume: 0.25988319. 2014-03-15 00:50:25,900 strategy [INFO] Price: 632.42. Volume: 0.184. 2014-03-15 00:50:25,952 strategy [INFO] Price: 632.42. Volume: 0.184. 2014-03-15 00:50:26,000 strategy [INFO] Price: 632.42. Volume: 0.184. 2014-03-15 00:50:26,065 strategy [INFO] Price: 632.44. Volume: 0.184. 2014-03-15 00:50:26,139 strategy [INFO] Price: 632.97. Volume: 0.092. 2014-03-15 00:50:26,300 strategy [INFO] Order book updated. Best bid: 627.02. Best ask: 629.0 2014-03-15 00:50:26,398 strategy [INFO] Price: 633.1. Volume: 0.16211681. 2014-03-15 00:50:29,850 strategy [INFO] Position opened at 629.0 2014-03-15 00:50:29,850 strategy [INFO] Price: 629.0. Volume: 0.25152623. 2014-03-15 00:50:29,850 strategy [INFO] Exit signal. Sell at 627.02 2014-03-15 00:50:37,294 strategy [INFO] Order book updated. Best bid: 627.02. Best ask: 633.1 ``` -------------------------------- ### Resampled CSV data format Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/_sources/bitcoincharts_example.txt Example of the expected CSV structure after resampling trade data into 30-minute bars. ```csv Date Time,Open,High,Low,Close,Volume,Adj Close 2014-01-01 00:00:00,732.0,738.25,729.01,734.81,266.17955488, 2014-01-01 00:30:00,734.81,739.9,734.47,739.02,308.96802502, 2014-01-01 01:00:00,739.02,739.97,737.65,738.11,65.66924473, 2014-01-01 01:30:00,738.0,742.0,737.65,741.89,710.27165024, 2014-01-01 02:00:00,741.89,757.99,741.89,752.23,1085.13335011, 2014-01-01 02:30:00,752.23,755.0,747.0,747.2,272.03949342, 2014-01-01 04:00:00,744.98,748.02,744.98,747.19,104.65989075, . . ``` -------------------------------- ### Implement and Plot VWAP Momentum Strategy Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/bitcoincharts_example.html This snippet demonstrates how to load historical data from a CSV file, initialize a backtesting broker, and set up a VWAP Momentum strategy. It includes optional plotting of the strategy's VWAP data using StrategyPlotter. Ensure the necessary libraries and data files are available. ```python barFeed.addBarsFromCSV(instrument, "30min-bitstampUSD.csv") brk = broker.BacktestingBroker(initialCash, barFeed) strat = VWAPMomentum(barFeed, brk, instrument, vwapWindowSize, buyThreshold, sellThreshold) if plot: plt = plotter.StrategyPlotter(strat) plt.getInstrumentSubplot(instrument).addDataSeries("VWAP", strat.getVWAP()) strat.run() if plot: plt.plot() ``` -------------------------------- ### Returns Analyzer Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/stratanalyzer.html Calculates time-weighted returns for the whole portfolio. It provides methods to get cumulative returns and bar-by-bar returns. ```APIDOC ## Class: pyalgotrade.stratanalyzer.returns.Returns ### Description A `pyalgotrade.stratanalyzer.StrategyAnalyzer` that calculates time-weighted returns for the whole portfolio. ### Parameters * **maxLen** (int) - Optional - The maximum number of values to hold in net and cumulative returns dataseries. If None then dataseries.DEFAULT_MAX_LEN is used. ### Methods * `getCumulativeReturns()`: Returns a `pyalgotrade.dataseries.DataSeries` with the cumulative returns for each bar. * `getReturns()`: Returns a `pyalgotrade.dataseries.DataSeries` with the returns for each bar. ``` -------------------------------- ### Loading CSV Data with PyAlgoTrade Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/feed.html Demonstrates initializing a CSV feed and iterating through the loaded data. ```python from __future__ import print_function from pyalgotrade.feed import csvfeed feed = csvfeed.Feed("Date", "%Y-%m-%d") feed.addValuesFromCSV("quandl_gold_2.csv") for dateTime, value in feed: print(dateTime, value) ``` -------------------------------- ### Strategy Lifecycle and Event Handlers Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/strategy.html Methods that can be overridden to handle strategy execution events such as start, finish, and bar updates. ```APIDOC ## onStart() ### Description Override to get notified when the strategy starts executing. ## onFinish(bars) ### Description Override to get notified when the strategy finished executing. ### Parameters #### Path Parameters - **bars** (pyalgotrade.bar.Bars) - Required - The last bars processed. ## onBars(bars) ### Description Mandatory override to get notified when new bars are available. This is the primary method for trading logic. ### Parameters #### Path Parameters - **bars** (pyalgotrade.bar.Bars) - Required - The current bars. ``` -------------------------------- ### Market Timing Strategy Output Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/_sources/sample_market_timing.txt This is the expected output from the market timing strategy example. It shows the total return calculated by the strategy. ```text Total return 1.234567 ``` -------------------------------- ### TA-Lib Bollinger Bands with pyalgotrade DataSeries Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/talib.html Demonstrates using TA-Lib's BBANDS function with a pyalgotrade DataSeries for closing prices. Ensure the DataSeries is available and has enough data points. ```python def onBars(self, bars): closeDs = self.getFeed().getDataSeries("orcl").getCloseDataSeries() upper, middle, lower = pyalgotrade.talibext.indicator.BBANDS(closeDs, 100, matype=talib.MA_T3) if upper != None: print "%s" % upper[-1] ``` -------------------------------- ### Get Simple Moving Average Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/sample_market_timing.html Retrieves the Simple Moving Average (SMA) for a given instrument from the strategy's internal storage. ```python def getSMA(self, instrument): return self.__sma[instrument] ``` -------------------------------- ### Execute and Plot Strategy Source: http://gbeced.github.io/pyalgotrade/docs/v0.20/html/tutorial.html Configures the data feed, attaches analyzers, and initializes the plotter to visualize the strategy results. ```python from pyalgotrade import plotter from pyalgotrade.barfeed import quandlfeed from pyalgotrade.stratanalyzer import returns import sma_crossover # Load the bar feed from the CSV file feed = quandlfeed.Feed() feed.addBarsFromCSV("orcl", "WIKI-ORCL-2000-quandl.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() ```