function to backtest cryptocurrency prices given a input stratagy in python

tags: Python, cryptocurrencies, backtesting, strategy development, technical analysis

import pandas as pd import numpy as np import ccxt # for fetching cryptocurrency market data

def backtest_crypto(strategy, symbol, start_date, end_date): """ Function to backtest a cryptocurrency trading strategy :param strategy: a callable function that takes two arguments - historical prices and current price The function should return a boolean indicating whether to buy or sell :param symbol: cryptocurrency symbol to test (e.g. 'BTC/USDT') :param start_date: start date of historical data to be fetched (format 'YYYY-MM-DD') :param end_date: end date of historical data to be fetched (format 'YYYY-MM-DD') :return: DataFrame containing the backtesting results """ # initialize exchange API exchange = ccxt.binance() exchange.load_markets()

main.py
# fetch historical data
ohlcvs = exchange.fetch_ohlcv(symbol, '1d', exchange.parse8601(start_date), exchange.parse8601(end_date))
df = pd.DataFrame(ohlcvs, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])

# convert timestamp to date
df['date'] = pd.to_datetime(df['timestamp'], unit='ms')
df = df[['date', 'open', 'high', 'low', 'close', 'volume']]
df.set_index('date', inplace=True)

# calculate technical indicators (add your own)
df['SMA'] = df['close'].rolling(20).mean()  # simple moving average
df['RSI'] = ta.RSI(df['close'], timeperiod=14)  # relative strength index

# initialize account balance and position
balance = 10000  # starting balance
position = 0  # starting position
results = []  # store backtesting results

# loop through historical data and apply trading strategy
for i in range(1, len(df)):
    historical_prices = df.iloc[:i]  # historical prices up to current point
    current_price = df.iloc[i]['close']  # current price
    signal = strategy(historical_prices, current_price)  # get trading signal from strategy

    if signal == 'buy' and balance > 0:
        # buy position
        position = balance / current_price
        balance = 0
    elif signal == 'sell' and position > 0:
        # sell position
        balance = position * current_price
        position = 0

    # calculate portfolio value
    portfolio_value = balance + position * current_price
    results.append(portfolio_value)

# calculate backtesting metrics
returns = np.diff(results) / results[:-1]
sharpe = (np.mean(returns) / np.std(returns)) * np.sqrt(365)
total_return = (results[-1] / results[0]) - 1

# create DataFrame of results
backtest_results = pd.DataFrame({'date': df.index[1:], 'portfolio_value': results[:-1], 'returns': returns,
                                 'sharpe_ratio': sharpe, 'total_return': total_return})
backtest_results.set_index('date', inplace=True)

return backtest_results
1928 chars
49 lines
main.py

The function `backtest_crypto` takes in a strategy function, cryptocurrency symbol, start and end dates, and returns the backtesting results as a pandas DataFrame. 

The strategy function `strategy(historical_prices, current_price)` is a function that takes in two arguments:
- `historical_prices`: A DataFrame containing the historical OHLCV data up to the current point
- `current_price`: A float representing the current price

This strategy function should return either 'buy' or 'sell' depending on the strategy. You can add any technical indicators or other conditions to this function depending on your strategy.

The function fetches historical data using the `ccxt` library, calculates technical indicators such as the simple moving average and the relative strength index, and applies the trading strategy to generate buy/sell signals. It then calculates the portfolio values and returns, and finally returns a DataFrame of the backtesting results.
960 chars
11 lines

related categories

gistlibby LogSnag