【问题标题】:Conditions True and false and I get None value条件真假,我得到无值
【发布时间】:2021-05-31 18:16:13
【问题描述】:

这是我的数据

!pip install yfinance
import yfinance as yf
from pandas_datareader import data
import matplotlib.pyplot as plt
import pandas as pd
import datetime as dt
import urllib.request, json
import os
import numpy as np
data=yf.download('AAPL', period='max', interval='5d' )
# find the log return which is equal to log(1+ri)
data['LogReturn'] = np.log(data['Close']).diff()
data['LogReturn'] = data['LogReturn'].shift(-1)
Fast=10
Slow=30
data['SlowSMA'] = data['Close'].rolling(Slow).mean()
data['FastSMA'] = data['Close'].rolling(Fast).mean()
data['Signal']=np.where(data['FastSMA'] >= data['SlowSMA'], 1, 0)
data['PrevSignal']=data['Signal'].shift(1)
data['Buy'] = (data['PrevSignal'] == 0) & (data['Signal'] == 1)
data['Sell'] = (data['PrevSignal'] == 1) & (data['Signal'] == 0)

def assign_is_invested(row): ## we will look at each row 
  global is_invested # we can change it outside the function 
  if is_invested and row['Sell']:
    is_invested=False
  if not is_invested and row['Buy']:
    is_invested=True
    return is_invested 
data['IsInvested'] = data.apply(assign_is_invested, axis=1)

当我运行上述函数以获取 IsInvested 列 None 并且我期待 True 或 False。这是为什么呢?

【问题讨论】:

    标签: pandas dataframe numpy


    【解决方案1】:

    我认为问题在于返回的缩进。

    is_invested= False # we are not invested yet no money  
    
    def assign_is_invested(row): ## we will look at each row 
      global is_invested # we can change it outside the function 
      if is_invested and row['Sell']:
        is_invested=False
      if not is_invested and row['Buy']:
        is_invested=True
      return is_invested
    
    data['IsInvested'] = data.apply(assign_is_invested, axis=1)
    

    如果数据与第二个 IF 语句中的条件匹配,则该函数仅返回 is_invested 变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-06
      • 1970-01-01
      • 1970-01-01
      • 2023-01-08
      • 1970-01-01
      相关资源
      最近更新 更多