2017-11-24 3 views
0

저는 Python 초보자이며 간단한 이동 평균 전략을위한 함수를 작성했습니다. 함수 내에서 DataFrame 포트폴리오를 만들었으니 이제는이 그래프를 그래프로 그려주는 함수 밖에이 DataFrame을 사용하고 싶습니다. 내 솔루션은 : 포트폴리오 반환 -하지만이 작동하지 않습니다. 아무도 나를 도울 수 있습니까? 당신은 변수에 함수의 반환 값을 할당해야함수 밖의 함수 안에 생성 된 pandas DataFrame 사용

import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt 

# Import a data source - FSE-Data with Index 'Date' 
all_close_prices = pd.read_csv('FSE_daily_close.csv') 
all_close_prices = all_close_prices.set_index('Date') 
# Fill NaN Values with the last available stock price - except for Zalando 
all_close_prices = all_close_prices.fillna(method='ffill') 
# Import ticker symbols 
ticker_list = list(all_close_prices) 
# Zalando 'FSE/ZO1_X' (position row 99) - doesn't begin in 2004 
# Drop Zalando 
all_close_prices.drop('FSE/ZO1_X', axis=1) 
# Also from the ticker list 
ticker_list.remove('FSE/ZO1_X') 
# Create an empty signal dataframe with datetime index equivalent to the stocks 
signals = pd.DataFrame(index=all_close_prices.index) 

def ma_strategy(ticker, long_window, short_window): 
    # Calculate the moving avergaes 
    moving_avg_long = all_close_prices.rolling(window=long_window, min_periods=1).mean() 
    moving_avg_short = all_close_prices.rolling(window=short_window, min_periods=1).mean() 
    moving_avg_short = moving_avg_short 
    moving_avg_long = moving_avg_long 
    # Add the two MAs for the stocks in the ticker_list to the signals dataframe 
    for i in ticker_list: 
     signals['moving_avg_short_' + i] = moving_avg_short[i] 
     signals['moving_avg_long_' + i] = moving_avg_long[i] 

    # Set up the signals 
    for i in ticker_list: 
     signals['signal_' + i] = np.where(signals['moving_avg_short_' + i] > signals['moving_avg_long_' + i], 1, 0) 
     signals['positions_' + i] = signals['signal_' + i].diff(periods=1) 
    #Backtest 
    initial_capital = float(100000) 
    # Create a DataFrame `positions` with index of signals 
    positions = pd.DataFrame(index=all_close_prices) 
    # Create a new column in the positions DataFrame 
    # On the days that the signal is 1 (short moving average crosses the long moving average, you’ll buy a 100 shares. 
    # The days on which the signal is 0, the final result will be 0 as a result of the operation 100*signals['signal'] 
    positions = 100 * signals[['signal_' + ticker]] 
    # Store the portfolio value owned with the stock 
    # DataFrame.multiply(other, axis='columns', fill_value=None) - Multiplication of dataframe and other, element-wise 
    # Store the difference in shares owned - same like position column in signals 
    pos_diff = positions.diff() 
    # Add `holdings` to portfolio 
    portfolio = pd.DataFrame(index=all_close_prices.index) 
    portfolio['holdings'] = (positions.multiply(all_close_prices[ticker], axis=0)).sum(axis=1) 
    # Add `cash` to portfolio 
    portfolio['cash'] = initial_capital - (pos_diff.multiply(all_close_prices[ticker], axis=0)).sum(
     axis=1).cumsum() 
    # Add `total` to portfolio 
    portfolio['total'] = portfolio['cash'] + portfolio['holdings'] 
    # Add `returns` to portfolio 
    portfolio['return'] = portfolio['total'].pct_change() 
    portfolio['return_cum'] = portfolio['total'].pct_change().cumsum() 
    return portfolio 


ma_strategy('FSE/VOW3_X',20,5) 

# Visualize the total value of the portfolio 
portfolio_value = plt.figure(figsize=(12, 8)) 
ax1 = portfolio_value.add_subplot(1, 1, 1, ylabel='Portfolio value in $') 
# Plot the equity curve in dollars 
portfolio['total'].plot(ax=ax1, lw=2.) 
+0

니스 코드로 변경해야합니다. 그러나 나는 당신의 데이터의 몇 줄을 보는 것에 더 관심이있다. –

+0

신뢰할 수있는 무료 데이터 소스가 필요하면 Quandl :)을 사용할 수 있습니다. 내 FSE 데이터는 데이터베이스에서 가져온 것입니다. – Tom

+1

나는 당신이 오해했다고 생각합니다. :/귀하의 현재 데이터 및 예상 결과를보고 싶습니다. –

답변

0

:

내 코드입니다.

ma_strategy('FSE/VOW3_X',20,5) 

을 말한다 선은 아마

portfolio = ma_strategy('FSE/VOW3_X',20,5) 
+0

감사합니다! 그게 잘 작동합니다 : – Tom

+0

@ 톰 당신이 대답을뿐만 아니라 (즉, 왼쪽에있는 눈금 기호를 클릭) 받아 주시면 감사하겠습니다 –

관련 문제